给当前访问对象添加自定义方法 判断当前访问用户是否是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();
});
};
网友评论