Skip to content

Instantly share code, notes, and snippets.

@stuk88
Last active August 29, 2015 14:23
Show Gist options
  • Save stuk88/34cc6039947090804554 to your computer and use it in GitHub Desktop.
Save stuk88/34cc6039947090804554 to your computer and use it in GitHub Desktop.
a generic way to check the queried model object
module.exports = function(req, res, next) {
// User is allowed, proceed to the next policy,
// or if this is the last policy, the controller
var policyValidator = ModelPolicy(req);
if (policyValidator.queriedModelCreteria({owner:req.session.user_id}) ) {
return next();
}
// User is not allowed
res.status(403);
return res.json({error:'not allowed'});
};
var wlFilter = require('waterline-criteria');
function ModelPolicy(req) {
this.req = req;
}
ModelPolicy.prototype.queriedModelCreteria = function(criteria) {
var Model = this.req.options.model;
if(!Model) return true; // if its not a model just continue;
var model_obj = Model.findOne(this.req.param("id")).then(function(data){
return data;
});
return this.customModelCreteria(model_obj, criteria);
};
ModelPolicy.prototype.customModelCreteria = function(model_obj, criteria) {
return (wlFilter(model_obj,criteria).results.length > 0);
};
module.exports.policies = {
ProductController: {
'*': true,
'delete': 'isOwner'
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment