user.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { ObjectId } = require('mongoose').Types;
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. const jwt = require('jsonwebtoken');
  8. class UserService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'user');
  11. this.model = this.ctx.model.User;
  12. this.rmodel = this.ctx.model.Role;
  13. }
  14. // 重写创建方法
  15. async create(data) {
  16. const { name, phone, passwd } = data;
  17. console.log(data);
  18. assert(name && phone && passwd, '缺少部分信息项');
  19. assert(/^\d{11}$/i.test(phone), 'phone无效');
  20. const user = await this.model.findOne({ phone });
  21. if (user) {
  22. throw new BusinessError(ErrorCode.DATA_EXISTED);
  23. }
  24. const newdata = data;
  25. const pas = await this.createJwtPwd(passwd);
  26. newdata.passwd = { secret: pas };
  27. const res = await this.model.create(newdata);
  28. return res;
  29. }
  30. // 创建登录Token
  31. async createJwtPwd(password) {
  32. const { secret, expiresIn, issuer } = this.config.jwt;
  33. const token = await jwt.sign(password, secret);
  34. return token;
  35. }
  36. // 重写修改方法
  37. async update({ id }, data) {
  38. const { name, phone, passwd, openid, role, menus, remark, uid } = data;
  39. const user = await this.model.findById(id, '+passwd');
  40. if (name) {
  41. user.name = name;
  42. }
  43. if (phone) {
  44. user.phone = phone;
  45. }
  46. if (passwd) {
  47. const newpasswd = await this.createJwtPwd(passwd);
  48. user.passwd = { secret: newpasswd };
  49. }
  50. if (openid) {
  51. user.openid = openid;
  52. }
  53. if (role) {
  54. user.role = role;
  55. }
  56. if (menus) {
  57. user.menus = menus;
  58. }
  59. if (uid) {
  60. user.uid = uid;
  61. }
  62. if (remark) {
  63. user.remark = remark;
  64. }
  65. await user.save();
  66. }
  67. // 用户修改密码
  68. async uppasswd(data) {
  69. const { id, oldpasswd, newpasswd } = data;
  70. assert(id && oldpasswd && newpasswd, '缺少部分信息项');
  71. // 根据用户id查询其他用户表中是否存在相应数据
  72. const user = await this.model.findById(id, '+passwd');
  73. // 如果用户不存在抛出异常
  74. if (!user) {
  75. throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  76. }
  77. // 将用户输入的密码进行加密并与查询到的用户数据密码相比对
  78. const _oldpasswd = await this.createJwtPwd(oldpasswd);
  79. // 如果两个密码不一致抛出异常
  80. if (_oldpasswd !== user.passwd.secret) {
  81. throw new BusinessError(ErrorCode.BAD_PASSWORD);
  82. }
  83. const _newpasswd = await this.createJwtPwd(newpasswd);
  84. user.passwd = { secret: _newpasswd };
  85. await user.save();
  86. }
  87. }
  88. module.exports = UserService;