user.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 phone = _.get(data, 'phone');
  14. if (phone) {
  15. const num = await this.model.count({ phone });
  16. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该手机号已注册');
  17. }
  18. return data;
  19. }
  20. async resetPwd({ id }, { password }) {
  21. const data = await this.model.findById(id);
  22. if (!data) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  23. data.password = { secret: password };
  24. await data.save();
  25. }
  26. /**
  27. * 登陆
  28. * @param {Object} body 登陆参数
  29. * @param body.phone 账户
  30. * @param body.password 密码
  31. */
  32. async login({ phone, password }) {
  33. const { populate } = this.getRefMods();
  34. const user = await this.model.findOne({ phone }, '+password').populate(populate);
  35. if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  36. const { password: upwd, status } = user;
  37. if (status !== '0') throw new BusinessError(ErrorCode.USER_NOT_BIND, '该账号处于禁止使用状态');
  38. if (password !== upwd.secret) throw new BusinessError(ErrorCode.BAD_PASSWORD);
  39. // // 使用redis存储,后续的任何操作进行token的校验
  40. // await this.setUserInRedis(user);
  41. delete user.password;
  42. delete user.meta;
  43. delete user.__v;
  44. const token = this.ctx.service.util.jwt.encrypt(user);
  45. return token;
  46. }
  47. /**
  48. * 微信登录
  49. * @param {Object} body 登陆参数
  50. * @param body.openid 微信小程序的openid
  51. */
  52. async wxLogin({ openid }) {
  53. const { populate } = this.getRefMods();
  54. const user = await this.model.findOne({ openid }).populate(populate);
  55. if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  56. const { status } = user;
  57. if (status !== '0') throw new BusinessError(ErrorCode.USER_NOT_BIND, '该账号处于禁止使用状态');
  58. delete user.meta;
  59. delete user.__v;
  60. const token = this.ctx.service.util.jwt.encrypt(user);
  61. return token;
  62. }
  63. }
  64. module.exports = UserService;