mirror of
https://github.com/OpenHands/OpenHands.git
synced 2025-12-26 05:48:36 +08:00
Co-authored-by: openhands <openhands@all-hands.dev> Co-authored-by: sp.wack <83104063+amanape@users.noreply.github.com> Co-authored-by: Engel Nyst <enyst@users.noreply.github.com>
40 lines
1.2 KiB
Python
40 lines
1.2 KiB
Python
import jwt
|
|
from jwt.exceptions import InvalidTokenError
|
|
|
|
from openhands.core.logger import openhands_logger as logger
|
|
|
|
|
|
def get_sid_from_token(token: str, jwt_secret: str) -> str:
|
|
"""Retrieves the session id from a JWT token.
|
|
|
|
Parameters:
|
|
token (str): The JWT token from which the session id is to be extracted.
|
|
|
|
Returns:
|
|
str: The session id if found and valid, otherwise an empty string.
|
|
"""
|
|
try:
|
|
# Decode the JWT using the specified secret and algorithm
|
|
payload = jwt.decode(token, jwt_secret, algorithms=['HS256'])
|
|
|
|
# Ensure the payload contains 'sid'
|
|
if 'sid' in payload:
|
|
return payload['sid']
|
|
else:
|
|
logger.error('SID not found in token')
|
|
return ''
|
|
except InvalidTokenError:
|
|
logger.error('Invalid token')
|
|
except Exception as e:
|
|
logger.exception('Unexpected error decoding token: %s', e)
|
|
return ''
|
|
|
|
|
|
def sign_token(payload: dict[str, object], jwt_secret: str, algorithm='HS256') -> str:
|
|
"""Signs a JWT token."""
|
|
# payload = {
|
|
# "sid": sid,
|
|
# # "exp": datetime.now(timezone.utc) + timedelta(minutes=15),
|
|
# }
|
|
return jwt.encode(payload, jwt_secret, algorithm=algorithm)
|