auth.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import jwt
  2. from jwt.exceptions import InvalidTokenError
  3. from openhands.core.logger import openhands_logger as logger
  4. def get_sid_from_token(token: str, jwt_secret: str) -> str:
  5. """Retrieves the session id from a JWT token.
  6. Parameters:
  7. token (str): The JWT token from which the session id is to be extracted.
  8. Returns:
  9. str: The session id if found and valid, otherwise an empty string.
  10. """
  11. try:
  12. # Decode the JWT using the specified secret and algorithm
  13. payload = jwt.decode(token, jwt_secret, algorithms=['HS256'])
  14. # Ensure the payload contains 'sid'
  15. if 'sid' in payload:
  16. return payload['sid']
  17. else:
  18. logger.error('SID not found in token')
  19. return ''
  20. except InvalidTokenError:
  21. logger.error('Invalid token')
  22. except Exception as e:
  23. logger.exception('Unexpected error decoding token: %s', e)
  24. return ''
  25. def sign_token(payload: dict[str, object], jwt_secret: str) -> str:
  26. """Signs a JWT token."""
  27. # payload = {
  28. # "sid": sid,
  29. # # "exp": datetime.now(timezone.utc) + timedelta(minutes=15),
  30. # }
  31. return jwt.encode(payload, jwt_secret, algorithm='HS256')