From d825373542b36b2a25a590a69300b32df87e54c2 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Mon, 11 Mar 2024 09:43:41 +0700 Subject: [PATCH] auth(role): Multi role support --- src/middlewares/role.ts | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/middlewares/role.ts b/src/middlewares/role.ts index 0ea1125b..fef95919 100644 --- a/src/middlewares/role.ts +++ b/src/middlewares/role.ts @@ -3,11 +3,21 @@ import HttpError from "../interfaces/http-error"; import HttpStatus from "../interfaces/http-status"; import { RequestWithUser } from "./user"; -export function authRole(role: string, errorMessage = "คุณไม่มีสิทธิในการเข้าถึงทรัพยากรดังกล่าว") { +export function authRole( + role: string | string[], + errorMessage = "คุณไม่มีสิทธิในการเข้าถึงทรัพยากรดังกล่าว", +) { return (req: RequestWithUser, _res: express.Response, next: express.NextFunction) => { - if (!req.user.role.includes(role)) { + if ((Array.isArray(role) && role.includes("*")) || role === "*") return next(); + + if (!Array.isArray(role) && !req.user.role.includes(role)) { throw new HttpError(HttpStatus.FORBIDDEN, errorMessage); } - next(); + + if (!req.user.role.some((v) => role.includes(v))) { + throw new HttpError(HttpStatus.FORBIDDEN, errorMessage); + } + + return next(); }; }