Vizz17/context-aware-rag
0
1from __future__ import annotations2 3import logging4from fastapi import APIRouter, HTTPException, Depends, status, Request, Query5from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials6 7from app.core.config import settings8from app.models.schemas import UserAuthRequest, AuthResponse9from app.services.auth import (10 register_user,11 login_user,12 create_guest_session,13 logout_session,14 get_username_from_token,15 list_registered_users,16)17 18logger = logging.getLogger(__name__)19router = APIRouter()20security = HTTPBearer()21 22def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)) -> str:23 """Dependency to validate the HTTP Bearer session token."""24 token = credentials.credentials25 username = get_username_from_token(token)26 if not username:27 raise HTTPException(28 status_code=status.HTTP_401_UNAUTHORIZED,29 detail="Session expired or invalid. Please log in again.",30 headers={"WWW-Authenticate": "Bearer"},31 )32 return username33 34@router.post("/auth/register", status_code=status.HTTP_201_CREATED)35def register(req: UserAuthRequest):36 """Register a new user account."""37 try:38 register_user(req.username, req.password)39 return {"message": "User registered successfully"}40 except ValueError as e:41 raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))42 except Exception as e:43 logger.error(f"Registration error: {e}")44 raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))45 46@router.post("/auth/login", response_model=AuthResponse)47def login(req: UserAuthRequest):48 """Authenticate a user and start a session."""49 try:50 token = login_user(req.username, req.password)51 return AuthResponse(token=token, username=req.username.lower(), is_guest=False)52 except ValueError as e:53 raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e))54 except Exception as e:55 logger.error(f"Login error: {e}")56 raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))57 58@router.post("/auth/guest", response_model=AuthResponse)59def guest_login():60 """Create a temporary guest session."""61 try:62 token, username = create_guest_session()63 return AuthResponse(token=token, username=username, is_guest=True)64 except Exception as e:65 logger.error(f"Guest login error: {e}")66 raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))67 68@router.post("/auth/logout")69def logout(credentials: HTTPAuthorizationCredentials = Depends(security)):70 """Terminate the active session (and clear guest files if guest)."""71 token = credentials.credentials72 try:73 logout_session(token)74 return {"message": "Logged out successfully"}75 except Exception as e:76 logger.error(f"Logout error: {e}")77 raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))78 79@router.get("/admin/users")80def get_users_list(secret: str | None = Query(default=None)):81 """Secret endpoint to list registered users and their session states."""82 if not settings.admin_secret:83 raise HTTPException(84 status_code=status.HTTP_403_FORBIDDEN,85 detail="Admin access is disabled because admin_secret is not configured."86 )87 if secret != settings.admin_secret:88 raise HTTPException(89 status_code=status.HTTP_401_UNAUTHORIZED,90 detail="Invalid admin secret."91 )92 try:93 return list_registered_users()94 except Exception as e:95 raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))96 