feat: add utils, error handler and auth middleware

This commit is contained in:
Developer
2026-03-18 16:03:38 +08:00
parent b0ce7dcbaf
commit 9c3281e6ac
3 changed files with 261 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
const jwt = require('jsonwebtoken');
const { AppError } = require('./errorHandler');
const JWT_SECRET = process.env.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 {
const decoded = jwt.verify(token, JWT_SECRET);
req.userId = decoded.userId;
next();
} catch (err) {
throw new AppError('登录已过期', 401, 'TOKEN_EXPIRED');
}
}
function generateToken(userId) {
return jwt.sign({ userId }, JWT_SECRET, { expiresIn: '7d' });
}
module.exports = {
authenticate,
generateToken,
JWT_SECRET,
};