search
HomeWeb Front-endJS TutorialDetailed explanation of user rights management of nodejs acl

Detailed explanation of user rights management of nodejs acl

May 30, 2018 am 11:13 AM
javascriptnodejsDetailed explanation

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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!