auto(agent): added validation middleware and improved error handling in auth.js
This commit is contained in:
parent
4ee009a730
commit
51be362dc4
1 changed files with 32 additions and 13 deletions
|
|
@ -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' });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue