egg实现登录鉴权(四):人员新增和密码修改

需求

  • 新增人员
    • 请求header中需加token
    • 新增直接传nickname,nickname不重名
    • password默认是123456的md5加密密文
  • 修改密码
    • 请求header中需加token
    • 传参:新密码

实现

代码基本上没有改动,只需要改动路由(router.js),控制器(controller),服务(service)

    • 数据库
    • 依赖包
    • config/config.default.js
    • config/plugin.js
    • app/model/user.js
  • 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;
    const data = await ctx.service.user.getUser();
    ctx.body = { code: 200, msg: '查询成功', data };
  }
  // 通过id获取用户
  async show() {
    const { ctx } = this;
    const data = await ctx.service.user.getUser(ctx.params.id);
    ctx.body = { code: 200, msg: '查询成功', data };
  }
  // 创建人员
  async create() {
    const { ctx } = this;
    const { nickname } = ctx.request.body;
    await ctx.service.user.addUser(nickname);
    ctx.body = { code: 200, msg: '新增成功' };
  }
  // 修改密码
  async updatePwd() {
    const { ctx } = this;
    const { password } = ctx.request.body;
    await ctx.service.user.editPwd(ctx.params.id, password);
    ctx.body = { code: 200, msg: '修改成功' };
  }
}

module.exports = UserController;

 

 

  • app/service/user.js

 

'use strict';

const Service = require('egg').Service;
const crypto = require('crypto');
// 设置默认密码
const DEFAULT_PWD = '123456';
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 = this.getMd5Data(password);
    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);
  }
  // 新增人员
  async addUser(nickname) {
    const { ctx } = this;
    const password = this.getMd5Data(DEFAULT_PWD);
    await ctx.model.User.create({ nickname, password });
  }
  // 修改密码
  async editPwd(id, password) {
    const { ctx } = this;
    const user = await ctx.model.User.findByPk(id);
    const newPwd = this.getMd5Data(password);
    await user.update({ password: newPwd });
  }
  // 专门对数据进行md5加密的方法,输入明文返回密文
  getMd5Data(data) {
    return crypto.createHash('md5').update(data).digest('hex');
  }
}
module.exports = UserService;

 

 

  • 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);
  // 新增
  router.put('/user', jwt, controller.user.create);
  // 修改密码
  router.post('/user/:id', jwt, controller.user.updatePwd);
};

 

  • 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"
}

 

自测

  • 新增人员

    image.png

  • 修改密码

    image.png

posted @ 2019-12-24 10:39  mingL  阅读(1145)  评论(0编辑  收藏  举报