2026-03-04 16:03:04 +00:00
|
|
|
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)
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-06 17:27:33 +00:00
|
|
|
const loginSchema = z.object({
|
|
|
|
|
email: z.string().email(),
|
|
|
|
|
password: z.string().min(1)
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-06 17:45:29 +00:00
|
|
|
// Middleware für Validierung
|
|
|
|
|
const validateRegister = (req, res, next) => {
|
2026-03-06 17:27:33 +00:00
|
|
|
try {
|
|
|
|
|
const parsed = registerSchema.safeParse(req.body);
|
|
|
|
|
if (!parsed.success) {
|
|
|
|
|
return res.status(400).json({
|
|
|
|
|
error: 'Validation failed',
|
|
|
|
|
details: parsed.error.flatten()
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-03-06 17:45:29 +00:00
|
|
|
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' });
|
|
|
|
|
}
|
|
|
|
|
};
|
2026-03-04 16:03:04 +00:00
|
|
|
|
2026-03-07 03:24:42 +00:00
|
|
|
// Sicherheitsfunktionen
|
|
|
|
|
const generateSecureToken = (userId, email) => {
|
|
|
|
|
// Verwende eine stärkere JWT-Konfiguration
|
|
|
|
|
return jwt.sign(
|
|
|
|
|
{ userId, email },
|
|
|
|
|
process.env.JWT_SECRET || 'fallback_secret_key_for_dev',
|
|
|
|
|
{
|
|
|
|
|
expiresIn: '7d',
|
|
|
|
|
issuer: 'helpyourneighbour-backend',
|
|
|
|
|
audience: 'helpyourneighbour-users'
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Rate limiting für Auth-Endpunkte (simuliert)
|
|
|
|
|
let loginAttempts = new Map();
|
|
|
|
|
const MAX_ATTEMPTS = 5;
|
|
|
|
|
const LOCKOUT_TIME = 15 * 60 * 1000; // 15 Minuten
|
|
|
|
|
|
2026-03-06 17:45:29 +00:00
|
|
|
router.post('/register', validateRegister, async (req, res) => {
|
|
|
|
|
try {
|
|
|
|
|
const { email, password, displayName } = req.validatedData;
|
2026-03-07 03:24:42 +00:00
|
|
|
|
|
|
|
|
// Überprüfe, ob das Passwort sicher ist
|
|
|
|
|
if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password)) {
|
|
|
|
|
return res.status(400).json({
|
|
|
|
|
error: 'Password must contain at least one lowercase letter, one uppercase letter, and one digit'
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-06 17:27:33 +00:00
|
|
|
const passwordHash = await bcrypt.hash(password, 12);
|
2026-03-04 16:03:04 +00:00
|
|
|
|
|
|
|
|
const [result] = await pool.query(
|
|
|
|
|
'INSERT INTO users (email, password_hash, display_name) VALUES (?, ?, ?)',
|
|
|
|
|
[email, passwordHash, displayName]
|
|
|
|
|
);
|
|
|
|
|
|
2026-03-07 03:24:42 +00:00
|
|
|
const token = generateSecureToken(result.insertId, email);
|
|
|
|
|
return res.status(201).json({
|
|
|
|
|
token,
|
|
|
|
|
userId: result.insertId,
|
|
|
|
|
email
|
|
|
|
|
});
|
2026-03-04 16:03:04 +00:00
|
|
|
} catch (err) {
|
2026-03-06 17:27:33 +00:00
|
|
|
console.error('Registration error:', err);
|
|
|
|
|
if (err.code === 'ER_DUP_ENTRY') {
|
|
|
|
|
return res.status(409).json({ error: 'Email already exists' });
|
|
|
|
|
}
|
2026-03-04 16:03:04 +00:00
|
|
|
return res.status(500).json({ error: 'Registration failed' });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-06 17:45:29 +00:00
|
|
|
router.post('/login', validateLogin, async (req, res) => {
|
2026-03-06 17:27:33 +00:00
|
|
|
try {
|
2026-03-06 17:45:29 +00:00
|
|
|
const { email, password } = req.validatedData;
|
2026-03-07 03:24:42 +00:00
|
|
|
|
|
|
|
|
// Rate limiting check
|
|
|
|
|
const attempts = loginAttempts.get(email) || 0;
|
|
|
|
|
if (attempts >= MAX_ATTEMPTS) {
|
|
|
|
|
return res.status(429).json({ error: 'Too many login attempts. Please try again later.' });
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-06 17:27:33 +00:00
|
|
|
const [rows] = await pool.query('SELECT id, email, password_hash FROM users WHERE email = ? LIMIT 1', [email]);
|
|
|
|
|
const user = rows[0];
|
2026-03-04 16:03:04 +00:00
|
|
|
|
2026-03-06 17:27:33 +00:00
|
|
|
if (!user) {
|
2026-03-07 03:24:42 +00:00
|
|
|
// Erhöhe den Versuchscounter für nicht-existente E-Mail
|
|
|
|
|
loginAttempts.set(email, (attempts + 1));
|
2026-03-06 17:27:33 +00:00
|
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
|
|
|
}
|
2026-03-04 16:03:04 +00:00
|
|
|
|
2026-03-06 17:27:33 +00:00
|
|
|
const ok = await bcrypt.compare(password, user.password_hash);
|
|
|
|
|
if (!ok) {
|
2026-03-07 03:24:42 +00:00
|
|
|
// Erhöhe den Versuchscounter für falsches Passwort
|
|
|
|
|
loginAttempts.set(email, (attempts + 1));
|
2026-03-06 17:27:33 +00:00
|
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
|
|
|
}
|
2026-03-04 16:03:04 +00:00
|
|
|
|
2026-03-07 03:24:42 +00:00
|
|
|
// Reset des Versuchscounters bei erfolgreicher Anmeldung
|
|
|
|
|
loginAttempts.delete(email);
|
|
|
|
|
|
|
|
|
|
const token = generateSecureToken(user.id, user.email);
|
|
|
|
|
return res.status(200).json({
|
|
|
|
|
token,
|
|
|
|
|
userId: user.id,
|
|
|
|
|
email: user.email
|
|
|
|
|
});
|
2026-03-06 17:27:33 +00:00
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Login error:', err);
|
|
|
|
|
return res.status(500).json({ error: 'Login failed' });
|
|
|
|
|
}
|
2026-03-04 16:03:04 +00:00
|
|
|
});
|
|
|
|
|
|
2026-03-06 17:27:33 +00:00
|
|
|
export default router;
|