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.
What is permission management?
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.
Why use Node.js for permission management?
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:
- Rapid development: Node.js provides numerous modules and libraries that can greatly reduce development time.
- High performance: Because Node.js is non-blocking, it can handle a large number of concurrent requests.
- Extensibility: Node.js allows you to easily add and extend modules.
- Cost: Node.js is free and has extensive documentation and community resources.
Build a permission management system using Node.js
The following are the steps to build a permission management system using Node.js:
Step 1: Install 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.
Step 2: Set up the project
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.
Step 3: Install the required Node.js modules
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:
- express: A framework for creating web applications.
- body-parser: used to parse the data in the request body.
- cookie-parser: used to parse data in cookies.
- express-session: used to manage sessions.
- connect-flash: used to display flash messages.
npm install express body-parser cookie-parser express-session connect-flash --save
Step 4: Create a database
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".
Step 5: Write the code
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:
- Import all Requires Node.js module and connects to MongoDB database.
- Define two MongoDB collections User and Role.
- Configure the Express application and define the middleware function for validating user roles.
- Define Express routing, including root routing, login routing, dashboard routing and logout routing.
- Start the Express application and listen on port 3000.
Step 6: Create Views
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:
- index.ejs: used to render the homepage.
- login.ejs: used to present the login interface.
- dashboard.ejs: used to render the dashboard.
<!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.
Conclusion
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!

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

AI Hentai Generator
Generate AI Hentai for free.

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

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig
