Add user authentication with JWT login and registration
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const JWT_SECRET =
|
||||
process.env.JWT_SECRET || "reco-jwt-secret-change-in-production";
|
||||
const JWT_EXPIRES_IN = "7d";
|
||||
|
||||
// 无需认证的公开路由
|
||||
const PUBLIC_PATHS = [
|
||||
"/api/auth/login",
|
||||
"/api/auth/register",
|
||||
"/api/auth/health",
|
||||
];
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
// 白名单放行
|
||||
if (
|
||||
PUBLIC_PATHS.includes(req.path) ||
|
||||
req.path.startsWith("/api/auth/health")
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const header = req.headers.authorization;
|
||||
if (!header || !header.startsWith("Bearer ")) {
|
||||
return res.status(401).json({ error: "请先登录" });
|
||||
}
|
||||
|
||||
try {
|
||||
const token = header.split(" ")[1];
|
||||
const decoded = jwt.verify(token, JWT_SECRET);
|
||||
req.userId = decoded.userId;
|
||||
next();
|
||||
} catch (err) {
|
||||
return res.status(401).json({ error: "登录已过期,请重新登录" });
|
||||
}
|
||||
}
|
||||
|
||||
function signToken(userId) {
|
||||
return jwt.sign({ userId }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
|
||||
}
|
||||
|
||||
module.exports = { authMiddleware, signToken, JWT_SECRET };
|
||||
Reference in New Issue
Block a user