52 lines
2.3 KiB
JavaScript
52 lines
2.3 KiB
JavaScript
const express = require('express');
|
|
const bcrypt = require('bcryptjs');
|
|
const jwt = require('jsonwebtoken');
|
|
const db = require('../db');
|
|
const { authenticate } = require('../middleware/auth');
|
|
|
|
const router = express.Router();
|
|
const SECRET = process.env.JWT_SECRET || 'dev-secret';
|
|
|
|
// POST /api/auth/login
|
|
router.post('/login', (req, res) => {
|
|
const { username, password } = req.body;
|
|
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
|
if (!user || !bcrypt.compareSync(password, user.password_hash))
|
|
return res.status(401).json({ error: 'Benutzername oder Passwort falsch' });
|
|
|
|
const token = jwt.sign(
|
|
{ id: user.id, username: user.username, role: user.role },
|
|
SECRET, { expiresIn: '7d' }
|
|
);
|
|
res.json({ token, user: { id: user.id, username: user.username, role: user.role } });
|
|
});
|
|
|
|
// POST /api/auth/change-password
|
|
router.post('/change-password', authenticate, (req, res) => {
|
|
const { currentPassword, newPassword } = req.body;
|
|
const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.user.id);
|
|
if (!bcrypt.compareSync(currentPassword, user.password_hash))
|
|
return res.status(400).json({ error: 'Aktuelles Passwort falsch' });
|
|
if (!newPassword || newPassword.length < 8)
|
|
return res.status(400).json({ error: 'Mindestens 8 Zeichen erforderlich' });
|
|
db.prepare('UPDATE users SET password_hash = ? WHERE id = ?')
|
|
.run(bcrypt.hashSync(newPassword, 12), req.user.id);
|
|
res.json({ success: true });
|
|
});
|
|
|
|
// POST /api/auth/change-username
|
|
router.post('/change-username', authenticate, (req, res) => {
|
|
const { newUsername, password } = req.body;
|
|
if (!newUsername || newUsername.trim().length < 3)
|
|
return res.status(400).json({ error: 'Mindestens 3 Zeichen erforderlich' });
|
|
const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.user.id);
|
|
if (!bcrypt.compareSync(password, user.password_hash))
|
|
return res.status(400).json({ error: 'Passwort falsch' });
|
|
const exists = db.prepare('SELECT id FROM users WHERE username = ? AND id != ?').get(newUsername.trim(), req.user.id);
|
|
if (exists) return res.status(400).json({ error: 'Benutzername bereits vergeben' });
|
|
db.prepare('UPDATE users SET username = ? WHERE id = ?').run(newUsername.trim(), req.user.id);
|
|
res.json({ success: true, username: newUsername.trim() });
|
|
});
|
|
|
|
module.exports = router;
|