You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
2.3 KiB
Python
71 lines
2.3 KiB
Python
from fastapi import Request, Response
|
|
|
|
from admin_app.core import AdminAuthenticatedSession, AdminSettings
|
|
|
|
PANEL_ACCESS_COOKIE_NAME = "orquestrador_admin_panel_access"
|
|
PANEL_REFRESH_COOKIE_NAME = "orquestrador_admin_panel_refresh"
|
|
PANEL_COOKIE_SAMESITE = "lax"
|
|
|
|
# Sessão web do painel. Realiza a ponte entre o AuthService (que realiza a autenticação e geração do token) e o navegador usando cookies HTTP.
|
|
|
|
# É o adaptador entre a autenticação administrativa orientada a tokens e o modo como o painel web mantém sessão no navegador.
|
|
|
|
def get_panel_access_cookie(request: Request) -> str | None:
|
|
return request.cookies.get(PANEL_ACCESS_COOKIE_NAME)
|
|
|
|
|
|
def get_panel_refresh_cookie(request: Request) -> str | None:
|
|
return request.cookies.get(PANEL_REFRESH_COOKIE_NAME)
|
|
|
|
|
|
def set_panel_auth_cookies(
|
|
response: Response,
|
|
session: AdminAuthenticatedSession,
|
|
settings: AdminSettings,
|
|
) -> None:
|
|
cookie_path = build_panel_cookie_path(settings)
|
|
use_secure = should_use_secure_cookies(settings)
|
|
response.set_cookie(
|
|
key=PANEL_ACCESS_COOKIE_NAME,
|
|
value=session.access_token,
|
|
max_age=session.expires_in_seconds,
|
|
httponly=True,
|
|
secure=use_secure,
|
|
samesite=PANEL_COOKIE_SAMESITE,
|
|
path=cookie_path,
|
|
)
|
|
response.set_cookie(
|
|
key=PANEL_REFRESH_COOKIE_NAME,
|
|
value=session.refresh_token,
|
|
max_age=settings.admin_auth_refresh_token_ttl_days * 24 * 60 * 60,
|
|
httponly=True,
|
|
secure=use_secure,
|
|
samesite=PANEL_COOKIE_SAMESITE,
|
|
path=cookie_path,
|
|
)
|
|
|
|
|
|
def clear_panel_auth_cookies(response: Response, settings: AdminSettings) -> None:
|
|
cookie_path = build_panel_cookie_path(settings)
|
|
response.delete_cookie(
|
|
key=PANEL_ACCESS_COOKIE_NAME,
|
|
path=cookie_path,
|
|
httponly=True,
|
|
samesite=PANEL_COOKIE_SAMESITE,
|
|
)
|
|
response.delete_cookie(
|
|
key=PANEL_REFRESH_COOKIE_NAME,
|
|
path=cookie_path,
|
|
httponly=True,
|
|
samesite=PANEL_COOKIE_SAMESITE,
|
|
)
|
|
|
|
|
|
def build_panel_cookie_path(settings: AdminSettings) -> str:
|
|
normalized_prefix = settings.admin_api_prefix.rstrip("/")
|
|
return normalized_prefix or "/"
|
|
|
|
|
|
def should_use_secure_cookies(settings: AdminSettings) -> bool:
|
|
return settings.admin_environment.lower() == "production" and not settings.admin_debug
|