Express implements login verification

Express implements login verification

This article example shares the specific code for Express to implement login verification for your reference. The specific content is as follows

The routing login implemented by Express is applicable to many scenarios. This code is recorded for future use.

First is the main file: server.js

const express = require('express');
const static = require('express-static');
const bodyParser = require('body-parser');
const multer = require('multer');
// The path to upload the configuration file, here is the local address const multerObj = multer({ dest: './static/upload' });
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const consolidate = require('consolidate');
 
// The sub-route page needs to be used, make sure it has been installed const expressRoute = require('express-route');
const mysql = require('mysql');
 
var server = express();
server.listen(8080);
 
// Process submitted data and files server.use(bodyParser.urlencoded());
server.use(multerObj.any());
 
// cookie and signature processing server.use(cookieParser());
(function () {
    var keys = [];
    for (var i = 0; i < 100000; i++) {
        keys[i] = 'secret' + Math.random();
    };
    server.use(cookieSession({
        name: 'session_id',
        keys: keys,
        maxAge: 20 * 60 * 1000  
    }));
})();
 
// Template rendering server.engine('html', consolidate.ejs);
server.set('views', 'template');
server.set('view engine', 'html');
 
// Route splitting server.use('/', require('./route/web/index.js')()); // Front-end routing server.use('/admin/', require('./route/admin/index.js')()); // Back-end routing // Static data server.use(static('./static/'));

The above is an overall structural framework. In the future, you only need to focus on the routing part. The following is the background routing part.

const express = require('express');
 
module.exports = function () {
 
    var router = express.Router();
 
    // Before logging in router.use((req, res, next) => {
        if (!req.session['admin_id'] && req.url != '/login') { 
            res.redirect('/admin/login');
        } else {
            next();
        }
    });
    router.use('/login', require('./login')());
 
    
    // Other routes after normal login router.get('/', (req, res) => {
        res.render('admin/index.ejs', {});
    });
    // Add routing based on business router.use('/banners', require('./banners')());
 
    return router;
};

The modularity of express is actually defined by routing level by level. Next, let's take a look at the implementation of the login code in the above code.

const express = require('express');
// Encapsulated public method (md5) encryption module const common = require('../../libs/common');
const mysql = require('mysql');
 
var db = mysql.createPool({ 
    host: 'localhost', 
    user: 'root', 
    password: '123456', 
    database: 'blog' 
});
 
module.exports = function () {
    var router = express.Router();
    router.get('/', (req, res) => {
        res.render('admin/login.ejs', {});
    });
    
    router.post('/', (req, res) => {
        var username = req.body.username;
        var password = common.md5(req.body.password + common.MD5_SUFFIX);
        db.query(`SELECT * FROM admin_table WHERE username='${username}'`, (err, data) => {
            if (err) {
                // The returned data is very simple. Actually, an object is returned.res.status(500).send('Database connection error').end();
            } else {
                if (data.length == 0) {
                    res.status(400).send('Administrator does not exist').end();
                } else {
                    if (data[0].password == password) {
                        req.session['admin_id'] = data[0].ID;
                        res.redirect('/admin/');
                    } else {
                        res.status(400).send('Wrong password').end();
                    }
                }
            }
        });
    });
 
    return router;
};

You may have noticed that there is an import of the common module in the above code. This file mainly defines some common methods, such as the md5 encryption method.

const crypto = require('crypto');
module.exports = {
    MD5_SUFFIX: 'FDSW$t34tregt5tO&$(#RHuyoyiUYE*&OI$HRLuy87odlfh)',
    md5: function (str) {
        var obj = crypto.createHash('md5');
        obj.update(str);
        return obj.digest('hex');
    }
};

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Express + Session to implement login verification function
  • Nodejs Advanced: express+session to achieve simple login authentication
  • Node.js+Express+MySql to realize user login and registration functions
  • Use node and express to connect to mysql to implement login and registration code
  • Node+Express+MongoDB to implement login and registration functions
  • How to use jwt to implement verification in express framework
  • Express + jwt + postMan verification to achieve persistent login
  • Sample code for implementing login status permission verification with Vue+Express
  • Nodejs uses express to obtain get and post value transfer and session verification method
  • DevExpress implements GridControl cell editing verification method

<<:  The forgotten button tag

>>:  Docker cleaning killer/Docker overlay file takes up too much disk space

Recommend

How to create a MySQL database and support Chinese characters

Let's first look at the MySQL official docume...

MySQL Packet for query is too large problem and solution

Problem description: Error message: Caused by: co...

An in-depth summary of MySQL time setting considerations

Does time really exist? Some people believe that ...

Complete steps to use samba to share folders in CentOS 7

Preface Samba is a free software that implements ...

How to reduce memory usage and CPU usage of web pages

Some web pages may not look large but may be very...

How to implement the singleton pattern in Javascript

Table of contents Overview Code Implementation Si...

Example code for implementing a simple search engine with MySQL

Table of contents Preface Introduction ngram full...

Vue+element ui realizes anchor positioning

This article example shares the specific code of ...

Implementation of HTML to PDF screenshot saving function

Using Technology itext.jar: Convert byte file inp...

Detailed explanation of nodejs built-in modules

Table of contents Overview 1. Path module 2. Unti...

An article to understand Linux disks and disk partitions

Preface All hardware devices in the Linux system ...

Detailed explanation of the fish school algorithm in CocosCreator game

Preface I recently wanted to learn CocosCreator, ...

How to implement remote access control in Centos 7.4

1. SSH remote management SSH is a secure channel ...

How to configure Jupyter notebook in Docker container

Jupyter notebook is configured under the docker c...