How to create dynamic policies in sails.js

I worked on a project where I need to create and assign policies according to access rights / levels for a user in sails.js

Each user can access all levels below his level, for example, the administrator has level 9, and he can access all levels below level 9

Currently, all sails are stored in sails.

API / Policy

and assigned to the controller in

config / policy.js

module.exports.policies = {

UserController: {
    "create": ['canCreate'],
    "list": ['canRead'],
    "show": ['canRead'],
},
AuthController: {
    '*': true,
}};

My question is: how can I create dynamic policies based on access levels coming from db

I have googled but nothing was found about how to create dynamic policies in sails.js, so post here.

Appreciate your help on this.

thank

+4
4

.

sails.js Waterline. pass.js, , .

+2

.

/level01.js /level 02.js ect.,.

/, , .

/level01.js

module.exports = function(req,res,next){
 if(req.session.accessLevel = 1) return next();
 return res.forbidden();
}

module.exports.policies = {
UserController: {
    "create": ['policyXX.js'],
    "list": ['policyXX.js'],
    "show": ['policyXX.js'],
},
AuthController: {
    '*': true,
}};

- , , . , .

+1

@Travis Webb's solution is a good one. You can also create model roles and model resolution, linked by relationships (from one to many, from many to many ...), as you wish, and then filter them using this policy:

Example:

module.exports = function isAdmin (req, res, next) {
    if (typeof req.session.User != "undefined") {
    User.findOne(req.session.User.id).populate('roles').exec(function(err,user){
           if(err) return res.forbidden('You are not permitted to perform this action.');
           if(!user) return res.redirect('/user/new');
           for(var i in user.roles){
                if(user.roles[i]['name'] == 'ROLE_ADMIN'){
                    return next();
                }
           }
           return res.redirect('/user/show/'+req.session.User.id);
        });
    } else {
        return res.redirect('/session/new');
    }
};

Regards

+1
source

After a year and a half, if someone comes across this, sails-must seem like a good solution for this.

RabbitController: {
    nurture: must().be.a('rabbit').mother,
    feed: [must().be.nice.to('rabbits'), must().have('rabbit').food]
},

Disclaimer: I have not used it myself.

0
source

Source: https://habr.com/ru/post/1583748/


All Articles