What is the best way to implement roles and permissions in Express REST Api

I need an expert opinion to implement Roles and Permissions in Express js. I plan to develop Restful Api using Express js, but have not received enough information to implement Roles and Permissions, although tons of options are available for authentication and authorization.

+4
source share
1 answer

Create tables

First you need to create your own tables, which will contain associations between roles, permissions and resources:

  • Create a role table ('Admin', 'User', 'Guest')
  • Create a resource table ("Users", "Projects", "Programs")
  • ( "", "", "", "", "" )

, . , "Deny", Read!= True.

, , role_id resource_id , true.

, . , , , :

users.post('/', getAuth, handleUserPost)

, - , , , , :

getAuth = function (req, res, next) {
  if(req.user) { 
    db.getPerms({role_id: req.user.role_id, resource_id: req.resource.id})
       .then(function(perms){
          var allow = false;
          //you can do this mapping of methods to permissions before the db call and just get the specific permission you want. 
          perms.forEach(function(perm){
              if (req.method == "POST" && perms.create) allow = true;
              else if (req.method == "GET" && perms.read) allow = true;
              else if (req.method == "PUT" && perms.write) allow = true;
              else if (req.method == "DELETE" && perm.delete) allow = true;

          })
          if (allow) next();
          else res.status(403).send({error: 'access denied'});
       })//handle your reject and catch here
   } else res.status(400).send({error: 'invalid token'})
}

, , .

+7

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


All Articles