Skip to content
关注公众号,获取新课通知

全局权限验证中间件实现


中间件:app/middleware/auth.js

js
module.exports = (option, app) => {
  return async (ctx, next) => {
    //1. 获取 header 头token
    const { token } = ctx.header;
    if (!token) {
      ctx.throw(400, "您没有权限访问该接口!");
    }
    //2. 根据token解密,换取用户信息
    let user = {};
    try {
      user = ctx.checkToken(token);
    } catch (error) {
      let fail = error.name === "TokenExpiredError"
        ? "token 已过期! 请重新获取令牌"
        : "Token 令牌不合法!";
      ctx.throw(400, fail);
    }
    //3. 判断当前用户是否登录
    let t = await ctx.service.cache.get("user_" + user.id);
    if (!t || t !== token) {
      ctx.throw(400, "Token 令牌不合法!");
    }

    //4. 获取当前用户,验证当前用户是否存在
    user = await app.model.User.findByPk(user.id);
    if (!user) {
      ctx.throw(400, "用户不存在");
    }
    // 5. 把 user 信息挂载到全局ctx上
    ctx.authUser = user;

    await next();
  };
};

配置:config/config.default.js

js
config.middleware = [
  //...
  "auth",
  // ...
];

// 配置那些路由需要验证
config.auth = {
  //ignore: ['/reg', '/login']
  match: [
    "/logout",
    "/video",
    "/video_detail",
    "/vod/sign",
    "/comment",
    "/fava",
    "/user/follow",
    "/user/unfollow",
    "/user/follows",
    "/user/fens",
    "/user/statistics",
  ],
};