channel.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const { ObjectId } = require('mongoose').Types;
  5. const _ = require('lodash');
  6. const assert = require('assert');
  7. const jwt = require('jsonwebtoken');
  8. // 科技频道
  9. class ChannelService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx, 'channel');
  12. this.model = this.ctx.model.Channel;
  13. }
  14. async create(body) {
  15. const last = await this.model.findOne().sort({ room_id: -1 });
  16. let room_id = 2001;
  17. if (last) room_id = last.room_id + 1;
  18. body.room_id = room_id;
  19. body.passwd = { secret: room_id };
  20. return await this.model.create(body);
  21. }
  22. /**
  23. * 管理者登陆
  24. * @param {Object} { room_id, passwd } 登陆参数
  25. * @property {String} room_id 房间号
  26. * @property {String} passwd 密码
  27. */
  28. async login({ room_id, passwd }) {
  29. const object = await this.model.findOne({ room_id }, '+passwd');
  30. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, `未找到展会号为: ${room_id} 的展会`);
  31. const op = _.get(object, 'passwd.secret');
  32. if (!_.isEqual(op, passwd)) throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
  33. const data = _.omit(JSON.parse(JSON.stringify(object)), [ 'meta', 'passwd', '__v' ]);
  34. const { secret: jwts } = this.config.jwt;
  35. const token = jwt.sign(data, jwts);
  36. return token;
  37. }
  38. }
  39. module.exports = ChannelService;