From 9d3f66f3276405398c72afe135166a3f802591ec Mon Sep 17 00:00:00 2001 From: Daeki Yoon Date: Wed, 27 Jul 2022 10:28:00 +0900 Subject: [PATCH] =?UTF-8?q?=EC=84=9C=EB=B2=84=20authenticate=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/controllers/auth.controller.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/controllers/auth.controller.ts b/src/controllers/auth.controller.ts index 4031939..0463130 100644 --- a/src/controllers/auth.controller.ts +++ b/src/controllers/auth.controller.ts @@ -6,11 +6,37 @@ import isEmail from "validator/lib/isEmail"; import { asyncWrap } from "../helpers"; import { roleDb, userDb } from "../db"; import { jwtCofig, envConfig, cookieConfig } from "../config"; +import { TypedRequest } from "../types"; export interface TypedRequestAuth extends Request { auth: T; } +/** + * 함수를 호출하기 전에 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; + 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 || "권한 없음"); + } + } +); + /** * 지정된 역할 이상으로 권한이 있는지를 판단하는 미들웨어를 반환합니다. * @param roleName 역할 문자열 -- GitLab