Home >Web Front-end >JS Tutorial >How to build a permission management system using Node.js
As the complexity of web applications increases, permission management becomes more and more important. Managing users and user roles, as well as restricting access to certain pages, has become an essential part of web applications. Node.js is a very popular server-side JavaScript environment that helps build efficient web applications. In this article, we will learn how to build a permission management system using Node.js.
Permission management is the process of controlling what users can access and perform. It involves managing users and user roles, allocation of resources and permissions, etc.
In a Web application, permission management is very important, whether it is protecting sensitive information or controlling user access permissions. Different users may have different access rights, depending on their roles and permissions.
Node.js is an event-driven server-side JavaScript environment that is ideal for building efficient web applications. Using Node.js to build a permission management system can provide the following advantages:
The following are the steps to build a permission management system using Node.js:
To start using Node.js, you need to install it first. You can go to [Node.js official website](https://nodejs.org/en/) to download the latest version of Node.js. After running the installer, you can verify from the command line that Node.js is installed correctly. Type the following command into the command line:
node -v
If the installation is successful, you will see the version number of Node.js.
Now that you have Node.js installed, you need to set up the project. Go to the project folder on the command line and enter the following command:
npm init
This command will guide you to create a new package.json file. This file is a manifest for a JavaScript project that contains all of the project's information and dependencies.
In Node.js, you can easily use the package manager npm to install the required modules. Enter the following command on the command line to install the required modules:
npm install express body-parser cookie-parser express-session connect-flash --save
You will also need a database to store user and role information. In this article, we will use MongoDB.
First, you need to install MongoDB. You can download the latest version of MongoDB from [MongoDB official website](https://www.mongodb.com/).
Then you need to create a new database and collection in MongoDB. Enter the following command at the command line:
mongo use mydb db.createCollection("users") db.createCollection("roles")
This code will create a database named "mydb", and two collections named "users" and "roles".
Now that you have completed all the preparations, you can start writing the code. In the project directory, create a file called "app.js" and add the following code to the file:
const express = require('express'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const flash = require('connect-flash'); const mongoose = require('mongoose'); const app = express(); mongoose.connect('mongodb://localhost/mydb'); const User = mongoose.model('User', { name: String, password: String, role: String }); const Role = mongoose.model('Role', { name: String, permissions: [String] }); app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ secret: 'secret key', resave: false, saveUninitialized: false })); app.use(flash()); const requireRole = (role) => { return (req, res, next) => { if (req.session.user && req.session.user.role === role) { next(); } else { req.flash('error', 'Permission denied'); res.redirect('/login'); } }; }; app.get('/', (req, res) => { res.render('index'); }); app.get('/login', (req, res) => { res.render('login', { error: req.flash('error') }); }); app.post('/login', (req, res) => { User.findOne({ name: req.body.name, password: req.body.password }, (err, user) => { if (err) { req.flash('error', 'Login failed'); res.redirect('/login'); } else if (!user) { req.flash('error', 'Invalid user or password'); res.redirect('/login'); } else { req.session.user = user; res.redirect('/dashboard'); } }); }); app.get('/dashboard', requireRole('manager'), (req, res) => { res.render('dashboard'); }); app.get('/logout', (req, res) => { req.session.destroy(); res.redirect('/login'); }); app.listen(3000, () => { console.log('Server started at http://localhost:3000'); });
This code includes the following steps:
Finally, you need to create views to present your web application.
In the project directory, create a folder called "views" and create the following view files:
<!doctype html> <html> <head> <title>Node.js Authorization</title> </head> <body> <h1>Node.js Authorization</h1> <nav> <% if (typeof user === 'undefined') { %> <a href="/login">Sign in</a> <% } else { %> <a href="/dashboard">Dashboard</a> <a href="/logout">Sign out</a> <% } %> </nav> <hr> <p>Welcome to Node.js Authorization.</p> </body> </html>
<!doctype html> <html> <head> <title>Node.js Authorization - Login</title> </head> <body> <h1>Node.js Authorization - Login</h1> <% if (error) { %> <p><%= error %></p> <% } %> <form method="post" action="/login"> <div> <label for="name">Name:</label> <input type="text" name="name" required> </div> <div> <label for="password">Password:</label> <input type="password" name="password" required> </div> <div> <input type="submit" value="Sign in"> </div> </form> </body> </html>
<!doctype html> <html> <head> <title>Node.js Authorization - Dashboard</title> </head> <body> <h1>Node.js Authorization - Dashboard</h1> <nav> <a href="/">Home</a> <a href="/logout">Sign out</a> </nav> <hr> <h2>Welcome <%= user.name %>.</h2> <p>You are logged in as a manager.</p> </body> </html>
These three views are slightly different. The index.ejs route can be accessed directly, the login.ejs route is controlled when not logged in, and dashboard.ejs can only be accessed by users with the identity of manager.
Node.js is a great tool for building efficient web applications. It provides numerous features and modules to help you build a powerful permission management system easily. With Node.js you can develop quickly, perform well, be scalable, and it's free. Node.js also has an active community that provides tons of support and resources.
In this article, we learned how to build a permission management system using Node.js. We learned how to use MongoDB to store user and role information, how to build web applications using Express.js, and how to use a template engine to render views.
I hope this article is helpful to you, thank you for reading.
The above is the detailed content of How to build a permission management system using Node.js. For more information, please follow other related articles on the PHP Chinese website!