auth.controller.ts 5.68 KB
Newer Older
Yoon, Daeki's avatar
Yoon, Daeki committed
1
2
3
4
5
6
import bcrypt from "bcryptjs";
import { NextFunction, Request, Response } from "express";
import jwt, { JwtPayload } from "jsonwebtoken";
import isLength from "validator/lib/isLength";
import isEmail from "validator/lib/isEmail";
import { asyncWrap } from "../helpers";
Yoon, Daeki's avatar
Yoon, Daeki committed
7
import { roleDb, userDb } from "../db";
Yoon, Daeki's avatar
Yoon, Daeki committed
8
import { jwtCofig, envConfig, cookieConfig } from "../config";
Yoon, Daeki's avatar
Yoon, Daeki committed
9
import { TypedRequest } from "../types";
Yoon, Daeki's avatar
Yoon, Daeki committed
10
11
12
13

export interface TypedRequestAuth<T> extends Request {
  auth: T;
}
Yoon, Daeki's avatar
Yoon, Daeki committed
14

Yoon, Daeki's avatar
Yoon, Daeki committed
15
16
17
18
19
20
21
22
23
24
/**
 * 함수를 호출하기 전에 req에 user 정보를 지정해야 합니다.
 */
export const authenticate = asyncWrap(
  async (reqExp: Request, res: Response, next: NextFunction) => {
    try {
      const req = reqExp as TypedRequest;
      if (req.auth) {
        const { userId } = req.auth;
        const user = req.user;
Lee Soobeom's avatar
Lee Soobeom committed
25
26
27
28
        console.log("req.user", req.user);
        console.log("user.id", user.id);
        console.log("userId", userId);

Yoon, Daeki's avatar
Yoon, Daeki committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
        if (user && user.id === userId) {
          return next();
        } else {
          throw new Error("권한이 필요합니다");
        }
      } else {
        throw new Error("로그인이 필요합니다");
      }
    } catch (error: any) {
      console.log(error);
      return res.status(401).send(error.message || "권한 없음");
    }
  }
);

Yoon, Daeki's avatar
Yoon, Daeki committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
 * 지정된 역할 이상으로 권한이 있는지를 판단하는 미들웨어를 반환합니다.
 * @param roleName 역할 문자열
 * @returns 미들웨어
 */
export const hasRole = (roleName: string) => {
  // roleName 이상으로 허락하는 것
  return async (reqExp: Request, res: Response, next: NextFunction) => {
    const req = reqExp as TypedRequestAuth<{ userId: string }>;

    if (!req.auth) {
      return res.status(401).send("로그인이 필요합니다");
    }

    const { userId } = req.auth;
    if (!(await userDb.isValidUserId(userId))) {
      return res.status(401).send("유효한 사용자가 아닙니다");
    }
    const userRole = await roleDb.findRoleByUserId(userId);
    const maxRole = await roleDb.findRoleByName(roleName);
    if (maxRole && Number(maxRole.priority) >= Number(userRole.priority)) {
      return next();
    } else {
      return res.status(401).send("이용 권한이 없습니다");
    }
  };
};

