This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Whether in the actual project or in the interview, as long as it relates to the project, how to verify the registration and login is always the favorite of the interviewer. This time, let’s systematically comb out how to complete the verification of a login. (Note: The project implementation is based on egg.js as the background implementation.)

Step 1: Configure the middleware

  1. Create the Adminauth.js file under middleware
  • The CSRF global variable needs to be configured in the middleware to ensure that the form POST data can normally reach the controller login.js
  • Retrieve the user’s request path without request parameters through the URL module
  • First, check whether userInfo and USERNAME exist in the session. The execution is allowed to continue only when both conditions are met. If either of the two conditions is not met, check whether the path is related to login. If the login path is not involved, go to the login page for the user to log in.
const url = require("url");

module.exports = (options) = > {
  return async function adminAuth(ctx,next) {
    console.log("Middleware");
    console.log(ctx.request.url);
    // Configure global variables
    ctx.state.csrf = ctx.csrf;
    const pathname = url.parse(ctx.request.url).pathname;
    if (ctx.session.userinfo && ctx.session.userinfo.username) {
      await next();
    } else {
      // Jump to login without permission
      if (pathname === "/admin/login" || pathname === "/admin/doLogin" || pathname === "/admin/login/captcha") {
        await next();        
      } else {
        ctx.redirect("/admin/login"); }}// await next();}}Copy the code
  1. Register middleware in config.default.js
  • Set the middleware to intercept only paths containing /admin.
  config.middleware = ["adminAuth"];
  config.adminAuth = {
    match: '/admin'
  }
Copy the code

Step 2: Use Sequelize to manipulate the database

Database structure

  • Data table structure

  • Install the Sequelize plug-in
npm install --save egg-sequelize mysql2
Copy the code
  • Introduce plug-ins in plugin.js
module.exports = {
  // had enabled by egg
  static: {
    enable: true
  },
  ejs: {
    enable: true.package: 'egg-view-ejs'
  },
  sequelize: {
    enable: true.package: 'egg-sequelize',}}Copy the code
  • Configure basic database information in config.default.js
  config.sequelize = {
    dialect: 'mysql'.host: 'localhost'.port: 3306.username: "root".password: "123456".database: 'eggshop'};Copy the code
  • Create a new model folder under app and create admin.js in this folder
'use strict';

module.exports = app= > {
  const { STRING, INTEGER, DATE } = app.Sequelize;

  const Admin = app.model.define('admin', {
    id: {type: INTEGER,primaryKey: true.autoIncrement: true},
    username: STRING(255),
    password: STRING(32),
    mobile: STRING(32),
    email: STRING(255),
    status: INTEGER(1),
    roleId: INTEGER(11),
    addTime: INTEGER(11),
    isSuper: INTEGER(1),
    lastLogin: INTEGER(11),
  },{
    timestamps: false.tableName: 'admin'     
  });

  return Admin;
};
Copy the code

Step 3: Process login information

The user password is encrypted by MD5

  1. Installing the MD5 Module
npm install md5
Copy the code
  1. Encapsulate MD5 in the service
const md5 = require('md5');
class ToolsService extends Service {
  md5(msg) {
    returnmd5(msg); }}Copy the code

Handles the core login logic in the controller

  1. Obtain the user name, password, and verification code entered by the user.
  2. Check whether the verification code entered by the user is consistent with the verification code in the session. If they are inconsistent, go to the login page. If they are consistent, go to step 3.
  3. Use the Sequelize framework to check whether the user name and password exist in the database. If yes, go to the management module; if no, go to the login module.

Note: The server stores the verification code when the user obtains the verification code, that is, the user obtains the verification code and stores the verification code on the server.