Files
Aether/backend/app/utils/OAuth2WithCookie.py
T
2026-01-25 11:30:30 +03:00

45 lines
1.5 KiB
Python

from typing import Dict, Optional
from fastapi import HTTPException, Request, status, WebSocket
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
from fastapi.security import OAuth2
from fastapi.security.utils import get_authorization_scheme_param
class OAuth2PasswordBearerWithCookie(OAuth2):
def __init__(
self,
tokenUrl: str,
scheme_name: Optional[str] = None,
scopes: Optional[Dict[str, str]] = None,
auto_error: bool = True,
):
if not scopes:
scopes = {}
flows = OAuthFlowsModel(
password={"tokenUrl": tokenUrl, "scopes": scopes})
super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)
async def __call__(
self,
request: Request = None,
websocket: WebSocket = None
) -> Optional[str]:
connection = request or websocket
if connection is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No connection found")
authorization: str = connection.cookies.get("access_token")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "bearer":
if self.auto_error:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
else:
return None
return param