mechanism.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 jwt = require('jsonwebtoken');
  6. // 机构
  7. class MechanismService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'Mechanism');
  10. this.redis = this.app.redis;
  11. this.model = this.ctx.model.User.Mechanism;
  12. }
  13. /**
  14. * 创建用户
  15. * @param {Object} params 用户信息
  16. */
  17. async create({ passwd, ...data }) {
  18. data.passwd = { secret: passwd };
  19. const { phone } = data;
  20. // 检查是否重复
  21. const num = await this.model.count({ phone, isdel: '0' });
  22. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '已有机构使用该电话号码');
  23. return await this.model.create(data);
  24. }
  25. /**
  26. * 修改密码
  27. * @param {Object} {id,passwd} 用户id和密码
  28. */
  29. async password({ id, passwd }) {
  30. const object = await this.model.findById(id);
  31. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
  32. object.passwd = { secret: passwd };
  33. await object.save();
  34. }
  35. /**
  36. * 登陆
  37. * @param {Object} params 登陆信息
  38. * @property phone 手机号
  39. * @property passwd 密码
  40. */
  41. async login({ phone, passwd }) {
  42. const object = await this.model.findOne({ phone, isdel: '0' }, '+passwd');
  43. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
  44. const { passwd: op, status } = object;
  45. const { secret } = op;
  46. if (status !== '1') throw new BusinessError(ErrorCode.ACCESS_DENIED, '拒绝访问!');
  47. if (secret !== passwd) throw new BusinessError(ErrorCode.BAD_passwd, '密码错误');
  48. const data = _.omit(JSON.parse(JSON.stringify(object)), [ 'meta', 'passwd', '__v' ]);
  49. const { secret: secrets } = this.config.jwt;
  50. const token = jwt.sign(data, secrets);
  51. // 记录登陆
  52. // let number = await this.redis.get('login_number') || 0;
  53. // number++;
  54. // await this.redis.set('login_number', number);
  55. return token;
  56. }
  57. async delete({ id }) {
  58. const object = await this.model.findById(id);
  59. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
  60. object.isdel = '1';
  61. await object.save();
  62. }
  63. }
  64. module.exports = MechanismService;