mailbox/backend/middleware/auth.js

34 lines
920 B
JavaScript
Raw Permalink Normal View History

2025-12-16 08:18:15 +09:00
/**
* JWT 인증 미들웨어
* Authorization 헤더에서 Bearer 토큰을 추출하여 검증
*/
const jwt = require("jsonwebtoken");
const JWT_SECRET =
process.env.JWT_SECRET || "super_secret_jwt_key_changed_in_production";
/**
* JWT 토큰 인증 미들웨어
* @param {Request} req - Express 요청 객체
* @param {Response} res - Express 응답 객체
* @param {NextFunction} next - 다음 미들웨어
*/
const authenticateToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (!token) {
return res.status(401).json({ error: "인증 토큰이 필요합니다" });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ error: "유효하지 않은 토큰입니다" });
}
req.user = user;
next();
});
};
module.exports = { authenticateToken };