Home  >  Article  >  Web Front-end  >  Detailed explanation of user rights management of nodejs acl

Detailed explanation of user rights management of nodejs acl

亚连
亚连Original
2018-05-30 11:13:362674browse

This article mainly introduces the detailed explanation of user rights management of nodejs acl. Now I share it with you and give you a reference.

Instructions

Q: What is this tool used for?

A: Users have different permissions, such as administrator, vip, ordinary Users, each user accesses the API, and the page is different

nodejs has two well-known permission management modules, one is acl and the other is rbac. After a comprehensive comparison, I finally chose acl## when working on the project.

#Function list:

    ##addUserRoles //Add a role to a user
  1. removeUserRoles //Remove A certain user role
  2. userRoles //Get all the roles of a certain user
  3. roleUsers //Get all the users with this role
  4. hasRole // Whether a user is a certain role
  5. addRoleParents //Add a parent role to a certain role
  6. removeRoleParents //Remove a certain parent role or all parent roles
  7. removeRole //Remove a certain role
  8. removeResource //Remove A certain resource
  9. allow //Add certain permissions to certain resources to certain roles
  10. removeAllow //Remove certain permissions for certain roles Certain permissions for certain resources
  11. allowedPermissions //Query all resources and permissions of a person
  12. isAllowed //Query whether a person is There is a certain permission for a certain resource
  13. areAnyRolesAllowed //Query whether a certain role has a certain permission for a certain resource
  14. whatResources //Query whether a certain role has a certain permission Which resources
  15. middleware //middleware for express
  16. backend //Specification method (mongo/redis...)
ACL nouns and their main methods

roles Role

##removeRole
  1. addRoleParents
  2. allow
  3. removeAllow
  4. ##resources Resources

whatResources

  1. removeResource

  2. permissions Permissions

users Users


allowedPermissions

  1. isAllowed

  2. addUserRoles

  3. ##removeUserRoles

  4. userRoles

  5. roleUsers

  6. hasRole

  7. areAnyRolesAllowed

  8. How to use

Create the configuration file

  1. Assign corresponding permissions after the user logs in

  2. Use acl for verification where control is required

  3. Configuration file

  4. const Acl = require('acl');
    const aclConfig = require('../conf/acl_conf');
    
    module.exports = function (app, express) {
      const acl = new Acl(new Acl.memoryBackend()); // eslint-disable-line
    
      acl.allow(aclConfig);
    
      return acl;
    };
    
    // acl_conf
    
    module.exports = [
      {
        roles: 'normal', // 一般用户
        allows: [
          { resources: ['/admin/reserve'], permissions: ['get'] },
        ]
      },
      {
        roles: 'member', // 会员
        allows: [
          { resources: ['/admin/reserve', '/admin/sign'], permissions: ['get'] },
          { resources: ['/admin/reserve/add-visitor', '/admin/reserve/add-visitor-excel', '/admin/reserve/audit', '/admin/sign/ban'], permissions: ['post'] },
        ]
      },
      {
        roles: 'admin',  // 管理
        allows: [
          { resources: ['/admin/reserve', '/admin/sign', '/admin/set'], permissions: ['get'] },
          { resources: ['/admin/set/add-user', '/admin/set/modify-user'], permissions: ['post'] },
        ]
      },
      {
        roles: 'root', // 最高权限
        allows: [
          { resources: ['/admin/reserve', '/admin/sign', '/admin/set'], permissions: ['get'] },
        ]
      }
    ];

proofcheck

This is a proofreading combined with express... It turned out that the middleware provided by acl itself was too useless, so I rewrote one here.

