feat: add user creation endpoint with validation and error handling

This commit is contained in:
Thibault Pouch
2026-03-02 09:50:44 +01:00
parent 073dc38fd7
commit 244bea372e

View File

@@ -25,6 +25,32 @@ router.get('/', authenticate, requireAdmin, async (_req: Request, res: Response)
res.json(users.map(safeUser));
});
// POST /api/users — create a staff account (admin only)
router.post('/', authenticate, requireAdmin, async (req: Request, res: Response): Promise<void> => {
const schema = z.object({
username: z.string().min(2).max(32),
email: z.string().email(),
password: z.string().min(6),
role: z.enum(['dev', 'com']),
});
const parsed = schema.safeParse(req.body);
if (!parsed.success) { res.status(400).json({ error: parsed.error.flatten() }); return; }
const { username, email, password, role } = parsed.data;
const emailTaken = await prisma.user.findUnique({ where: { email: email.toLowerCase() } });
if (emailTaken) { res.status(409).json({ error: 'An account with this email already exists.' }); return; }
const usernameTaken = await prisma.user.findUnique({ where: { username } });
if (usernameTaken) { res.status(409).json({ error: 'This username is already taken.' }); return; }
const hashed = await bcrypt.hash(password, 10);
const user = await prisma.user.create({
data: { username, email: email.toLowerCase(), password: hashed, role },
});
res.status(201).json(safeUser(user));
});
// GET /api/users/me/profile — current user profile
router.get('/me/profile', authenticate, async (req: Request, res: Response): Promise<void> => {
const user = await prisma.user.findUnique({ where: { id: req.user!.userId } });