user.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 UserService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx, 'user');
  12. this.model = this.ctx.model.User;
  13. }
  14. async init() {
  15. const count = await this.model.count({ login_id: 'admin' });
  16. if (count <= 0) {
  17. const data = {
  18. name: '管理员',
  19. login_id: 'admin',
  20. password: { secret: '123456' },
  21. };
  22. await this.model.create(data);
  23. }
  24. }
  25. /**
  26. * 管理员登陆
  27. * @param {Object} params 登陆信息
  28. * @property login_id code或者是phone
  29. * @property password 密码
  30. */
  31. async login({ login_id, password }) {
  32. const object = await this.model.findOne({ login_id }, '+password');
  33. if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
  34. const { password: op } = object;
  35. const { secret } = op;
  36. if (secret !== password) throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
  37. const data = _.omit(JSON.parse(JSON.stringify(object)), [ 'meta', 'password', '__v' ]);
  38. const { secret: secrets } = this.config.jwt;
  39. const token = jwt.sign(data, secrets);
  40. return token;
  41. }
  42. }
  43. module.exports = UserService;