UNPKG

737 BJavaScriptView Raw
1import { intersection } from "lodash";
2import createError from "http-errors";
3
4import { Role } from "../constants";
5
6export default function(...roles) {
7 /**
8 * 中间件 检车是否拥有匹配的角色
9 *
10 * @param {import("koa").Context} ctx koa context
11 * @param {import("koa").Next} next koa next
12 */
13 return async (ctx, next) => {
14 const { jwt } = ctx.state;
15 jwt.roles = jwt.roles || [];
16
17 // 如果 拥有 ADMIN 角色,自动解析成所有角色
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}