import secrets
from fastapi import Request

CSRF_KEY = "csrf_token"

def get_or_create_csrf_token(request: Request) -> str:
    token = request.session.get(CSRF_KEY)
    if not token:
        token = secrets.token_urlsafe(32)
        request.session[CSRF_KEY] = token
    return token

def validate_csrf(request: Request, form_token: str | None) -> None:
    token = request.session.get(CSRF_KEY)
    if not token or not form_token or token != form_token:
        raise PermissionError("CSRF validation failed")
