Philip Feldmann
Philip Feldmann

Reputation: 8375

SailsJS policy on request method rather than route

Is there any way I can trigger a policy on a specific request method (e.g. DELETE) rather than on specific routes?

I'd imagine something like this:

module.exports.policies = {
   'DELETE *': 'isAdmin'
}

My goal here is to expose the blueprint api to admins only, so that I can keep it in production, as it's a very useful tool for allowing third party scripts to add extra functionality.

I'm on Sails 1.0 right now.

One way to do that might be to add the check for the request method to the actual admin policy, however that doesn't quite seem like the best solution to me.

Upvotes: 4

Views: 298

Answers (2)

logout
logout

Reputation: 631

Here is one method that you can use, I am not claiming that it is the right way, but you can consider it:

You can write your own hook. How to do this: https://sailsjs.com/documentation/concepts/extending-sails/hooks/project-hooks

Basically here is the solution with a hook:

1 Create a hooks folder under your api folder.

2 In the hooks folder create another folder - the name will be the name of your hook (say my-hook).

3 In api/hooks/my-hook create a file index.js and in it put the following code:

module.exports = function myHook(sails) {
  return {
    routes: {
      before: {
        '/*': function (req, res, next) {
          if (req.method.toUpperCase() === 'DELETE') {
            return sails.hooks.policies.middleware.isadmin(req, res, next); // note - your policy function name must be called here with all lowercase, otherwise it will not work.
          }

          return next();
        }
      }
    }
  };
};

Then in your isAdmin.js policy you can check if your user is an admin and if not:

return res.forbidden();

if it is admin:

return next();

Upvotes: 1

noah-sd
noah-sd

Reputation: 186

You can override the blueprint for all models for a particular method. You can do this for DELETE by creating a file destroy.js in /api/blueprints/ and then adding your code for what you want to do when a DELETE comes through:

module.exports = function(req,res, next) {
    if(ACLService.hasPermission(req.user.acl, 'admin')) {
        //Ok to allow delete here
    } else {
        return res.unauthorized();
    }
};

This is how I've done it in the past, but looking at the docs for the just released SailsJS 1.0:

https://sailsjs.com/documentation/reference/blueprint-api

You may need to add this hook for overriding blueprints in 1.0

https://www.npmjs.com/package/sails-hook-custom-blueprints

Upvotes: 2

Related Questions