[英]show records based on user role
I have a app which has roles eg "user,admin". 我有一个角色为“ user,admin”的应用程序。 In the controller I check if the user is admin "req.user.roles.indexOf('admin') > -1" to display all records otherwise display only users records.
在控制器中,我检查用户是否为管理员“ req.user.roles.indexOf('admin')> -1”以显示所有记录,否则仅显示用户记录。 I was wondering if there is a better way of doing this or is this the way to go.
我想知道是否有更好的方法可以做到这一点? Thanks
谢谢
code 码
/**
* List of Articles
*/
exports.list = function (req, res) {
if (req.user.roles.indexOf('admin') > -1) {
Article.find().sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
}else {
Article.find({user:req.user._id}).sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
}
};
You can also refactor out the database access bit in another method (probably in a different module - userController), which will make your code more readable. 您还可以使用其他方法(可能在其他模块中-userController)重构数据库访问位,这将使您的代码更具可读性。 This doesn't qualify as an answer but putting all this in comment didn't look ok.
这没有资格作为答案,但是将所有这些内容置入评论中似乎没有问题。
exports.list = function (req, res) {
if (hasRole('admin')) {
userController.getAllRecords(req, res);
} else {
userController.getRecordsById(req, res)
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.