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(); }; }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 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})
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!

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.

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 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 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.

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 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.

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'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.


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

WebStorm Mac version
Useful JavaScript development tools

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
Small size, syntax highlighting, does not support code prompt function

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
Recommended: Win version, supports code prompts!
