user.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 { ObjectId } = require('mongoose').Types;
  6. // 用户相关
  7. class UserService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'user');
  10. this.model = this.ctx.model.User;
  11. }
  12. /**
  13. * 创建用户
  14. * @param {Object} params 用户信息
  15. */
  16. async create({ password, ...data }) {
  17. data.password = { secret: password };
  18. const { phone } = data;
  19. // 检查手机号
  20. const num = await this.model.count({ phone });
  21. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '已有人员 使用该手机号');
  22. const res = await this.model.create(data);
  23. return res;
  24. }
  25. /**
  26. * 修改密码
  27. * @param {Object} {id,password} 用户id和密码
  28. */
  29. async password({ id, password }) {
  30. const object = await this.model.findById(id);
  31. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
  32. object.password = { secret: password };
  33. await object.save();
  34. }
  35. /**
  36. * 管理员登陆
  37. * @param {Object} params 登陆信息
  38. * @property phone 电话号
  39. * @property password 密码
  40. */
  41. async login({ phone, password, openid }) {
  42. let object;
  43. if (!openid) object = await this.model.findOne({ phone }, '+password');
  44. else object = await this.model.findOne({ openid });
  45. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
  46. if (!openid) {
  47. const { password: op } = object;
  48. const { secret } = op;
  49. if (secret !== password) throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
  50. }
  51. const data = _.omit(JSON.parse(JSON.stringify(object)), [ 'meta', 'password', '__v' ]);
  52. return data;
  53. }
  54. }
  55. module.exports = UserService;