user.js 2.0 KB

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