Yoon, Daeki's avatar
Yoon, Daeki committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
export const login = asyncWrap(async (req, res) => {
  const { email, password } = req.body;
  console.log(`email: ${email}, password: ${password}`);
  // 1) 사용자 존재 확인
  const user = await userDb.findUserByEmail(email, true);
  console.log("user =", user);
  if (!user) {
    return res.status(422).send(`${email} 사용자가 존재하지 않습니다`);
  }
  // 2) 비밀번호 확인
  const passwordMatch = await bcrypt.compare(password, user.password);
  if (!passwordMatch) {
    return res.status(401).send("잘못된 비밀번호를 입력하셨습니다");
  }
  // 3) 비밀번호가 맞으면 토큰 생성
87
88
  const token = jwt.sign({ userId: user.id }, jwtCofig.secret, {
    //userId를 토큰에다 넣는 중.
Yoon, Daeki's avatar
Yoon, Daeki committed
89
90
91
    expiresIn: jwtCofig.expires,
  });
  // 4) 토큰을 쿠키에 저장
92
93
94
95
96
  res.cookie(cookieConfig.name, token, {
    //token은 쿠키에 무엇을 실렸는가 이다. 항상 갖고 있다가 홈페이지 들어가면 서버로 접속
    maxAge: cookieConfig.maxAge, // 이 기간 내에서만 유효
    path: "/", //어떠한 경로에 관해서만 쓴다. 지금은 전부에 쓴다.
    httpOnly: envConfig.mode === "production", //false면 브라우저에서 쿠키를 조작, true면 조작할 수 없다.
Lee Soobeom's avatar
Lee Soobeom committed
97
    secure: envConfig.mode === "production", // true면 https를 통해서만 쿠키 전달, false면 불가능
Yoon, Daeki's avatar
Yoon, Daeki committed
98
99
100
101
102
  });
  // 5) 사용자 반환
  res.json({
    isLoggedIn: true,
    email: user.email,
Yoon, Daeki's avatar
Yoon, Daeki committed
103
    role: user.role?.name,
Yoon, Daeki's avatar
Yoon, Daeki committed
104
105
106
107
108
109
110
111
112
113
114
115
  });
});

export const logout = (req: Request, res: Response) => {
  res.clearCookie(cookieConfig.name);
  res.send("Logout Successful");
};

export const requireLogin = asyncWrap(async (reqExp, res, next) => {
  const req = reqExp as TypedRequestAuth<string | JwtPayload>;
  try {
    // 1) 쿠키 토큰 존재 여부 확인
Kim, MinGyu's avatar
Kim, MinGyu committed
116
    const token = req.cookies[cookieConfig.name]; //클라이언트 쪽에서 보낸 토큰을 받는중
Yoon, Daeki's avatar
Yoon, Daeki committed
117
118
119
120
    if (!token) {
      throw new Error("토큰이 존재하지 않습니다");
    }
    // 2) 쿠키 유효성 검사
Kim, MinGyu's avatar
Kim, MinGyu committed
121
    const decodedUser = jwt.verify(token, jwtCofig.secret); // 아까보낸 토근을 디코딩중.
Yoon, Daeki's avatar
Yoon, Daeki committed
122
123
    // 3) 요청 객체에 토큰 사용자 객체 추가
    req.auth = decodedUser;
124
    next(); // 에러가 안나오면 next 사용, 나오면 catch쪽으로.
Yoon, Daeki's avatar
Yoon, Daeki committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
  } catch (error) {
    res.clearCookie(cookieConfig.name);
    console.log("error in requreLogin===\n", error);
    return res
      .status(401)
      .json({ message: "로그인이 필요합니다", redirectUrl: "/login" });
  }
});

export const signup = asyncWrap(async (req, res) => {
  const { name, email, password } = req.body;
  // 1) name, email, password 유효성 검사
  if (!isLength(name ?? "", { min: 2, max: 10 })) {
    return res.status(422).send("이름은 2-10자로 입력해주세요");
  } else if (!isLength(password ?? "", { min: 6 })) {
    return res.status(422).send("비밀번호는 6자 이상으로 입력해주세요");
  } else if (!isEmail(email ?? "")) {
    return res.status(422).send("유효하지 않은 이메일입니다");
  }
  // 2) 사용자 중복 확인
  const userExist = await userDb.isUser(email);
  if (userExist) {
    return res.status(422).send(`${email} 사용자가 이미 존재합니다`);
  }
149
  // 3) 비밀번호 암호화는 useDb.createUser에서 처리
Yoon, Daeki's avatar
Yoon, Daeki committed
150
151
  // 4) 새로운 사용자 만들기
  const newUser = await userDb.createUser({
Lee Soobeom's avatar
Lee Soobeom committed
152
    name,
Yoon, Daeki's avatar
Yoon, Daeki committed
153
    email,
154
    password,
Yoon, Daeki's avatar
Yoon, Daeki committed
155
  });
156
  // 5) 사용자 반환(내부적으로 몽구스가 toJSON() 호출)
Yoon, Daeki's avatar
Yoon, Daeki committed
157
158
  res.json(newUser);
});