1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53import jwt from "jsonwebtoken";
function loginRequired(req, res, next) {
// request ν€λλ‘λΆν° authorization bearer ν ν°μ λ°μ.
// token format νμΈ
const wholeToken = req.headers["authorization"]?.split(" ");
const tokenFormat = wholeToken[0];
if (tokenFormat !== "Bearer") {
console.log("Bearer ν ν°μ΄ μλλλ€.");
res.status(401).json({
result: "Unauthorized-approach",
reason: "μ§μλμ§ μλ ν ν° ν¬λ§·μ
λλ€.",
});
}
const userToken = wholeToken[1];
// μ΄ ν ν°μ jwt ν ν° λ¬Έμμ΄μ΄κ±°λ, νΉμ "null" λ¬Έμμ΄μ΄κ±°λ, undefinedμ.
// ν ν°μ΄ "null" μΌ κ²½μ°, login_required κ° νμν μλΉμ€ μ¬μ©μ μ νν¨.
if (!userToken || userToken === "null") {
console.log("μλΉμ€ μ¬μ© μμ²μ΄ μμ΅λλ€.νμ§λ§, Authorization ν ν°: μμ");
res.status(401).json({
result: "Unauthorized-approach",
reason: "λ‘κ·ΈμΈν μ μ λ§ μ¬μ©ν μ μλ μλΉμ€μ
λλ€.",
});
return;
}
// ν΄λΉ token μ΄ μ μμ μΈ tokenμΈμ§ νμΈ
try {
const secretKey = process.env.JWT_SECRET_KEY || "secret-key";
const jwtDecoded = jwt.verify(userToken, secretKey);
const userId = jwtDecoded.userId;
// λΌμ°ν°μμ req.currentUserIdλ₯Ό ν΅ν΄ μ μ μ idμ μ κ·Ό κ°λ₯νκ² λ¨
req.currentUserId = userId;
next();
} catch (error) {
// jwt.verify ν¨μκ° μλ¬λ₯Ό λ°μμν€λ κ²½μ°λ ν ν°μ΄ μ μμ μΌλ‘ decode μλμμ κ²½μ°μ.
// 403 μ½λλ‘ JSON ννλ‘ νλ‘ νΈμ μ λ¬ν¨.
res.status(401).json({
result: "Unauthorized-approach",
reason: "μ μμ μΈ ν ν°μ΄ μλλλ€.",
});
return;
}
}
export { loginRequired };