diff --git a/src/controllers/auth.controller.ts b/src/controllers/auth.controller.ts index 4031939ed6ab2fd1610166bbb5b49cdf880a7312..04631301929cb8a939610569522a3dfb34b5b36d 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 역할 문자열