Skip to content

Instantly share code, notes, and snippets.

@hussainb
Forked from mphasize/beforeCreate.js
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hussainb/9c62cf2127c6a2330c49 to your computer and use it in GitHub Desktop.
Save hussainb/9c62cf2127c6a2330c49 to your computer and use it in GitHub Desktop.
/**
* beforeCreate
*
* @module :: Policy
* @description :: Simple policy to inject the user creating a record into the records values.
* Assumes req.user && req.user.id to be set when a user is logged in.
* @docs :: http://sailsjs.org/#!documentation/policies
*
*/
var actionUtil = require( 'sails/lib/hooks/blueprints/actionUtil' );
module.exports = function ( req, res, next ) {
var blueprint = req.options.action;
if ( blueprint === 'create' ) {
var Model = actionUtil.parseModel( req );
if ( req.user && req.user.id ) {
sails.log.debug( 'Policy beforeCreate: Injecting req.user.id into "' + Model.identity + '" parameters.' );
req.body[ Model.identity ].user = req.user.id;
} else {
// exception for creating new users, otherwise any creative act needs a logged in user
if ( Model.identity !== 'user' ) return res.forbidden( "Create blueprint needs an authenticated user!" );
}
}
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment