Express implements login authentication
- 2021-11-29 05:47:50
- OfStack
In this article, we share the specific code of Express login verification for your reference. The specific contents are as follows
Express implementation of the route login, this code is suitable for many scenarios, this record, for later use.
The 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');
// Path to upload configuration files , This is a 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, here to ensure that it is installed
const expressRoute = require('express-route');
const mysql = require('mysql');
var server = express();
server.listen(8080);
// Processing submitted data and documents
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');
// Routing splitting
server.use('/', require('./route/web/index.js')()); // Foreground routing
server.use('/admin/', require('./route/admin/index.js')()); // Background routing
// Static data
server.use(static('./static/'));
Above, this is an overall structural framework, and you only need to focus on the routing part in the follow-up. 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 routes based on traffic
router.use('/banners', require('./banners')());
return router;
};
The modularization of express is actually defined according to the routing level 1. Next, let's look at the implementation of login code in the above code.
const express = require('express');
// Public method of encapsulation (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 data returned is very simple, and it is actually returned 1 Objects
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(' Password error ').end();
}
}
}
});
});
return router;
};
You may notice the introduction of an common module in the above code. This file mainly defines 1 common methods, such as 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');
}
};