function auth() {
    return async function (req, res, next) {
      let resource = req.baseUrl;
      if (req.route) { // 正常在control中使用有route属性 但是使用app.use则不会有
        resource = resource + req.route.path;
      }
      console.log('resource', resource);

      // 容错 如果访问的是 /admin/sign/ 后面为 /符号认定也为过
      if (resource[resource.length - 1] === '/') {
        resource = resource.slice(0, -1);
      }

      let role = await acl.hasRole(req.session.userName, 'root');

      if (role) {
        return next();
      }

      let result = await acl.isAllowed(req.session.userName, resource, req.method.toLowerCase());
      // if (!result) {
      //   let err = {
      //     errorCode: 401,
      //     message: '用户未授权访问',
      //   };
      //   return res.status(401).send(err.message);
      // }
      next();
    };
  }

One thing to note is that express.Router supports exporting a Router module and then using it in app.use, but if you use app.use('/ admin/user',auth(), userRoute); Then the req.route attribute cannot be obtained in the auth function. Because acl does a strong match on access permissions, it needs to have a certain degree of fault tolerance

Login permission allocation

result is the user information queried from the database, or the background The user information returned by the api can be used in the form of a configuration file for the switch here. Because I only have three permissions for this project, I will briefly write it here.

let roleName = 'normal';

  switch (result.result.privilege) {
    case 0:
      roleName = 'admin';
      break;
    case 1:
      roleName = 'normal';
      break;
    case 2:
      roleName = 'member';
      break;
  }

  if (result.result.name === 'Nathan') {
    roleName = 'root';
  }

  req.session['role'] = roleName;
  // req.session['role'] = 'root';  // test
  acl.addUserRoles(result.result.name, roleName);
  // acl.addUserRoles(result.result.name, 'root'); // test

Rendering logic control in pug page

In express pug app.locals.auth= async function (){} This way of writing will not produce the final result when pug is rendered, because pug is synchronous, so how do I control whether the current page or the user of the button on the current page has permission to display it? The common methods here are

The user has a routing table and component table when logging in, and then renders according to this table when rendering

  1. When permission control is required Where, use a function to determine whether the user has permission to access

  2. I am using the ending plan 2. Because it is more convenient, but the problem is that express pug does not support asynchronous writing. What acl provides us is all asynchronous. Due to time reasons, I did not delve into the judgment inside, but adopted a judgment method with higher coupling but more convenient.

  3. app.locals.hasRole = function (userRole, path, method = 'get') {
    
      if (userRole === 'root') {
        return true;
      }
    
      const current = aclConf.find((n) => {
        return n['roles'] === userRole;
      });
    
      let isFind = false;
      for (let i of current.allows) {
        const currentPath = i.resources; // 目前数组第一个为单纯的get路由
        isFind = currentPath.includes(path);
    
        if (isFind) {
          // 如果找到包含该路径 并且method也对应得上 那么则通过
          if (i.permissions.includes(method)) {
            break;
          }
    
          // 如果找到该路径 但是method对应不上 则继续找.
          continue;
        }
      }
    
      return isFind;
    };

The above code page is relatively simple. It traverses acl_conf to find out whether the user has permissions for the current page or button. Because acl_conf has been written into the memory when loading, the performance consumption will not be special. big. Such as the following example.

if hasRole(user.role, '/admin/reserve/audit', 'post')
          .col.l3.right-align
            a.waves-effect.waves-light.btn.margin-right.blue.font12.js-reviewe-ok 同意
            a.waves-effect.waves-light.btn.pink.accent-3.font12.js-reviewe-no 拒绝

End

Relying on the acl component, you can quickly create a user rights management module. But there is still a problem, that is, the app.locals.hasRole function. If you use removeAllow to dynamically change the user's permission table, then the hasRole function will be very troublesome. So in this case there are several solutions:

Start with the acl source code

  1. Prepare the data every time you render

  2. const hasBtn1Role = hasRole(user.role, '/xxx','get');
    res.render('a.pug',{hasBtn1Role})

  3. The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

    Related articles:

    How to use better-scroll plug-in in Angular_AngularJS

    Angularjs implementation between controllers Summary of communication method examples

    JavaScript code to implement the upload preview function of txt files

The above is the detailed content of Detailed explanation of user rights management of nodejs acl. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn