hrms-api-org/src/middlewares/role.ts

24 lines
851 B
TypeScript
Raw Normal View History

2024-03-11 09:28:59 +07:00
import * as express from "express";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import { RequestWithUser } from "./user";
2024-03-11 09:43:41 +07:00
export function authRole(
role: string | string[],
errorMessage: string = "คุณไม่มีสิทธิในการเข้าถึงทรัพยากรดังกล่าว",
2024-03-11 09:43:41 +07:00
) {
2024-03-11 09:28:59 +07:00
return (req: RequestWithUser, _res: express.Response, next: express.NextFunction) => {
2024-03-11 09:43:41 +07:00
if ((Array.isArray(role) && role.includes("*")) || role === "*") return next();
if (!Array.isArray(role) && !req.user.role.includes(role)) {
throw new HttpError(HttpStatus.FORBIDDEN, errorMessage);
2024-03-11 09:28:59 +07:00
}
2024-03-11 09:43:41 +07:00
if (!req.user.role.some((v) => role.includes(v))) {
throw new HttpError(HttpStatus.FORBIDDEN, errorMessage);
}
return next();
2024-03-11 09:28:59 +07:00
};
}