admin.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. //
  7. class AdminService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'admin');
  10. this.model = this.ctx.model.User.Admin;
  11. }
  12. async beforeCreate(data) {
  13. const { account } = data;
  14. const num = await this.model.count({ account });
  15. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该账号名已存在');
  16. return data;
  17. }
  18. async beforeUpdate(filter, update) {
  19. const { account } = update;
  20. const id = _.get(filter, '_id', _.get(filter, 'id'));
  21. const num = await this.model.count({ _id: { $ne: id }, account });
  22. if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该账号名已存在');
  23. return { filter, update };
  24. }
  25. /**
  26. * 登陆
  27. * @param {Object} body 登陆参数
  28. * @param body.account 账户
  29. * @param body.password 密码
  30. */
  31. async login({ account, password }) {
  32. const { populate } = this.getRefMods();
  33. let user = await this.model.findOne({ account }, '+password').populate(populate);
  34. if (!user) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  35. const { password: upwd } = user;
  36. if (password !== upwd.secret) throw new BusinessError(ErrorCode.BAD_PASSWORD);
  37. // // 使用redis存储,后续的任何操作进行token的校验
  38. // await this.setUserInRedis(user);
  39. user = JSON.parse(JSON.stringify(user));
  40. delete user.password;
  41. delete user.meta;
  42. delete user.__v;
  43. const token = this.ctx.service.util.jwt.encrypt(user);
  44. return token;
  45. }
  46. async resetPwd({ id }, { password }) {
  47. const data = await this.model.findById(id);
  48. if (!data) throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  49. data.password = { secret: password };
  50. await data.save();
  51. }
  52. }
  53. module.exports = AdminService;