19 lines
797 B
TypeScript
19 lines
797 B
TypeScript
import { Response, NextFunction } from "express";
|
|
import { RequestWithUser } from "../interfaces/user";
|
|
import HttpError from "../interfaces/http-error";
|
|
import HttpStatus from "../interfaces/http-status";
|
|
|
|
export function role(
|
|
role: string | string[],
|
|
errorMessage: string = "You do not have permission to access this resource.",
|
|
) {
|
|
return (req: RequestWithUser, _res: Response, next: NextFunction) => {
|
|
if (!Array.isArray(role) && !req.user.roles.includes(role) && !req.user.roles.includes("*")) {
|
|
throw new HttpError(HttpStatus.FORBIDDEN, errorMessage, "noPermissionToAccess");
|
|
}
|
|
if (role !== "*" && !req.user.roles.some((v) => role.includes(v))) {
|
|
throw new HttpError(HttpStatus.FORBIDDEN, errorMessage, "noPermissionToAccess");
|
|
}
|
|
return next();
|
|
};
|
|
}
|