99 lines
No EOL
2.9 KiB
JavaScript
99 lines
No EOL
2.9 KiB
JavaScript
import { Router } from 'express';
|
|
import bcrypt from 'bcryptjs';
|
|
import jwt from 'jsonwebtoken';
|
|
import { z } from 'zod';
|
|
import { pool } from '../db/connection.js';
|
|
|
|
const router = Router();
|
|
|
|
const registerSchema = z.object({
|
|
email: z.string().email(),
|
|
password: z.string().min(8),
|
|
displayName: z.string().min(2).max(120)
|
|
});
|
|
|
|
const loginSchema = z.object({
|
|
email: z.string().email(),
|
|
password: z.string().min(1)
|
|
});
|
|
|
|
// Middleware für Validierung
|
|
const validateRegister = (req, res, next) => {
|
|
try {
|
|
const parsed = registerSchema.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' });
|
|
}
|
|
};
|
|
|
|
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(
|
|
'INSERT INTO users (email, password_hash, display_name) VALUES (?, ?, ?)',
|
|
[email, passwordHash, displayName]
|
|
);
|
|
|
|
const token = jwt.sign({ userId: result.insertId, email }, process.env.JWT_SECRET, { expiresIn: '7d' });
|
|
return res.status(201).json({ token });
|
|
} catch (err) {
|
|
console.error('Registration error:', err);
|
|
if (err.code === 'ER_DUP_ENTRY') {
|
|
return res.status(409).json({ error: 'Email already exists' });
|
|
}
|
|
return res.status(500).json({ error: 'Registration failed' });
|
|
}
|
|
});
|
|
|
|
router.post('/login', validateLogin, async (req, res) => {
|
|
try {
|
|
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];
|
|
|
|
if (!user) {
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
}
|
|
|
|
const ok = await bcrypt.compare(password, user.password_hash);
|
|
if (!ok) {
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
}
|
|
|
|
const token = jwt.sign({ userId: user.id, email: user.email }, process.env.JWT_SECRET, { expiresIn: '7d' });
|
|
return res.status(200).json({ token });
|
|
} catch (err) {
|
|
console.error('Login error:', err);
|
|
return res.status(500).json({ error: 'Login failed' });
|
|
}
|
|
});
|
|
|
|
export default router; |