home.js 1.4 KB

123456789101112131415161718192021222324252627282930313233
  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. // 项目测试及管理员登陆
  6. class HomeController extends Controller {
  7. async index() {
  8. const { ctx } = this;
  9. ctx.body = 'hi, egg';
  10. }
  11. /**
  12. * 系统管理员登陆
  13. * 太简单了,就不写service了,直接在这处理完完事了
  14. */
  15. async login() {
  16. let admin = await this.ctx.model.Admin.findOne({}, '+password').exec();
  17. if (!admin) throw new BusinessError(ErrorCode.FILE_FAULT, '未初始化管理员,拒绝请求!');
  18. const { account, password } = this.ctx.request.body;
  19. if (!account) throw new BusinessError(ErrorCode.BADPARAM, '未找到要登陆用户账号');
  20. if (!password) throw new BusinessError(ErrorCode.BADPARAM, '未找到要登陆用户密码');
  21. if (admin.account !== account) throw new BusinessError(ErrorCode.USER_NOT_EXIST, '未找到要登录的用户');
  22. if (admin.password.secret !== password) throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
  23. admin = JSON.parse(JSON.stringify(admin));
  24. delete admin.password;
  25. delete admin.meta;
  26. delete admin.__v;
  27. delete admin._id;
  28. const token = this.ctx.service.util.jwt.encrypt(admin);
  29. this.ctx.ok({ data: token });
  30. }
  31. }
  32. module.exports = CrudController(HomeController, {});