auth.controller.ts 8.84 KB
Newer Older
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";
Jiwon Yoon's avatar
Jiwon Yoon committed
7
import { roleDb, userDb, oauthDb } from "../db";
8
import { jwtCofig, envConfig, cookieConfig } from "../config";
9
import axios from "axios";
10
11
12

export interface TypedRequestAuth<T> extends Request {
  auth: T;
13
  user: any;
14
}
15

16
17
18
19
const REST_API_KEY = process.env.REST_API_KEY as string;
const REDIRECT_URI = process.env.REDIRECT_URI as string;
const CLIENT_SECRET_KEY = process.env.CLIENT_SECRET_KEY as string;
console.log("restapikey", REST_API_KEY);
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
/**
 * 함수를 호출하기 전에 req에 user 정보를 지정해야 합니다.
 */
export const authenticate = asyncWrap(
  async (reqExp: Request, res: Response, next: NextFunction) => {
    try {
      const req = reqExp as TypedRequestAuth<{ userId: string }>;
      if (req.auth) {
        const { userId } = req.auth;
        const user = req.user;
        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 || "권한 없음");
    }
  }
);

45
46
47
48
49
50
51
52
53
54
55
56
57
/**
 * 지정된 역할 이상으로 권한이 있는지를 판단하는 미들웨어를 반환합니다.
 * @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("로그인이 필요합니다");
    }
58

59
    const { userId } = req.auth;
60
61
62
    if (!(await userDb.isValidUserId(userId))) {
      return res.status(401).send("유효한 사용자가 아닙니다");
    }
63
64
65
66
67
68
69
70
71
72
    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("이용 권한이 없습니다");
    }
  };
};

73
74
75
76
77
78
79
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) {
80
81
82
    return res
      .status(422)
      .send(`${email} 사용자가 존재하지않습니다 회원가입을 해주세요`);
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
  }
  // 2) 비밀번호 확인
  const passwordMatch = await bcrypt.compare(password, user.password);
  if (!passwordMatch) {
    return res.status(401).send("잘못된 비밀번호를 입력하셨습니다");
  }
  // 3) 비밀번호가 맞으면 토큰 생성
  const token = jwt.sign({ userId: user.id }, jwtCofig.secret, {
    expiresIn: jwtCofig.expires,
  });
  // 4) 토큰을 쿠키에 저장
  res.cookie(cookieConfig.name, token, {
    maxAge: cookieConfig.maxAge,
    path: "/",
    httpOnly: envConfig.mode === "production",
    secure: envConfig.mode === "production",
  });
  // 5) 사용자 반환
  res.json({
    isLoggedIn: true,
    email: user.email,
  });
});

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) 쿠키 토큰 존재 여부 확인
    const token = req.cookies[cookieConfig.name];
    if (!token) {
      throw new Error("토큰이 존재하지 않습니다");
    }
    // 2) 쿠키 유효성 검사
    const decodedUser = jwt.verify(token, jwtCofig.secret);
    // 3) 요청 객체에 토큰 사용자 객체 추가
    req.auth = decodedUser;
    next();
  } 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
150
  // 3) 비밀번호 암호화는 useDb.createUser에서 처리
  // const hash = await bcrypt.hash(password, 10);
151
152
153
  // 4) 새로운 사용자 만들기
  const newUser = await userDb.createUser({
    email,
154
    password,
155
156
157
158
  });
  // 5) 사용자 반환
  res.json(newUser);
});
159
160

export const kakaoAuthenticate = asyncWrap(async (req, res) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
161
  // console.log(req.body);
162
163
  const code = req.body.code;
  try {
Jiwon Yoon's avatar
Jiwon Yoon committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    const socialKeys = await oauthDb.getSocialKey("kakao");
    if (socialKeys) {
      const params = new URLSearchParams({
        grant_type: "authorization_code",
        client_id: socialKeys.REST_API_KEY,
        redirect_uri: socialKeys.REDIRECT_URI,
        code: code,
        client_secret: socialKeys.CLIENT_SECRET_KEY,
      });
      const kakaoResponse = await axios.post(
        "https://kauth.kakao.com/oauth/token",
        params
      );
      const kakaoUserData = jwt.decode(kakaoResponse.data.id_token) as any;
Jiwon Yoon's avatar
Jiwon Yoon committed
178
      console.log(kakaoUserData);
Jiwon Yoon's avatar
Jiwon Yoon committed
179
      if (kakaoUserData) {
Jiwon Yoon's avatar
Jiwon Yoon committed
180
        // 카카오 계정이든 아니든 같은 이메일이 있는지 확인
Jiwon Yoon's avatar
Jiwon Yoon committed
181
182
        const userExist = await userDb.isUser(kakaoUserData.email);
        if (userExist) {
Jiwon Yoon's avatar
Jiwon Yoon committed
183
184
          // 이메일이 있을 경우
          // 카카오 계정으로 이메일이 있는지 확인
Jiwon Yoon's avatar
Jiwon Yoon committed
185
          const kakaoUser = await userDb.isSocialType(
Jiwon Yoon's avatar
Jiwon Yoon committed
186
187
            "kakao",
            kakaoUserData.email
Jiwon Yoon's avatar
Jiwon Yoon committed
188
          );
Jiwon Yoon's avatar
Jiwon Yoon committed
189
          console.log("카카오 유저: ", kakaoUser);
Jiwon Yoon's avatar
Jiwon Yoon committed
190
          if (kakaoUser) {
Jiwon Yoon's avatar
Jiwon Yoon committed
191
            // 1) 카카오 유저가 있을 경우 토큰 생성
Jiwon Yoon's avatar
Jiwon Yoon committed
192
193
194
            const token = jwt.sign({ userId: kakaoUser.id }, jwtCofig.secret, {
              expiresIn: jwtCofig.expires,
            });
Jiwon Yoon's avatar
Jiwon Yoon committed
195
            // 2) 토큰을 쿠키에 저장
Jiwon Yoon's avatar
Jiwon Yoon committed
196
197
198
199
200
201
            res.cookie(cookieConfig.name, token, {
              maxAge: cookieConfig.maxAge,
              path: "/",
              httpOnly: envConfig.mode === "production",
              secure: envConfig.mode === "production",
            });
Jiwon Yoon's avatar
Jiwon Yoon committed
202
            // 3) 사용자 반환
Jiwon Yoon's avatar
Jiwon Yoon committed
203
204
205
206
207
            res.json({
              isLoggedIn: true,
              email: kakaoUser.email,
            });
          } else {
Jiwon Yoon's avatar
Jiwon Yoon committed
208
            // 카카오 유저가 아닌 다른 이메일 유저일 경우
Jiwon Yoon's avatar
Jiwon Yoon committed
209
210
211
212
213
214
215
            return res
              .status(422)
              .send(
                `다른 로그인 방식의 ${kakaoUserData.email} 사용자가 이미 존재합니다`
              );
          }
        } else {
Jiwon Yoon's avatar
Jiwon Yoon committed
216
217
          // 이미 존재하는 이메일이 없을 경우
          // 1) email이랑 password(sub:고유 회원번호) DB에 저장
Jiwon Yoon's avatar
Jiwon Yoon committed
218
219
          const newUser = await userDb.createUser({
            email: kakaoUserData.email,
Jiwon Yoon's avatar
Jiwon Yoon committed
220
            password: kakaoUserData.sub,
Jiwon Yoon's avatar
Jiwon Yoon committed
221
222
            socialType: "kakao",
          });
Jiwon Yoon's avatar
Jiwon Yoon committed
223
          // 2) 토큰 생성
Jiwon Yoon's avatar
Jiwon Yoon committed
224
225
226
          const token = jwt.sign({ userId: newUser.id }, jwtCofig.secret, {
            expiresIn: jwtCofig.expires,
          });
Jiwon Yoon's avatar
Jiwon Yoon committed
227
          // 3) 토큰을 쿠키에 저장
Jiwon Yoon's avatar
Jiwon Yoon committed
228
229
230
231
232
233
          res.cookie(cookieConfig.name, token, {
            maxAge: cookieConfig.maxAge,
            path: "/",
            httpOnly: envConfig.mode === "production",
            secure: envConfig.mode === "production",
          });
Jiwon Yoon's avatar
Jiwon Yoon committed
234
          // 4) 사용자 반환
Jiwon Yoon's avatar
Jiwon Yoon committed
235
236
237
238
239
240
241
          res.json({
            isLoggedIn: true,
            email: newUser.email,
          });
        }
      }
    }
242
243
  } catch (error) {
    console.log(error);
Jiwon Yoon's avatar
Jiwon Yoon committed
244
    res.send("카카오 로그인 에러");
245
246
  }
});
Jiwon Yoon's avatar
Jiwon Yoon committed
247
248
249
250
251
252
253
254
255

export const saveOauthKeys = asyncWrap(async (req, res, next) => {
  console.log(req.body);
  try {
    const oauth = await oauthDb.createSocialKey(req.body);
    console.log(oauth);
    return res.json(oauth);
  } catch (error) {}
});
Jiwon Yoon's avatar
Jiwon Yoon committed
256
257
258
259
260
261
262
263
264

export const getOauthKeys = asyncWrap(async (req, res, next) => {
  console.log(req.params);
  try {
    const socialKeys = await oauthDb.getSocialKey(req.params.socialType);
    console.log(socialKeys);
    return res.json(socialKeys);
  } catch (error) {}
});