home.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. const Controller = require('egg').Controller;
  3. const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
  4. const { BusinessError, ErrorCode } = require('naf-core').Error;
  5. const { ObjectId } = require('mongoose').Types;
  6. // 项目测试及管理员登陆
  7. class HomeController extends Controller {
  8. async index() {
  9. const { ctx } = this;
  10. ctx.body = 'hello';
  11. }
  12. /**
  13. * 系统管理员登陆
  14. * 太简单了,就不写service了,直接在这处理完完事了
  15. */
  16. async login() {
  17. const { account, password } = this.ctx.request.body;
  18. let admin = await this.ctx.model.Admin.findOne({ account }, '+password').exec();
  19. if (!account) throw new BusinessError(ErrorCode.BADPARAM, '未找到要登陆用户账号');
  20. if (!password) throw new BusinessError(ErrorCode.BADPARAM, '未找到要登陆用户密码');
  21. if (admin.password.secret !== password) throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
  22. admin = JSON.parse(JSON.stringify(admin));
  23. delete admin.password;
  24. delete admin.meta;
  25. delete admin.__v;
  26. const { is_super } = admin;
  27. if (!is_super) {
  28. // 获取角色
  29. const roleRes = await this.ctx.model.Role.findOne({ _id: admin.role });
  30. if (roleRes) {
  31. admin.role_id = roleRes._id;
  32. }
  33. }
  34. const token = this.ctx.service.util.jwt.encrypt(admin);
  35. this.ctx.ok({ data: token });
  36. }
  37. }
  38. module.exports = CrudController(HomeController, {});