session_auth.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. // 加密类
  3. const crypto = require('crypto');
  4. const messageType = require('../const/message_type');
  5. module.exports = options => {
  6. /**
  7. * session判断中间件
  8. *
  9. * @param {function} next - 中间件继续执行的方法
  10. * @return {void}
  11. */
  12. return function* sessionAuth(next) {
  13. try {
  14. // 判断session
  15. const sessionUser = this.session.sessionUser;
  16. if (sessionUser === undefined) {
  17. throw '不存在session';
  18. }
  19. // 校验session
  20. if (sessionUser.account === undefined || sessionUser.loginTime === undefined) {
  21. throw '用户数据不完整';
  22. }
  23. // 校验session
  24. const sessionToken = crypto.createHmac('sha1', sessionUser.loginTime + '')
  25. .update(sessionUser.account).digest('hex').toString('base64');
  26. if (sessionToken !== sessionUser.sessionToken) {
  27. throw 'session数据错误';
  28. }
  29. // 获取用户新建标段权利
  30. const accountInfo = yield this.service.projectAccount.getDataById(this.session.sessionUser.accountId);
  31. this.session.sessionUser.permission = accountInfo !== undefined && accountInfo.permission !== '' ? JSON.parse(accountInfo.permission) : null;
  32. // 同步消息
  33. yield this.service.notify.syncNotifyData();
  34. // 同步系统维护信息
  35. yield this.service.maintain.syncMaintainData();
  36. if (this.session === null) {
  37. throw '系统维护中~';
  38. }
  39. } catch (error) {
  40. console.log(error);
  41. if (this.helper.isAjax(this.request)) {
  42. return this.body = {
  43. err: 2,
  44. msg: '登录信息异常,请重新登录',
  45. data: '',
  46. };
  47. } else if (this.session === null) {
  48. if (this.helper.isWap(this.request)) {
  49. this.session.wapTenderID = this.params.id ? this.params.id : null;
  50. return this.redirect('/wap/login?referer=' + this.url);
  51. } else {
  52. return this.redirect('/login?referer=' + this.url);
  53. }
  54. } else {
  55. if (this.helper.isWap(this.request)) {
  56. this.session.wapTenderID = this.params.id ? this.params.id : null;
  57. return this.redirect('/wap/login?referer=' + this.url);
  58. } else {
  59. this.session.message = {
  60. type: messageType.ERROR,
  61. icon: 'exclamation-circle',
  62. message: '登录信息异常,请重新登录',
  63. };
  64. return this.redirect('/login?referer=' + this.url);
  65. }
  66. }
  67. }
  68. yield next;
  69. };
  70. };