Files

36 lines
876 B
JavaScript
Raw Permalink Normal View History

const jwt = require('jsonwebtoken');
const { AppError } = require('./errorHandler');
2026-05-18 15:16:46 +08:00
const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET && process.env.NODE_ENV === 'production') {
throw new Error('JWT_SECRET must be set in production');
}
const tokenSecret = JWT_SECRET || 'accountbook_secret_key_2024';
function authenticate(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
throw new AppError('请先登录', 401, 'UNAUTHORIZED');
}
try {
2026-05-18 15:16:46 +08:00
const decoded = jwt.verify(token, tokenSecret);
req.userId = decoded.userId;
next();
} catch (err) {
throw new AppError('登录已过期', 401, 'TOKEN_EXPIRED');
}
}
function generateToken(userId) {
2026-05-18 15:16:46 +08:00
return jwt.sign({ userId }, tokenSecret, { expiresIn: '7d' });
}
module.exports = {
authenticate,
generateToken,
2026-05-18 15:16:46 +08:00
JWT_SECRET: tokenSecret,
};