organization.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const jwt = require('jsonwebtoken');
  6. // 机构
  7. class OrganizationService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'organization');
  10. this.redis = this.app.redis;
  11. this.model = this.ctx.model.Organization;
  12. }
  13. /**
  14. * 创建用户
  15. * @param {Object} params 用户信息
  16. */
  17. async create({ passwd, ...data }) {
  18. data.passwd = { secret: passwd };
  19. const { institution_code } = data;
  20. // 检查是否重复
  21. const num = await this.model.count({ institution_code, 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 institution_code 手机号
  39. * @property passwd 密码
  40. */
  41. async login({ institution_code, passwd }) {
  42. console.log(institution_code, passwd);
  43. const object = await this.model.findOne({ institution_code, isdel: '0' }, '+passwd');
  44. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
  45. const { passwd: op, status } = object;
  46. const { secret } = op;
  47. if (status !== '1') throw new BusinessError(ErrorCode.ACCESS_DENIED, '拒绝访问!');
  48. if (secret !== passwd) throw new BusinessError(ErrorCode.BAD_passwd, '密码错误');
  49. const data = _.omit(JSON.parse(JSON.stringify(object)), [ 'meta', 'passwd', '__v' ]);
  50. const { secret: secrets } = this.config.jwt;
  51. const token = jwt.sign(data, secrets);
  52. // 记录登陆
  53. // let number = await this.redis.get('login_number') || 0;
  54. // number++;
  55. // await this.redis.set('login_number', number);
  56. return token;
  57. }
  58. async delete({ id }) {
  59. const object = await this.model.findById(id);
  60. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
  61. object.isdel = '1';
  62. await object.save();
  63. }
  64. }
  65. module.exports = OrganizationService;