feat(auth): Implement OIDCSession helper for secure temporary storage
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
import requests
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from enum import Enum
|
||||
from typing import Dict, Any, Optional
|
||||
from authlib.integrations.requests_client import OAuth2Session
|
||||
from jose import JWTError, jwt
|
||||
|
||||
class AuthType(Enum):
|
||||
LOCAL = "local"
|
||||
@@ -29,6 +31,31 @@ def get_user_auth_type(email: str, history_manager: Any) -> AuthType:
|
||||
|
||||
return AuthType.OIDC
|
||||
|
||||
class OIDCSession:
|
||||
"""Helper for managing temporary OIDC session data in a secure cookie."""
|
||||
ALGORITHM = "HS256"
|
||||
|
||||
@classmethod
|
||||
def encrypt(cls, data: dict, secret_key: str, expires_delta: Optional[timedelta] = None) -> str:
|
||||
"""Encrypt OIDC session data into a JWT."""
|
||||
to_encode = data.copy()
|
||||
now = datetime.now(timezone.utc)
|
||||
if expires_delta:
|
||||
expire = now + expires_delta
|
||||
else:
|
||||
expire = now + timedelta(minutes=5) # Short-lived by default
|
||||
|
||||
to_encode.update({"exp": expire, "iat": now})
|
||||
return jwt.encode(to_encode, secret_key, algorithm=cls.ALGORITHM)
|
||||
|
||||
@classmethod
|
||||
def decrypt(cls, token: str, secret_key: str) -> Optional[dict]:
|
||||
"""Decrypt and validate OIDC session data from a JWT."""
|
||||
try:
|
||||
return jwt.decode(token, secret_key, algorithms=[cls.ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
|
||||
class OIDCClient:
|
||||
"""
|
||||
Client for OIDC Authentication using Authlib.
|
||||
|
||||
Reference in New Issue
Block a user