From 51be362dc49ae062db1f267bfc0a9baaf403e489 Mon Sep 17 00:00:00 2001 From: OpenClaw Date: Fri, 6 Mar 2026 17:45:29 +0000 Subject: [PATCH] auto(agent): added validation middleware and improved error handling in auth.js --- backend/src/routes/auth.js | 45 +++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/backend/src/routes/auth.js b/backend/src/routes/auth.js index e0a6aa0..6bb8714 100644 --- a/backend/src/routes/auth.js +++ b/backend/src/routes/auth.js @@ -17,7 +17,8 @@ const loginSchema = z.object({ password: z.string().min(1) }); -router.post('/register', async (req, res) => { +// Middleware für Validierung +const validateRegister = (req, res, next) => { try { const parsed = registerSchema.safeParse(req.body); if (!parsed.success) { @@ -26,8 +27,34 @@ router.post('/register', async (req, res) => { details: parsed.error.flatten() }); } + req.validatedData = parsed.data; + next(); + } catch (err) { + console.error('Validation error:', err); + return res.status(500).json({ error: 'Internal server error during validation' }); + } +}; - const { email, password, displayName } = parsed.data; +const validateLogin = (req, res, next) => { + try { + const parsed = loginSchema.safeParse(req.body); + if (!parsed.success) { + return res.status(400).json({ + error: 'Validation failed', + details: parsed.error.flatten() + }); + } + req.validatedData = parsed.data; + next(); + } catch (err) { + console.error('Validation error:', err); + return res.status(500).json({ error: 'Internal server error during validation' }); + } +}; + +router.post('/register', validateRegister, async (req, res) => { + try { + const { email, password, displayName } = req.validatedData; const passwordHash = await bcrypt.hash(password, 12); const [result] = await pool.query( @@ -46,17 +73,9 @@ router.post('/register', async (req, res) => { } }); -router.post('/login', async (req, res) => { +router.post('/login', validateLogin, async (req, res) => { try { - const parsed = loginSchema.safeParse(req.body); - if (!parsed.success) { - return res.status(400).json({ - error: 'Validation failed', - details: parsed.error.flatten() - }); - } - - const { email, password } = parsed.data; + const { email, password } = req.validatedData; const [rows] = await pool.query('SELECT id, email, password_hash FROM users WHERE email = ? LIMIT 1', [email]); const user = rows[0]; @@ -70,7 +89,7 @@ router.post('/login', async (req, res) => { } const token = jwt.sign({ userId: user.id, email: user.email }, process.env.JWT_SECRET, { expiresIn: '7d' }); - return res.json({ token }); + return res.status(200).json({ token }); } catch (err) { console.error('Login error:', err); return res.status(500).json({ error: 'Login failed' });