user.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. //
  7. class UserService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'user');
  10. this.model = this.ctx.model.User.User;
  11. }
  12. async beforeCreate(data) {
  13. const openid = _.get(data, 'openid');
  14. const phone = _.get(data, 'phone');
  15. if (!openid && phone) {
  16. const num = await this.model.count({ phone });
  17. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该手机号已注册');
  18. } else if (openid) {
  19. const num = await this.model.count({ openid });
  20. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该微信号已注册');
  21. }
  22. return data;
  23. }
  24. async resetPwd({ id }, { password }) {
  25. const data = await this.model.findById(id);
  26. if (!data) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  27. data.password = { secret: password };
  28. await data.save();
  29. }
  30. /**
  31. * 登陆
  32. * @param {Object} body 登陆参数
  33. * @param body.phone 账户
  34. * @param body.password 密码
  35. */
  36. async login({ phone, password }) {
  37. const { populate } = this.getRefMods();
  38. let user = await this.model.findOne({ phone }, '+password').populate(populate);
  39. if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  40. const { password: upwd, status } = user;
  41. if (status !== '0') throw new BusinessError(ErrorCode.USER_NOT_BIND, '该账号处于禁止使用状态');
  42. if (password !== upwd.secret) throw new BusinessError(ErrorCode.BAD_PASSWORD);
  43. // // 使用redis存储,后续的任何操作进行token的校验
  44. // await this.setUserInRedis(user);
  45. user = JSON.parse(JSON.stringify(user));
  46. delete user.password;
  47. delete user.meta;
  48. delete user.__v;
  49. const token = this.ctx.service.util.jwt.encrypt(user);
  50. return token;
  51. }
  52. /**
  53. * 微信登录
  54. * @param {Object} body 登陆参数
  55. * @param body.openid 微信小程序的openid
  56. */
  57. async wxLogin({ openid }) {
  58. const { populate } = this.getRefMods();
  59. const user = await this.model.findOne({ openid }).populate(populate);
  60. if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  61. const { status } = user;
  62. if (status !== '0') throw new BusinessError(ErrorCode.USER_NOT_BIND, '该账号处于禁止使用状态');
  63. delete user.meta;
  64. delete user.__v;
  65. const token = this.ctx.service.util.jwt.encrypt(user);
  66. return token;
  67. }
  68. }
  69. module.exports = UserService;