54 lines
1.8 KiB
JavaScript
54 lines
1.8 KiB
JavaScript
|
|
const express = require('express');
|
||
|
|
const jwt = require('jsonwebtoken');
|
||
|
|
const User = require('../models/User');
|
||
|
|
const authenticate = require('../middleware/auth');
|
||
|
|
|
||
|
|
const router = express.Router();
|
||
|
|
const JWT_SECRET = process.env.JWT_SECRET || 'dev_secret_change_in_production';
|
||
|
|
|
||
|
|
// Register
|
||
|
|
router.post('/register', async (req, res) => {
|
||
|
|
try {
|
||
|
|
const { email, password } = req.body;
|
||
|
|
if (!email || !password) {
|
||
|
|
return res.status(400).json({ error: 'Email and password required' });
|
||
|
|
}
|
||
|
|
const existing = await User.findOne({ where: { email } });
|
||
|
|
if (existing) {
|
||
|
|
return res.status(409).json({ error: 'User already exists' });
|
||
|
|
}
|
||
|
|
const user = await User.create({ email, password });
|
||
|
|
const token = jwt.sign({ id: user.id, email: user.email }, JWT_SECRET, { expiresIn: '7d' });
|
||
|
|
res.status(201).json({ token, user: { id: user.id, email: user.email } });
|
||
|
|
} catch (err) {
|
||
|
|
console.error(err);
|
||
|
|
res.status(500).json({ error: 'Registration failed' });
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
// Login
|
||
|
|
router.post('/login', async (req, res) => {
|
||
|
|
try {
|
||
|
|
const { email, password } = req.body;
|
||
|
|
if (!email || !password) {
|
||
|
|
return res.status(400).json({ error: 'Email and password required' });
|
||
|
|
}
|
||
|
|
const user = await User.findOne({ where: { email } });
|
||
|
|
if (!user || !(await user.validatePassword(password))) {
|
||
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
||
|
|
}
|
||
|
|
const token = jwt.sign({ id: user.id, email: user.email }, JWT_SECRET, { expiresIn: '7d' });
|
||
|
|
res.json({ token, user: { id: user.id, email: user.email } });
|
||
|
|
} catch (err) {
|
||
|
|
console.error(err);
|
||
|
|
res.status(500).json({ error: 'Login failed' });
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
// Get current user
|
||
|
|
router.get('/me', authenticate, async (req, res) => {
|
||
|
|
res.json({ id: req.user.id, email: req.user.email });
|
||
|
|
});
|
||
|
|
|
||
|
|
module.exports = router;
|