request_context.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. from dataclasses import dataclass
  2. from http.cookies import SimpleCookie
  3. @dataclass
  4. class RequestContext:
  5. gateway_session_id: str = ''
  6. source: str = ''
  7. def has_session(self):
  8. return bool(self.gateway_session_id)
  9. class RequestContextParser:
  10. def parse(self, headers):
  11. normalized = {str(k).lower(): str(v).strip() for k, v in (headers or {}).items()}
  12. header_value = normalized.get('x-gateway-session', '')
  13. if header_value.startswith('GWS_'):
  14. return RequestContext(header_value, 'header')
  15. authorization = normalized.get('authorization', '')
  16. prefix = 'bearer '
  17. if authorization.lower().startswith(prefix):
  18. token = authorization[len(prefix):].strip()
  19. if token.startswith('GWS_'):
  20. return RequestContext(token, 'authorization')
  21. cookie_header = normalized.get('cookie', '')
  22. if cookie_header:
  23. cookie = SimpleCookie()
  24. cookie.load(cookie_header)
  25. morsel = cookie.get('gateway_session_id')
  26. if morsel and morsel.value.startswith('GWS_'):
  27. return RequestContext(morsel.value, 'cookie')
  28. return RequestContext()