power.js 960 B

1234567891011121314151617181920212223242526272829
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. const assert = require('assert');
  4. const crypto = require('crypto');
  5. class UserService extends Service {
  6. async login({ acct, password }) {
  7. assert(acct, '帐号不存在');
  8. assert(password, '密码不存在');
  9. const { AdminUser: model } = this.ctx.model;
  10. const hash = crypto.createHmac('sha256', this.app.config.userSecret);
  11. const pwd = hash.update(password).digest('hex');
  12. try {
  13. const res = await model.find({ acct });
  14. if (res.state !== 0) {
  15. return { errmsg: '用户状态异常', errcode: -2003 };
  16. }
  17. if (res.password !== pwd) {
  18. return { errmsg: '密码错误', errcode: -2003 };
  19. }
  20. const token = this.app.jwt.sign(res, this.app.config.jwt.secret);
  21. return { errmsg: '', errcode: 0, token };
  22. } catch (error) {
  23. throw new Error({ errcode: -2001, errmsg: '登录失败' });
  24. }
  25. }
  26. }
  27. module.exports = UserService;