login_controller.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. 'use strict';
  2. /**
  3. * 登录页面控制器
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/11/15
  7. * @version
  8. */
  9. const URL = require('url');
  10. module.exports = app => {
  11. class LoginController extends app.BaseController {
  12. /**
  13. * 登录页面
  14. *
  15. * @param {Object} ctx - egg全局页面
  16. * @return {void}
  17. */
  18. async index(ctx) {
  19. const errorMessage = ctx.session.loginError;
  20. // 显示完删除
  21. ctx.session.loginError = null;
  22. const renderData = {
  23. errorMessage,
  24. };
  25. await ctx.render('login/login.ejs', renderData);
  26. }
  27. /**
  28. * 登录操作
  29. *
  30. * @param {Object} ctx - egg全局变量
  31. * @return {void}
  32. */
  33. async login(ctx) {
  34. let loginType = ctx.request.body.type;
  35. try {
  36. loginType = parseInt(loginType);
  37. const result = await ctx.service.projectAccount.accountLogin(ctx.request.body, loginType);
  38. if (!result) {
  39. throw '登录失败';
  40. }
  41. // 判断是否已经有对应用户信息,没有则跳转初始化页面
  42. const needBoot = await ctx.service.customer.isNeedBoot(ctx.request.body);
  43. const url = needBoot ? '/boot' : '/dashboard';
  44. const query = URL.parse(ctx.request.header.referer, true).query;
  45. ctx.redirect(query.referer ? query.referer : url);
  46. } catch (error) {
  47. this.log(error);
  48. ctx.session.loginError = '用户名或密码错误';
  49. ctx.redirect('/login');
  50. }
  51. }
  52. /**
  53. * 退出登录
  54. *
  55. * @param {Object} ctx - egg全局变量
  56. * @return {void}
  57. */
  58. async logout(ctx) {
  59. // 删除session并跳转
  60. ctx.session = null;
  61. ctx.redirect('/');
  62. }
  63. /**
  64. * 获取项目名
  65. *
  66. * @param {Object} ctx - egg全局context
  67. * @return {void}
  68. */
  69. async projectName(ctx) {
  70. const response = {
  71. err: 0,
  72. msg: '',
  73. };
  74. const code = ctx.query.code;
  75. try {
  76. const data = await ctx.service.project.getProjectByCode(code);
  77. if (data) {
  78. response.data = data.name;
  79. } else {
  80. throw '项目不存在';
  81. }
  82. } catch (err) {
  83. response.err = 1;
  84. response.msg = err;
  85. }
  86. ctx.body = response;
  87. }
  88. }
  89. return LoginController;
  90. };