import jwt from "jsonwebtoken";
import { prisma } from "../src/utils/prisma/index.js";
export default async function (req, res, next) {
try {
const { authorization } = req.cookies;
const [tokenType, token] = authorization.split(" ");
if (tokenType !== "Bearer")
throw new Error("토큰 타입이 일치하지 않습니다.");
// 서버에서 발급한 jwt가 맞는지 검증한다.
const decodedToken = jwt.verify(token, "key");
const userId = decodedToken.userId;
const user = await prisma.users.findFirst({
where: { userId: +userId },
});
if (!user) {
res.clearCookie("authorization");
throw new Error("토큰 사용자가 존재하지 않습니다."); // catch로 넘긴다.
}
req.user = user;
//미들웨어가 실행되면 다음으로 넘어간다. NEXT()
next();
} catch (error) {
res.clearCookie("authorization");
// 에러 구분
switch (error.name) {
case "TokenExpriredError": // 토큰이 만료되었을 때 발생하는 에러
return res.status(401).json({ message: "토큰이 만료되었습니다." });
break;
case "JsonwebtokenEroor": // 토큰에 검증이 실패했을 때 발생하는 에러
return res.status(401).json({ message: "토큰이 검증이 실패했습니다." });
break;
deafult: return res
.status(401)
.json({ message: error.name ?? "비정상적인 요청입니다." });
}
}
}