from datetime import timezone from fastapi import ( APIRouter, Depends, Header, HTTPException, Request, status, ) from fastapi.security import HTTPBasic, HTTPBasicCredentials from sqlalchemy.orm import Session from app.api.deps import get_db from app.api.users import user_to_response from app.services.auth_service import ( AuthService, InvalidCredentialsError, InvalidSessionError, LoginRateLimitError, LoginRateLimitUnavailableError, ) router = APIRouter(prefix="/api/v1/auth", tags=["Authentication"]) basic_security = HTTPBasic(auto_error=False) @router.post("/sessions", status_code=status.HTTP_201_CREATED) def create_session( request: Request, credentials: HTTPBasicCredentials = Depends(basic_security), db: Session = Depends(get_db), ): if credentials is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Basic authentication required", headers={ "WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"' }, ) client_ip = request.headers.get("x-real-ip") if not client_ip and request.client: client_ip = request.client.host try: result = AuthService(db).create_session( username=credentials.username, password=credentials.password, client_ip=client_ip or "unknown", ) expires_at = result["expires_at"] if expires_at.tzinfo is None: expires_at = expires_at.replace(tzinfo=timezone.utc) else: expires_at = expires_at.astimezone(timezone.utc) return { "token": result["token"], "token_type": result["token_type"], "expires_at": expires_at.isoformat( timespec="microseconds" ).replace("+00:00", "Z"), "user": user_to_response(result["user"]), } except InvalidCredentialsError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid username or password", headers={ "WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"' }, ) from None except LoginRateLimitError as exc: raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many login attempts. Try again later.", headers={"Retry-After": str(exc.retry_after)}, ) from None except LoginRateLimitUnavailableError: raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Authentication service temporarily unavailable", headers={"Retry-After": "5"}, ) from None @router.delete( "/sessions/current", status_code=status.HTTP_204_NO_CONTENT, ) def delete_current_session( authorization: str | None = Header(default=None), db: Session = Depends(get_db), ): if not authorization or not authorization.startswith("Bearer "): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Bearer token required", headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, ) token = authorization[7:].strip() if not token: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Bearer token required", headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, ) try: AuthService(db).delete_session(token) except InvalidSessionError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired session", headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, ) from None