power.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. if (res.length <= 0) {
  16. return { errmsg: '用户不存在', errcode: -2003 };
  17. }
  18. const userInfo = res[0];
  19. if (userInfo.state !== '0') {
  20. return { errmsg: '用户状态异常', errcode: -2003 };
  21. }
  22. if (userInfo.password !== pwd) {
  23. return { errmsg: '密码错误', errcode: -2003 };
  24. }
  25. const token = this.app.jwt.sign({ acct: userInfo.acct, userName: userInfo.userName, id: userInfo._id }, this.app.config.jwt.secret);
  26. return { errmsg: '', errcode: 0, token, userInfo: { acct: userInfo.acct, userName: userInfo.userName, id: userInfo._id } };
  27. } catch (error) {
  28. console.log(error);
  29. throw new Error({ errcode: -2001, errmsg: '登录失败' });
  30. }
  31. }
  32. async getUserMenu() {
  33. const { AdminUser: model } = this.ctx.model;
  34. const { Role: rolemodel } = this.ctx.model;
  35. try {
  36. const str = this.ctx.request.header.authorization;
  37. const token = str.substring(7);
  38. const decode = this.ctx.app.jwt.verify(token, this.app.config.jwt.secret);
  39. const menulist = [];
  40. const res = await model.find({ acct: decode.acct });
  41. if (res.length > 0) {
  42. const userRoleList = res[0].roleList;
  43. if (userRoleList && userRoleList.length > 0) {
  44. for (let e = 0; e < userRoleList.length; e++) {
  45. const role = await rolemodel.find({ code: userRoleList[e], state: '0' });
  46. if (role.length > 0) {
  47. const adminMenuList = role[0].adminMenuList;
  48. for (let i = 0; i < adminMenuList.length; i++) {
  49. const item = menu.filter(j => adminMenuList[i] === j.id)[0];
  50. if (!menulist.includes(item)) {
  51. menulist.push(item);
  52. }
  53. }
  54. }
  55. }
  56. }
  57. }
  58. return { errcode: 0, errmsg: '', data: menulist };
  59. } catch (error) {
  60. throw new Error({ errcode: -2001, errmsg: '登录失败' });
  61. }
  62. }
  63. }
  64. module.exports = UserService;