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

Baota Linux panel command list

Table of contents Install Pagoda Management Pagod...

HTML page jump code

Save the following code as the default homepage fi...

This article helps you understand PReact10.5.13 source code

Table of contents render.js part create-context.j...

Manually install mysql5.7.10 on Ubuntu

This tutorial shares the process of manually inst...

How to deploy nodejs service using Dockerfile

Initialize Dockerfile Assuming our project is nam...

vue2.x configuration from vue.config.js to project optimization

Table of contents Preface vue.config.js configura...

Let's deeply understand the event object in js

We know that the commonly used events in JS are: ...

Detailed explanation of bash command usage

On Linux, bash is adopted as the standard, which ...

Detailed explanation of table return and index coverage examples in MySQL

Table of contents Index Type Index structure Nonc...

TypeScript problem with iterating over object properties

Table of contents 1. Problem 2. Solution 1. Decla...