The previous article implemented basic token generation and token validation, which isn’t really useful. The main implementation of this article is to validate the people in the database.

Project warehouse

Github.com/XingGuoZM/e…

demand

  • Login: Query the database’s user table to verify that this person exists
    • The nickname exists in the user table, and the token is generated
    • {code:’404′, MSG :’ no nickname ‘}
  • The query
  • Query all users without passing tokens
  • To query the specified user by ID, you need to pass the token
  • Status code
    • 201: success
    • 404: Does not exist
    • 400: The service logic is incorrect

implementation

  • The database table has not changed. There is still only one user table
    • Database: test; User: root; Password: 123456

  • Install the dependency packages on top of the login authentication (1) implemented by the Egg
npm install --save egg-cors egg-jwt
Copy the code
  • directory

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),}, {timestamps: false});return User;
};
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
    const isValid = await ctx.service.user.isValidUser('nickname', data.nickname);
    if (isValid) {
      const token = app.jwt.sign({
        nickname: data.nickname,
      }, app.config.jwt.secret);
      ctx.body = token;
    } else {
      ctx.body = { code: 404.msg: 'The user does not exist'}; }}// 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 = awaitctx.service.user.getUser(ctx.params.id); }}module.exports = UserController;
Copy the code

app/service/user.js

'use strict';

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

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

class UserService extends Service {
  // Query the test database user table to verify whether the user exists
  async isValidUser(key, value) {
    const data = await this.getUser();
    for (const item of data) {
      if (item[key] === value) 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 awaitctx.model.User.findAll(query); }}module.exports = UserService;
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);
};
Copy the code

self-test

  • The login

  • Query all

  • Queries the person with the specified ID

reference

  • An egg + sequelize + mysql CRUD
  • Login Authentication with Egg (1)