Node JS – Authorisations (Sails JS)

In Sails JS we can define authorisations (among other things) with the policies. Policies are operations (usually checks) that are executed before any call to a controller. Since a policy is agnostic about what controller will be associated to and what other policies will be associated to the same controller, it behaves as a chain’s ring: if the result of a policy is positive it will just call the next ring, that could be another policy or the controller, depending on the configuration.

We define policies under the “api/policies” folder, here is an example of authentication policy reply with an “unauthorised” message whether the user isn’t logged in (we check this by searching for the user’s object in the session).

module.exports = function (req, res, next) {
     if (req.session.userObj) {
          return next();

     return res.json("unauthorized");

To apply the policy to our controllers we have to edit the “config/policies.js” file in this way:

module.exports.policies = {

     "*": “<myPolicyFileNameWithoutExtension>",

     loginController: {
          "index": true

With this configuration we are telling Sails JS that we want to apply our policy to all the controllers/actions, apart the loginController/index actions, that will be free to access.

In case our controller is inside a subfolder we can refer to it in this way:

“myFolder/myController”: {
     “myAction”: ...

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s