Spaces:
Running
Running
File size: 1,146 Bytes
28e1dba |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import jwt from 'jsonwebtoken';
import { JWT_SECRET, JWT_ENABLED } from '../config/users.js';
export const authenticateToken = (req, res, next) => {
console.log(`Authenticating request: ${req.method} ${req.path}`);
// 如果JWT未启用,提供默认用户并跳过验证
if (!JWT_ENABLED) {
console.log('JWT disabled, using default user');
req.user = {
userId: 'PS01',
username: 'PS01',
role: 'admin'
};
return next();
}
console.log('Authorization header:', req.headers['authorization'] ? 'Present' : 'Missing');
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
console.log('No token provided');
return res.status(401).json({ error: 'Access token required' });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
console.log('Token verification failed:', err.message);
return res.status(403).json({ error: 'Invalid or expired token' });
}
console.log('Token verified for user:', user.userId);
req.user = user;
next();
});
}; |