Home > Web Front-end > JS Tutorial > body text

How to build a permission management system using Node.js

PHPz
Release: 2023-04-05 09:17:59
Original
1619 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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")
Copy after login

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');
});
Copy after login

This code includes the following steps:

  1. Import all Requires Node.js module and connects to MongoDB database.
  2. Define two MongoDB collections User and Role.
  3. Configure the Express application and define the middleware function for validating user roles.
  4. Define Express routing, including root routing, login routing, dashboard routing and logout routing.
  5. 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 === &#39;undefined&#39;) { %>
      <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>
Copy after login
<!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>
Copy after login
<!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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template