auth.py 1.2 KB

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