美文网首页
Using current context

Using current context

作者: 萧哈哈 | 来源:发表于2018-07-06 15:27 被阅读13次

给当前访问对象添加自定义方法 判断当前访问用户是否是Admin

https://github.com/strongloop/loopback/issues/3796

./server/boot/is-admin-phase.js

'use strict';

var isAdmin = require('../../lib/is-admin');

module.exports = function(app) {
  app.remotes().phases
    .addBefore('invoke', 'options-from-request')
    .use(function(ctx, next) {
      // Some requests are missing parts of these properties, so check for safety!
      if (ctx && ctx.args && ctx.args.options && ctx.args.options.accessToken) {
        const User = app.models.User;
        User.findById(ctx.args.options.accessToken.userId, function(err, user) {
          if (err) return next(err);
          ctx.args.options.currentUser = Object.assign(user, {
            isAdmin: isAdmin,
          });
          next();
        });
      } else {
        return next();
      }
    });
};

./common/models/category.js

'use strict';

module.exports = function(Category) {
  Category.observe('access', function(ctx, next) {
    // Note: This ctx object doesn't contain the "args" property you used in the custom phase!
    if (ctx.options.currentUser.isAdmin()) {
      console.log('Hurray!'); // Yay!
    }
    return next();
  });
};

相关文章

网友评论

      本文标题:Using current context

      本文链接:https://www.haomeiwen.com/subject/carutftx.html