session_auth.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. // 加密类
  3. const crypto = require('crypto');
  4. module.exports = options => {
  5. /**
  6. * session判断中间件
  7. *
  8. * @param {function} next - 中间件继续执行的方法
  9. * @return {void}
  10. */
  11. return function* sessionAuth(next) {
  12. try {
  13. // 判断session
  14. const userSession = this.session.userSession;
  15. if (userSession === undefined) {
  16. throw '不存在session';
  17. }
  18. // 校验session
  19. if (userSession.username === undefined || userSession.loginTime === undefined) {
  20. throw '用户数据不完整';
  21. }
  22. // 校验session
  23. const sessionToken = crypto.createHmac('sha1', userSession.loginTime + '')
  24. .update(userSession.username).digest().toString('base64');
  25. if (sessionToken !== userSession.sessionToken) {
  26. throw 'session数据错误';
  27. }
  28. // 同步消息
  29. //yield this.service.notify.syncNotifyData();
  30. } catch (error) {
  31. console.log(error);
  32. return this.redirect('/');
  33. }
  34. yield next;
  35. };
  36. };