Detailed explanation of user rights management of nodejs acl
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
- removeUserRoles //Remove A certain user role
- userRoles //Get all the roles of a certain user
- roleUsers //Get all the users with this role
- hasRole // Whether a user is a certain role
- addRoleParents //Add a parent role to a certain role
- removeRoleParents //Remove a certain parent role or all parent roles
- removeRole //Remove a certain role
- removeResource //Remove A certain resource
- allow //Add certain permissions to certain resources to certain roles
- removeAllow //Remove certain permissions for certain roles Certain permissions for certain resources
- allowedPermissions //Query all resources and permissions of a person
- isAllowed //Query whether a person is There is a certain permission for a certain resource
- areAnyRolesAllowed //Query whether a certain role has a certain permission for a certain resource
- whatResources //Query whether a certain role has a certain permission Which resources
- middleware //middleware for express
- backend //Specification method (mongo/redis...)
roles Role
##removeRole- addRoleParents
- allow
- removeAllow
##resources Resources
whatResources
removeResource
permissions Permissions
allowedPermissions
isAllowed
addUserRoles
- ##removeUserRoles
- userRoles
- roleUsers
- hasRole
- areAnyRolesAllowed
- How to use
- Assign corresponding permissions after the user logs in
- Use acl for verification where control is required
- Configuration file
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(); }; }
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 areThe user has a routing table and component table when logging in, and then renders according to this table when rendering
- When permission control is required Where, use a function to determine whether the user has permission to access
- 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.
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; };
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
- Prepare the data every time you render
const hasBtn1Role = hasRole(user.role, '/xxx','get'); res.render('a.pug',{hasBtn1Role})
Copy after loginThe 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application
