kjzlMedium.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. const jwt = require('jsonwebtoken');
  7. // 科教之旅机构表
  8. class KjzlMediumService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'kjzl_medium');
  11. this.model = this.ctx.model.Kjzl.KjzlMedium;
  12. }
  13. /**
  14. * 创建用户
  15. * @param {Object} params 用户信息
  16. */
  17. async create({ password, ...data }) {
  18. data.password = { secret: password };
  19. return await this.model.create(data);
  20. }
  21. /**
  22. * 修改密码
  23. * @param {Object} {id,password} 用户id和密码
  24. */
  25. async password({ id, password }) {
  26. const object = await this.model.findById(id);
  27. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
  28. object.password = { secret: password };
  29. await object.save();
  30. }
  31. /**
  32. * 登陆
  33. * @param {Object} params 登陆信息
  34. * @property phone 手机号
  35. * @property password 密码
  36. */
  37. async login({ phone, password }) {
  38. const object = await this.model.findOne({ phone }, '+password');
  39. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
  40. const { password: op } = object;
  41. const { secret } = op;
  42. if (secret !== password) throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
  43. const data = _.omit(JSON.parse(JSON.stringify(object)), [ 'meta', 'password', '__v' ]);
  44. const { secret: secrets } = this.config.jwt;
  45. const token = jwt.sign(data, secrets);
  46. return token;
  47. }
  48. }
  49. module.exports = KjzlMediumService;