power.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. const assert = require('assert');
  4. const crypto = require('crypto');
  5. const menu = require('../public/adminMenu');
  6. class UserService extends Service {
  7. async login({ acct, password }) {
  8. assert(acct, '帐号不存在');
  9. assert(password, '密码不存在');
  10. const { AdminUser: model } = this.ctx.model;
  11. const hash = crypto.createHmac('sha256', this.app.config.userSecret);
  12. const pwd = hash.update(password).digest('hex');
  13. try {
  14. const res = await model.find({ acct });
  15. const userInfo = res[0];
  16. if (userInfo.state !== '0') {
  17. return { errmsg: '用户状态异常', errcode: -2003 };
  18. }
  19. if (userInfo.password !== pwd) {
  20. return { errmsg: '密码错误', errcode: -2003 };
  21. }
  22. const token = this.app.jwt.sign({ acct: userInfo.acct, userName: userInfo.userName, id: userInfo._id }, this.app.config.jwt.secret);
  23. return { errmsg: '', errcode: 0, token, userInfo: { acct: userInfo.acct, userName: userInfo.userName, id: userInfo._id } };
  24. } catch (error) {
  25. throw new Error({ errcode: -2001, errmsg: '登录失败' });
  26. }
  27. }
  28. async getUserMenu() {
  29. const { AdminUser: model } = this.ctx.model;
  30. const { Role: rolemodel } = this.ctx.model;
  31. try {
  32. const str = this.ctx.request.header.authorization;
  33. const token = str.substring(7);
  34. const decode = this.ctx.app.jwt.verify(token, this.app.config.jwt.secret);
  35. const menulist = [];
  36. const res = await model.find({ acct: decode.acct });
  37. if (res.length > 0) {
  38. const userRoleList = res[0].roleList;
  39. if (userRoleList && userRoleList.length > 0) {
  40. for (let e = 0; e < userRoleList.length; e++) {
  41. const role = await rolemodel.find({ code: userRoleList[e], state: '0' });
  42. if (role.length > 0) {
  43. const adminMenuList = role[0].adminMenuList;
  44. for (let i = 0; i < adminMenuList.length; i++) {
  45. const item = menu.filter(j => adminMenuList[i] === j.id)[0];
  46. if (!menulist.includes(item)) {
  47. menulist.push(item);
  48. }
  49. }
  50. }
  51. }
  52. }
  53. }
  54. return { errcode: 0, errmsg: '', data: menulist };
  55. } catch (error) {
  56. throw new Error({ errcode: -2001, errmsg: '登录失败' });
  57. }
  58. }
  59. }
  60. module.exports = UserService;