session_auth.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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().toString('base64');
  26. if (sessionToken !== sessionUser.sessionToken) {
  27. throw 'session数据错误';
  28. }
  29. // 同步消息
  30. yield this.service.notify.syncNotifyData();
  31. } catch (error) {
  32. console.log(error);
  33. if (this.helper.isAjax(this.request)) {
  34. return this.body = {
  35. err: 2,
  36. msg: '登录信息异常,请重新登录',
  37. data: '',
  38. };
  39. } else {
  40. this.session.message = {
  41. type: messageType.ERROR,
  42. icon: 'exclamation-circle',
  43. message: '登录信息异常,请重新登录',
  44. };
  45. return this.redirect('/login?referer=' + this.url);
  46. }
  47. }
  48. yield next;
  49. };
  50. };