|
import express from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
import bcrypt from 'bcryptjs';
|
|
import { USERS, JWT_SECRET, JWT_EXPIRES_IN } from '../config/users.js';
|
|
|
|
const router = express.Router();
|
|
|
|
|
|
router.post('/login', async (req, res, next) => {
|
|
try {
|
|
const { username, password } = req.body;
|
|
|
|
if (!username || !password) {
|
|
return res.status(400).json({ error: 'Username and password are required' });
|
|
}
|
|
|
|
|
|
const user = USERS.find(u => u.username === username);
|
|
if (!user) {
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
}
|
|
|
|
|
|
if (user.password !== password) {
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
}
|
|
|
|
|
|
const token = jwt.sign(
|
|
{
|
|
userId: user.id,
|
|
username: user.username,
|
|
role: user.role
|
|
},
|
|
JWT_SECRET,
|
|
{ expiresIn: JWT_EXPIRES_IN }
|
|
);
|
|
|
|
res.json({
|
|
token,
|
|
user: {
|
|
id: user.id,
|
|
username: user.username,
|
|
role: user.role
|
|
}
|
|
});
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
|
|
router.get('/verify', (req, res, next) => {
|
|
try {
|
|
const authHeader = req.headers['authorization'];
|
|
const token = authHeader && authHeader.split(' ')[1];
|
|
|
|
if (!token) {
|
|
return res.status(401).json({ error: 'No token provided' });
|
|
}
|
|
|
|
jwt.verify(token, JWT_SECRET, (err, decoded) => {
|
|
if (err) {
|
|
return res.status(401).json({ error: 'Invalid token' });
|
|
}
|
|
|
|
res.json({
|
|
user: {
|
|
id: decoded.userId,
|
|
username: decoded.username,
|
|
role: decoded.role
|
|
}
|
|
});
|
|
});
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
|
|
router.get('/user', (req, res, next) => {
|
|
try {
|
|
const authHeader = req.headers['authorization'];
|
|
const token = authHeader && authHeader.split(' ')[1];
|
|
|
|
if (!token) {
|
|
return res.status(401).json({ error: 'No token provided' });
|
|
}
|
|
|
|
jwt.verify(token, JWT_SECRET, (err, decoded) => {
|
|
if (err) {
|
|
return res.status(401).json({ error: 'Invalid token' });
|
|
}
|
|
|
|
const user = USERS.find(u => u.id === decoded.userId);
|
|
if (!user) {
|
|
return res.status(404).json({ error: 'User not found' });
|
|
}
|
|
|
|
res.json({
|
|
id: user.id,
|
|
username: user.username,
|
|
role: user.role
|
|
});
|
|
});
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
export default router; |