我们已经完成了多个具有多个访问级别和 mongoose 的项目,这是迄今为止我们最喜欢的方法:
var ACCESS_MODES = 'public followers private explicit'.split(' ');
var projectSchema = new Schema({
access: { type: String, enum: ACCESS_MODES, required: true, default: 'public' },
owner: { type: Schema.Types.ObjectId, ref: 'User' }]
});
然后我们通常会在 schema 上实现一些自定义的访问方法,例如:
projectSchema.statics.getByIdFor = function(user, id, done) {
this.findOne({ _id: id }).populate('owner').exec(onFound);
function onFound(err, project) {
// now check 'user' against the project's access method:
if (project.access === 'public') return done(undefined, project);
if (project.access === 'private') {
// ...etc, handle the logic for access at different levels
}
// finally, they didn't get access
done(new Error('no permission to access this project'));
}
};
所以你现在可以做这样的事情并且知道它是安全的:
ProjectModel.findByIdFor(loggedinUser, req.params.projectId, onFound);
要查找用户有权访问的所有项目:
projectSchema.statics.getForUser = function(user, done) {
var accessible = [];
this.find({ access: 'public' }).exec(onPublic);
this.find({ access: 'followers' }).populate('owner').exec(onFollowers);
this.find({ access: 'private', owner: user }).exec(onPrivate);
this.find({ access: 'explicit' }).populate('owner').exec(onExplicit);
// add onPublic/Followers/Private/Explicit to accessible where user is in the correct list
};