egg实现登录鉴权(三):密码的md5加密及验证

用户登录少不了密码,上一篇只用nickname进行验证。这一篇加上使用md5加密的password作为另一个条件进行登录验证。

需求

  • 通过nickname和password(md5加密后)进行验证登录,查询数据库user表验证nickname和password
    • 存在nickname并且password解密后与数据数据对应成功则生成token返回
    • 反之返回{code:400,msg:'登录失败'}
  • 为了方便操作,加入了一个字符串md5加密的接口(user/getMd5/:data)
    • 传入字符串返回md5加密的密文字符串

环境

  • 数据库(mysql)
    • 数据库名称(database):test,用户名(user):root,密码(password):123456
    • 数据库user表做了一些改变,新加一个password字段

            image.png

  • 依赖包(package.json)
    • 确保安装以下依赖包

            image.png

实现

  • 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',
  };
  // 安全配置 (https://eggjs.org/zh-cn/core/security.html)
  config.security = {
    csrf: {
      enable: false,
      ignoreJSON: true,
    },
    // 允许访问接口的白名单
    domainWhiteList: [ 'http://localhost:8080' ],
  };
  // 跨域配置
  config.cors = {
    origin: '*',
    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,
  };
};
 
  • 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',
  },
};
  • 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;
};
  • 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 {
  // 查询user表,验证密码和花名
  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;
  }
  // 获取用户,不传id则查询所有
  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);
  }
  // 专门对数据进行md5加密的方法,输入明文返回密文
  getMd5Data(data) {
    return crypto.createHash('md5').update(data).digest('hex');
  }
}
module.exports = UserService;
 
  • app/controller/user.js
'use strict';

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

class UserController extends Controller {
  // 登录
  async login() {
    const { ctx, app } = this;
    const data = ctx.request.body;
    // 判断该用户是否存在并且密码是否正确
    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: '登录成功', token };
    } else {
      ctx.body = { code: 400, msg: '登录失败' };
    }
  }
  // 获取所有用户
  async index() {
    const { ctx } = this;
    ctx.body = await ctx.service.user.getUser();
  }
  // 通过id获取用户
  async show() {
    const { ctx } = this;
    ctx.body = await ctx.service.user.getUser(ctx.params.id);
  }
  async getMd5Data() {
    const { ctx } = this;
    ctx.body = await ctx.service.user.getMd5Data(ctx.params.data);
  }
}

module.exports = UserController;
  • 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);
  // 查询
  router.get('/user', controller.user.index);
  router.get('/user/:id', jwt, controller.user.show);
  // 生成经过md5加密后的密文
  router.get('/user/getMd5/:data', controller.user.getMd5Data);
};
  • package.json
{
  "name": "jwt",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "egg": {
    "declarations": true
  },
  "dependencies": {
    "egg": "^2.15.1",
    "egg-cors": "^2.2.3",
    "egg-jwt": "^3.1.7",
    "egg-scripts": "^2.11.0",
    "egg-sequelize": "^5.2.0",
    "mysql2": "^2.0.2"
  },
  "devDependencies": {
    "autod": "^3.0.1",
    "autod-egg": "^1.1.0",
    "egg-bin": "^4.11.0",
    "egg-ci": "^1.11.0",
    "egg-mock": "^3.21.0",
    "eslint": "^5.13.0",
    "eslint-config-egg": "^7.1.0"
  },
  "engines": {
    "node": ">=10.0.0"
  },
  "scripts": {
    "start": "egg-scripts start --daemon --title=egg-server-jwt",
    "stop": "egg-scripts stop --title=egg-server-jwt",
    "dev": "egg-bin dev",
    "debug": "egg-bin debug",
    "test": "npm run lint -- --fix && npm run test-local",
    "test-local": "egg-bin test",
    "cov": "egg-bin cov",
    "lint": "eslint .",
    "ci": "npm run lint && npm run cov",
    "autod": "autod"
  },
  "ci": {
    "version": "10"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "",
  "license": "MIT"
}

自测

  • 花名(nickname)和密码(password)登录

image.png

  • 为了方便开发,临时加入获取md5数据加密的接口

image.png

  • 通过id查询user,需要传token

image.png

  • 查询所有user,不用传token

image.png

参考

原文地址:https://www.cnblogs.com/xingguozhiming/p/12083435.html