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

WeChat applet calculator example

WeChat applet calculator example, for your refere...

A brief analysis of crontab task scheduling in Linux

1. Create a scheduling task instruction crontab -...

Detailed explanation of how to solve the problem of too long content in CSS

When we write CSS, we sometimes forget about the ...

A brief discussion on the principle of Vue's two-way event binding v-model

Table of contents explain: Summarize Replenish Un...

Implementation of waterfall layout + dynamic rendering

Table of contents Typical waterfall website Water...

Detailed explanation of the usage of DECIMAL in MySQL data type

Detailed explanation of the usage of DECIMAL in M...

CSS -webkit-box-orient: vertical property lost after compilation

1. Cause The requirement is to display two lines,...

Native JS to implement image carousel JS to implement small advertising plug-in

Recently I want to use native JS to implement som...

Detailed explanation of the platform bus of Linux driver

Table of contents 1. Introduction to platform bus...

CSS to achieve dynamic secondary menu

Dynamically implement a simple secondary menu Whe...

JavaScript super detailed implementation of web page carousel

Table of contents Creating HTML Pages Implement t...

Setting up VMware vSphere in VMware Workstation (Graphic Tutorial)

VMware vSphere is the industry's leading and ...

MySQL deduplication methods

MySQL deduplication methods 【Beginner】There are v...

Usage and description of HTML tag tbody

The tbody element should be used in conjunction wi...