如何在express / mongoose中创build访问控制
我有expressjs和Mongoose(有mongodb)的项目。 我有多个用户angular色 – pipe理员,经理,用户
我希望每个表的几个字段可以被pipe理员访问,而其他的则不可以。 默认情况下用户不会有任何编辑访问权限,pipe理员将具有完全访问权限。 一种方法是通过查看用户的angular色来在每个控制器function中进行这种控制。 有没有简单的方法来做,如检查用户是否有控制,然后为每个表保存一次,以避免业务逻辑的重复。
我的ordersschema如下。 我不希望没有pipe理员权限的客户信息。
var OrderSchema = new Schema({ order_type: { type: String, trim: true }, customer_phone: { type: String, trim: true } }); var managerAccess = [order_type];
我的用户模式如下(更多字段没有添加)
var UserSchema = new Schema({ firstName: { type: String, trim: true, default: '', validate: [validateLocalStrategyProperty, 'Please fill in your first name'] }, roles: { type: [{ type: String, enum: ['user', 'admin'] }], default: ['user'] }, })
您可以将全局逻辑插入如下的function:
app.all('*', requireAuthentication, loadUser); OR app.all('*', function(req, res, next){ }, function(req, res, next){ });
无论你放在上面哪条路线,后续/下面的路线将在requireAuthentication &然后loadUsercallback后执行。
另一个赌注是限制特定的路线,如下所示:
app.all('/api/*', requireAuthentication); // all routes prefixed with **/api/** will require authentication.
这是express API文档的优秀参考 。