auth(role): Multi role support
This commit is contained in:
parent
1af696b39c
commit
d825373542
1 changed files with 13 additions and 3 deletions
|
|
@ -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();
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue