Skip to content

Instantly share code, notes, and snippets.

@robksawyer
Last active August 29, 2015 14:24
Show Gist options
  • Select an option

  • Save robksawyer/5481b23af2d1e8cbb166 to your computer and use it in GitHub Desktop.

Select an option

Save robksawyer/5481b23af2d1e8cbb166 to your computer and use it in GitHub Desktop.
A policy that checks various controllers to see if the user accessing is the actual owner.
/**
* Authorization Service
*
* Handles various validating various items regarding whether or not a User is allowed to access parts of the app.
*
*/
var changeCase = require('change-case');
module.exports = {
/**
* Handles checking whether or not the user is the owner of the record.
* @param model: string - The model to look up record in.
* @param modelId: string - The model id
* @param userId: string - The user id
*/
isOwner: function(model, modelId, userId) {
var promise = new sails.RSVP.Promise( function(fulfill, reject) {
try {
model.findOne({id: modelId, owner: userId })
.exec(
function(err, res) {
if(err) {
reject(false);
}
if(typeof res !== 'undefined' && res !== '') {
fulfill(true);
} else {
reject(false);
}
}
);
} catch(err) {
sails.log.error(err);
}
});
return promise;
}
};
/**
* isOwner Policy
*
* Policy for authorizing user requests if the current authenticated requesting user is the owner of the record.
*
* @param {Object} req
* @param {Object} res
* @param {Function} next
*/
var changeCase = require('change-case');
module.exports = function (req, res, next) {
if (req.session.authenticated) {
//Check to see if an id is passed along
//Check the controller that the user is trying to access
var modelName = req.options.controller;
var model = sails.models[modelName];
if(typeof model !== 'undefined' && typeof req.param('id') !== 'undefined') {
AuthorizationService.isOwner(model, req.param('id'), req.user.id).then(
function (res) {
return next();
},
function (err){
return res.forbidden('You are not permitted to perform this action.');
}
)
} else {
return res.forbidden('You are not permitted to perform this action.');
}
} else {
// User is not allowed
// (default res.forbidden() behavior can be overridden in `config/403.js`)
return res.forbidden('You are not permitted to perform this action.');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment