Hanif Bali
Hanif Bali

Reputation: 71

How to restrict findOne with policy

With the find and update methods i am able to restrict fetching of data restricted to the logged in user by adding a policy that sets req.options.where.owner = userID, therefore i dont need to create custom controllers or models for these methods.

With update and create i can also set req.options.values.owner = userID so that the user cant create or update an object that will belong to another user.

But the problem is that the blueprint findOne controller does not have any options for this kind of filtering, so any logged in user can request an object created and owned by another user.

Is there anyway i can restrict findOne without writing my own controller and query?

Upvotes: 1

Views: 235

Answers (2)

Hanif Bali
Hanif Bali

Reputation: 71

Found a solution to the problem, what you can do is to override the default blueprint action by creating a folder named blueprints in your api folder, there you can create a findone.js (lowercase) file,

  1. copy the original blueprint action from /node_modules/sails/lib/hooks/blueprints/actions/findOne.js to /api/blueprints/findone.js
  2. add .where( actionUtil.parseCriteria(req) ); to the query.
  3. Dont forget to change the path of actionutil from require('../actionUtil'); to require('../../node_modules/sails/lib/hooks/blueprints/actionUtil');

Voila, now the findOne action will respect your req.options.where queries.

Upvotes: 2

Andi N. Dirgantara
Andi N. Dirgantara

Reputation: 2051

You can specify blueprint in your policies like this

module.exports = function (req, res, next) {

  var blueprint = req.options.action;

  if (blueprint === 'findOne') {
    // do restriction here
    return next();
  }

  res.forbidden('not allowed to do something');
};

I'm rather forget, is blueprint name findOne or findone.

Upvotes: 1

Related Questions