diff --git a/app/api/users/route.ts b/app/api/users/route.ts index 07afa848..c56a6f13 100644 --- a/app/api/users/route.ts +++ b/app/api/users/route.ts @@ -175,6 +175,24 @@ async function getAdminToken() { } } +// Validate username according to Keycloak requirements +function validateUsername(username: string): { isValid: boolean; error?: string } { + // Keycloak username requirements: + // - Only alphanumeric characters, dots (.), hyphens (-), and underscores (_) + // - Must start with a letter or number + // - Must be between 3 and 255 characters + const usernameRegex = /^[a-zA-Z0-9][a-zA-Z0-9._-]{2,254}$/; + + if (!usernameRegex.test(username)) { + return { + isValid: false, + error: "Le nom d'utilisateur doit commencer par une lettre ou un chiffre, ne contenir que des lettres, chiffres, points, tirets et underscores, et faire entre 3 et 255 caractères" + }; + } + + return { isValid: true }; +} + export async function POST(req: Request) { const session = await getServerSession(authOptions); @@ -186,6 +204,15 @@ export async function POST(req: Request) { const data = await req.json(); console.log("Creating user:", data); + // Validate username + const usernameValidation = validateUsername(data.username); + if (!usernameValidation.isValid) { + return NextResponse.json( + { error: usernameValidation.error }, + { status: 400 } + ); + } + const token = await getAdminToken(); if (!token) { return NextResponse.json({ error: "Erreur d'authentification" }, { status: 401 });