52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
import os
|
|
from fastapi import Depends, HTTPException, status, Request
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from ea_chatbot.config import Settings
|
|
from ea_chatbot.history.manager import HistoryManager
|
|
from ea_chatbot.auth import OIDCClient
|
|
from ea_chatbot.api.utils import decode_access_token
|
|
from ea_chatbot.history.models import User
|
|
|
|
settings = Settings()
|
|
|
|
# Shared instances
|
|
history_manager = HistoryManager(settings.history_db_url)
|
|
|
|
oidc_client = None
|
|
if settings.oidc_client_id and settings.oidc_client_secret and settings.oidc_server_metadata_url:
|
|
oidc_client = OIDCClient(
|
|
client_id=settings.oidc_client_id,
|
|
client_secret=settings.oidc_client_secret,
|
|
server_metadata_url=settings.oidc_server_metadata_url,
|
|
redirect_uri=os.getenv("OIDC_REDIRECT_URI", "http://localhost:3000/auth/callback")
|
|
)
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/auth/login", auto_error=False)
|
|
|
|
async def get_current_user(request: Request, token: str = Depends(oauth2_scheme)) -> User:
|
|
"""Dependency to get the current authenticated user from the JWT token (cookie or header)."""
|
|
# Prioritize cookie, fallback to header
|
|
token = request.cookies.get("access_token") or token
|
|
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
if not token:
|
|
raise credentials_exception
|
|
|
|
payload = decode_access_token(token)
|
|
if payload is None:
|
|
raise credentials_exception
|
|
|
|
user_id: str | None = payload.get("sub")
|
|
if user_id is None:
|
|
raise credentials_exception
|
|
|
|
user = history_manager.get_user_by_id(user_id)
|
|
if user is None:
|
|
raise credentials_exception
|
|
|
|
return user |