The user login requires a password, and only the nickname is used for authentication. This article adds the use of MD5 encrypted passwords as another condition for login authentication.

demand

  • Procedure Verify the login using the nickname and password(encrypted by MD5). Query the database user table to verify the nickname and password
    • If the nickname exists and the password successfully corresponds to the data after decryption, the token is generated and returned
    • Return {code:400, MSG :’ login failed ‘}
  • For ease of operation, a string MD5 encryption interface (user/getMd5/:data) has been added.
    • Returns an MD5 encrypted ciphertext string passed in

The environment

  • Database (mysql)
    • Database: test; User: root; Password: 123456
    • A new password field has been added to the user table of the database

  • Dependency packages (package.json)
    • Ensure that the following dependency packages are installed

implementation

config/config.default.js

/* eslint valid-jsdoc: "off" */

'use strict';

/ * * *@param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo= > {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}* * /
  const config = exports = {};

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1576461360545_5788';

  // add your middleware config here
  config.middleware = [];
  config.jwt = {
    secret: '123456'};// Security configuration (https://eggjs.org/zh-cn/core/security.html)
  config.security = {
    csrf: {
      enable: false.ignoreJSON: true,},// Whitelist of the interfaces that are allowed to access
    domainWhiteList: [ 'http://localhost:8080']};// Cross-domain configuration
  config.cors = {
    origin: The '*'.allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'}; config.sequelize = {dialect: 'mysql'.host: '127.0.0.1'.port: '3306'.user: 'root'.password: '123456'.database: 'test'.define: {
      underscored: true.freezeTableName: true,}};// add your user config here
  const userConfig = {
    // myAppName: 'egg',
  };

  return{... config, ... userConfig, }; };Copy the code

config/plugin.js

'use strict';

/ * *@type Egg.EggPlugin */
module.exports = {
  jwt: {
    enable: true.package: 'egg-jwt',},cors: {
    enable: true.package: 'egg-cors',},sequelize: {
    enable: true.package: 'egg-sequelize',}};Copy the code

app/model/user.js

'use strict';

module.exports = app= > {
  const { STRING, INTEGER } = app.Sequelize;
  const User = app.model.define('user', {
    id: { type: INTEGER, primaryKey: true.autoIncrement: true },
    nickname: STRING(20),
    password: STRING(50),}, {timestamps: false});return User;
};
Copy the code

app/service/user.js

'use strict';

const Service = require('egg').Service;
const crypto = require('crypto');

function toInt(str) {
  if (typeof str === 'number') return str;
  if(! str)return str;
  return parseInt(str, 10) | |0;
}

class UserService extends Service {
  // Query the user table to verify the password and the flower name
  async validUser(nickname, password) {
    const data = await this.getUser();
    const pwd = crypto.createHash('md5').update(password).digest('hex');
    for (const item of data) {
      if (item.nickname === nickname && item.password === pwd) return true;
    }
    return false;
  }
  // Obtain the user. If no id is sent, query all
  async getUser(id) {
    const { ctx } = this;
    const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) };

    if (id) {
      return await ctx.model.User.findByPk(toInt(id));
    }
    return await ctx.model.User.findAll(query);
  }
  // The md5 encryption method is used to encrypt data. Input plaintext and return ciphertext
  getMd5Data(data) {
    return crypto.createHash('md5').update(data).digest('hex'); }}module.exports = UserService;
Copy the code

app/controller/user.js

'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  / / login
  async login() {
    const { ctx, app } = this;
    const data = ctx.request.body;
    // Check whether the user exists and whether the password is correct
    const isValidUser = await ctx.service.user.validUser(data.nickname, data.password);
    if (isValidUser) {
      const token = app.jwt.sign({ nickname: data.nickname }, app.config.jwt.secret);
      ctx.body = { code: 200.msg: 'Login successful', token };
    } else {
      ctx.body = { code: 400.msg: 'Login failed'}; }}// Get all users
  async index() {
    const { ctx } = this;
    ctx.body = await ctx.service.user.getUser();
  }
  // Obtain the user by id
  async show() {
    const { ctx } = this;
    ctx.body = await ctx.service.user.getUser(ctx.params.id);
  }
  async getMd5Data() {
    const { ctx } = this;
    ctx.body = awaitctx.service.user.getMd5Data(ctx.params.data); }}module.exports = UserController;
Copy the code

app/router.js

'use strict';

/ * * *@param {Egg.Application} app - egg application
 */
module.exports = app= > {
  const { router, controller, jwt } = app;
  router.get('/', controller.home.index);

  router.post('/user/login', controller.user.login);
  / / query
  router.get('/user', controller.user.index);
  router.get('/user/:id', jwt, controller.user.show);
  // Generate the md5 encrypted ciphertext
  router.get('/user/getMd5/:data', controller.user.getMd5Data);
};
Copy the code

self-test

  • Nickname and password login

  • To facilitate development, the interface for obtaining MD5 data encryption is added temporarily

  • To query the user by ID, you need to pass the token

  • Query all users without passing tokens

reference

  • www.cnblogs.com/malng/p/946…