Created
March 2, 2015 10:10
-
-
Save mphasize/a69d86b9722ea464deca to your computer and use it in GitHub Desktop.
Sails-beforeCreate-Policy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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(); | |
}; |
If you think this is interesting for your project, please also take a look at this Feature Request and see if that would help you apply this Policy.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This policy injects the ID of the user creating a model records into that records data. This way it's a lot easier to define a
user
attribute on a model and make sure that only registered + logged in users can create new records of this model.After installing this policy in
api/policies/beforeCreate.js
you need to set it up inconfig/policies.js
to be used on the Controllers create action like this: