Fix OAuth imports in fastapi_users when httpx-oauth is not installed

This commit is contained in:
François Voron
2025-12-19 10:32:07 +01:00
parent cf899923bf
commit 55dfc07267
2 changed files with 28 additions and 2 deletions

View File

@@ -18,13 +18,14 @@ from fastapi_users.router import (
try:
from httpx_oauth.oauth2 import BaseOAuth2
from fastapi_users.router import get_oauth_router
from fastapi_users.router.oauth import (
CSRF_TOKEN_COOKIE_NAME,
get_oauth_associate_router,
get_oauth_router,
)
except ModuleNotFoundError: # pragma: no cover
BaseOAuth2 = type # type: ignore
CSRF_TOKEN_COOKIE_NAME = "" # type: ignore
class FastAPIUsers(Generic[models.UP, models.ID]):
@@ -156,6 +157,12 @@ class FastAPIUsers(Generic[models.UP, models.ID]):
state_secret: SecretType,
redirect_url: str | None = None,
requires_verification: bool = False,
csrf_token_cookie_name: str = CSRF_TOKEN_COOKIE_NAME,
csrf_token_cookie_path: str = "/",
csrf_token_cookie_domain: str | None = None,
csrf_token_cookie_secure: bool = True,
csrf_token_cookie_httponly: bool = True,
csrf_token_cookie_samesite: Literal["lax", "strict", "none"] = "lax",
) -> APIRouter:
"""
Return an OAuth association router for a given OAuth client.
@@ -167,6 +174,15 @@ class FastAPIUsers(Generic[models.UP, models.ID]):
If not given, the URL to the callback endpoint will be generated.
:param requires_verification: Whether the endpoints
require the users to be verified or not. Defaults to False.
:param csrf_token_cookie_name: Name of the cookie.
:param csrf_token_cookie_path: Cookie path.
:param csrf_token_cookie_domain: Cookie domain.
:param csrf_token_cookie_secure: Whether to only send the cookie to the
server via SSL request.
:param csrf_token_cookie_httponly: Whether to prevent access to the cookie
via JavaScript.
:param csrf_token_cookie_samesite: A string that specifies the samesite
strategy for the cookie. Valid values are lax, strict and none. Defaults to lax.
"""
return get_oauth_associate_router(
oauth_client,
@@ -176,6 +192,12 @@ class FastAPIUsers(Generic[models.UP, models.ID]):
state_secret,
redirect_url,
requires_verification,
csrf_token_cookie_name=csrf_token_cookie_name,
csrf_token_cookie_path=csrf_token_cookie_path,
csrf_token_cookie_domain=csrf_token_cookie_domain,
csrf_token_cookie_secure=csrf_token_cookie_secure,
csrf_token_cookie_httponly=csrf_token_cookie_httponly,
csrf_token_cookie_samesite=csrf_token_cookie_samesite,
)
def get_users_router(

View File

@@ -15,8 +15,12 @@ __all__ = [
]
try: # pragma: no cover
from fastapi_users.router.oauth import get_oauth_router # noqa: F401
from fastapi_users.router.oauth import ( # noqa: F401
get_oauth_associate_router,
get_oauth_router,
)
__all__.append("get_oauth_router")
__all__.append("get_oauth_associate_router")
except ModuleNotFoundError: # pragma: no cover
pass