user.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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, mobile, passwd } = data;
  17. console.log(data);
  18. assert(name && mobile && passwd, '缺少部分信息项');
  19. assert(/^\d{11}$/i.test(mobile), 'mobile无效');
  20. const user = await this.model.findOne({ mobile });
  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, mobile, passwd, openid, roles, remark, uid } = data;
  39. const user = await this.model.findById(id, '+passwd');
  40. if (name) {
  41. user.name = name;
  42. }
  43. if (mobile) {
  44. user.mobile = mobile;
  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 (roles) {
  54. user.roles = roles;
  55. }
  56. if (uid) {
  57. user.uid = uid;
  58. }
  59. if (remark) {
  60. user.remark = remark;
  61. }
  62. await user.save();
  63. }
  64. // 用户修改密码
  65. async uppasswd(data) {
  66. const { id, oldpasswd, newpasswd } = data;
  67. assert(id && oldpasswd && newpasswd, '缺少部分信息项');
  68. // 根据用户id查询其他用户表中是否存在相应数据
  69. const user = await this.model.findById(id, '+passwd');
  70. // 如果用户不存在抛出异常
  71. if (!user) {
  72. throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  73. }
  74. // 将用户输入的密码进行加密并与查询到的用户数据密码相比对
  75. const _oldpasswd = await this.createJwtPwd(oldpasswd);
  76. // 如果两个密码不一致抛出异常
  77. if (_oldpasswd !== user.passwd.secret) {
  78. throw new BusinessError(ErrorCode.BAD_PASSWORD);
  79. }
  80. const _newpasswd = await this.createJwtPwd(newpasswd);
  81. user.passwd = { secret: _newpasswd };
  82. await user.save();
  83. }
  84. }
  85. module.exports = UserService;