1 | import { intersection } from "lodash";
|
2 | import createError from "http-errors";
|
3 |
|
4 | import { Role } from "../constants";
|
5 |
|
6 | export default function(...roles) {
|
7 | |
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | return async (ctx, next) => {
|
14 | const { jwt } = ctx.state;
|
15 | jwt.roles = jwt.roles || [];
|
16 |
|
17 |
|
18 | if (jwt.roles.includes("ADMIN")) jwt.roles = Object.values(Role);
|
19 |
|
20 | const found = intersection(roles, jwt.roles);
|
21 | if (found.length === 0) {
|
22 | throw new createError.Forbidden(`Require roles ${roles.join(",")}`);
|
23 | }
|
24 |
|
25 | await next();
|
26 | };
|
27 | }
|