Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /mdfarhankc_fastapi-fullauth /fastapi_fullauth /fullauth.py
| import asyncio | |
| import logging | |
| import warnings | |
| from collections.abc import AsyncIterator, Coroutine | |
| from contextlib import asynccontextmanager | |
| from typing import Any, Generic | |
| from fastapi import APIRouter, FastAPI, Request | |
| from fastapi_fullauth.adapters.base import AbstractUserAdapter | |
| from fastapi_fullauth.backends import AbstractBackend, BearerBackend | |
| from fastapi_fullauth.config import FullAuthConfig | |
| from fastapi_fullauth.core.tokens import TokenEngine, create_blacklist | |
| from fastapi_fullauth.hooks import EventHooks | |
| from fastapi_fullauth.oauth.base import OAuthProvider | |
| from fastapi_fullauth.protection.lockout import create_lockout | |
| from fastapi_fullauth.protection.ratelimit import AuthRateLimiter | |
| from fastapi_fullauth.routers._schemas import LoginResponse, MessageResponse | |
| from fastapi_fullauth.types import ( | |
| CreateUserSchemaType, | |
| RouterName, | |
| TokenClaimsBuilder, | |
| UserSchema, | |
| UserSchemaType, | |
| ) | |
| from fastapi_fullauth.utils import get_client_ip | |
| from fastapi_fullauth.validators import PasswordValidator | |
| logger = logging.getLogger("fastapi_fullauth") | |
| class FullAuth(Generic[UserSchemaType, CreateUserSchemaType]): | |
| """Main auth manager. | |
| Args: | |
| adapter: Database backend (SQLModelAdapter, SQLAlchemyAdapter, etc.). | |
| config: FullAuthConfig object. Reads from env (FULLAUTH_ prefix) if omitted. | |
| providers: OAuth providers (GoogleOAuthProvider, GitHubOAuthProvider, etc.). | |
| backends: Token transport strategies. Defaults to [BearerBackend()]. | |
| password_validator: Custom PasswordValidator. Defaults to min-length from config. | |
| on_create_token_claims: async `(user) -> dict` returning extra claims for JWTs. | |
| login_response_schema: Custom `LoginResponse` subclass for the login/OAuth/passkey | |
| token responses. Add optional fields to extend the body. | |
| message_response_schema: Custom `MessageResponse` subclass for endpoints that return | |
| a `{detail: ...}` body. | |
| """ | |
| def __init__( | |
| self, | |
| *, | |
| adapter: AbstractUserAdapter[UserSchemaType, CreateUserSchemaType], | |
| config: FullAuthConfig | None = None, | |
| providers: list[OAuthProvider] | None = None, | |
| backends: list[AbstractBackend] | None = None, | |
| password_validator: PasswordValidator | None = None, | |
| on_create_token_claims: TokenClaimsBuilder | None = None, | |
| login_response_schema: type[LoginResponse] | None = None, | |
| message_response_schema: type[MessageResponse] | None = None, | |
| ) -> None: | |
| if config is None: | |
| config = FullAuthConfig() | |
| self.config = config | |
| self.adapter = adapter | |
| self.backends = backends or [BearerBackend()] | |
| self.token_engine = TokenEngine(config=config, blacklist=create_blacklist(config)) | |
| self.lockout = create_lockout(config) | |
| self.auth_rate_limiter = AuthRateLimiter(config) | |
| self.challenge_store = None | |
| if config.PASSKEY_ENABLED: | |
| from fastapi_fullauth.protection.challenges import create_challenge_store | |
| self.challenge_store = create_challenge_store(config) | |
| self._warn_memory_backends(config) | |
| self.password_validator = password_validator or PasswordValidator( | |
| min_length=config.PASSWORD_MIN_LENGTH | |
| ) | |
| self.on_create_token_claims = on_create_token_claims | |
| self.login_response_schema = login_response_schema or LoginResponse | |
| self.message_response_schema = message_response_schema or MessageResponse | |
| self.hooks = EventHooks() | |
| self.oauth_providers: dict[str, OAuthProvider] = {p.name: p for p in (providers or [])} | |
| self._warn_adapter_feature_mismatch() | |
| self._log_effective_config(config) | |
| self._auth_router: APIRouter | None = None | |
| self._profile_router: APIRouter | None = None | |
| self._verify_router: APIRouter | None = None | |
| self._admin_router: APIRouter | None = None | |
| self._passkey_router: APIRouter | None = None | |
| self._sessions_router: APIRouter | None = None | |
| self._router: APIRouter | None = None | |
| _RESERVED_CLAIM_KEYS = frozenset( | |
| {"sub", "exp", "iat", "jti", "type", "roles", "extra", "family_id", "purpose"} | |
| ) | |
| def _warn_memory_backends(config: FullAuthConfig) -> None: | |
| # Each of these stores per-process state. Under `uvicorn --workers N` | |
| # state isn't shared between workers: blacklisted tokens stay valid on | |
| # other workers, lockouts and rate limits reset per worker, and passkey | |
| # begin/complete can land on different workers and break the flow. | |
| offenders: list[str] = [] | |
| if config.BLACKLIST_ENABLED and config.BLACKLIST_BACKEND == "memory": | |
| offenders.append("BLACKLIST_BACKEND") | |
| if config.LOCKOUT_ENABLED and config.LOCKOUT_BACKEND == "memory": | |
| offenders.append("LOCKOUT_BACKEND") | |
| if config.AUTH_RATE_LIMIT_ENABLED and config.RATE_LIMIT_BACKEND == "memory": | |
| offenders.append("RATE_LIMIT_BACKEND") | |
| if config.PASSKEY_ENABLED and config.PASSKEY_CHALLENGE_BACKEND == "memory": | |
| offenders.append("PASSKEY_CHALLENGE_BACKEND") | |
| if offenders: | |
| warnings.warn( | |
| f"In-memory backends in use: {', '.join(offenders)}. " | |
| "State is per-process; logout/revocation, lockouts, rate limits, and " | |
| "passkey flows will behave inconsistently under multi-worker deployments. " | |
| "Set these to 'redis' (and configure REDIS_URL) in production.", | |
| UserWarning, | |
| stacklevel=3, | |
| ) | |
| def _warn_adapter_feature_mismatch(self) -> None: | |
| # A feature can be configured while the adapter can't serve it - either | |
| # the matching mixin isn't implemented, or (for the SQL adapters, which | |
| # inherit every mixin) the required model wasn't passed. The router build | |
| # skips those routes, so the symptom is a 404 with no explanation. | |
| # Surface it at construction. | |
| if self.config.PASSKEY_ENABLED and not self.adapter.supports_feature("passkey"): | |
| warnings.warn( | |
| "PASSKEY_ENABLED is set but the adapter cannot serve passkeys " | |
| "(missing PasskeyAdapterMixin or passkey_model); passkey routes " | |
| "will not be registered.", | |
| UserWarning, | |
| stacklevel=3, | |
| ) | |
| if self.oauth_providers and not self.adapter.supports_feature("oauth"): | |
| warnings.warn( | |
| "OAuth providers are configured but the adapter cannot serve OAuth " | |
| "(missing OAuthAdapterMixin or oauth_account_model); OAuth routes " | |
| "will not be registered.", | |
| UserWarning, | |
| stacklevel=3, | |
| ) | |
| if self.oauth_providers and not self.config.BLACKLIST_ENABLED: | |
| warnings.warn( | |
| "OAuth providers are configured but BLACKLIST_ENABLED is False, so " | |
| "OAuth state tokens can't be burned after use; a captured (code, " | |
| "state) pair is replayable within the state TTL. Enable the token " | |
| "blacklist in production.", | |
| UserWarning, | |
| stacklevel=3, | |
| ) | |
| def _log_effective_config(self, config: FullAuthConfig) -> None: | |
| # One line showing the resolved state, since BACKEND/PASSKEY_ENABLED are | |
| # now inferred from REDIS_URL/PASSKEY_RP_ID and aren't otherwise visible. | |
| parts = [ | |
| f"blacklist={config.BLACKLIST_BACKEND if config.BLACKLIST_ENABLED else 'off'}", | |
| f"lockout={config.LOCKOUT_BACKEND if config.LOCKOUT_ENABLED else 'off'}", | |
| f"ratelimit={config.RATE_LIMIT_BACKEND if config.AUTH_RATE_LIMIT_ENABLED else 'off'}", | |
| ] | |
| if config.PASSKEY_ENABLED: | |
| parts.append(f"passkey={config.PASSKEY_CHALLENGE_BACKEND}") | |
| logger.info( | |
| "fullauth ready: %s | passkeys=%s | oauth=%s", | |
| " ".join(parts), | |
| "on" if config.PASSKEY_ENABLED else "off", | |
| ",".join(self.oauth_providers) or "none", | |
| ) | |
| def _warn_cookie_backend_without_csrf(self, app: FastAPI) -> None: | |
| from fastapi_fullauth.backends import CookieBackend | |
| from fastapi_fullauth.middleware.csrf import CSRFMiddleware | |
| if not any(isinstance(b, CookieBackend) for b in self.backends): | |
| return | |
| # Starlette types m.cls as a middleware factory, so mypy can't see the | |
| # identity overlap with the concrete class; the check itself is correct. | |
| if any(m.cls is CSRFMiddleware for m in app.user_middleware): # type: ignore[comparison-overlap] | |
| return | |
| warnings.warn( | |
| "CookieBackend is in use but CSRFMiddleware is not wired on this app; " | |
| "cookie-based sessions are exposed to CSRF. Add " | |
| "app.add_middleware(CSRFMiddleware, secret=config.SECRET_KEY). " | |
| "Ignore this if you wire the middleware after init_app().", | |
| UserWarning, | |
| stacklevel=3, | |
| ) | |
| def _register_aclose(self, app: FastAPI) -> None: | |
| # add_event_handler("shutdown", ...) only fires under Starlette's default | |
| # lifespan; an app built with a custom lifespan= would silently leak | |
| # pooled Redis connections and OAuth HTTP clients. Wrap the existing | |
| # lifespan_context instead so cleanup composes with any lifespan: the | |
| # existing context becomes the inner one, and aclose() runs after its | |
| # teardown. The sentinel keeps an accidental double-wrap a no-op. | |
| existing = app.router.lifespan_context | |
| if getattr(existing, "_fullauth_aclose_wrapped", False): | |
| return | |
| async def wrapped(app: FastAPI) -> AsyncIterator[Any]: | |
| try: | |
| async with existing(app) as state: | |
| yield state | |
| finally: | |
| await self.aclose() | |
| wrapped._fullauth_aclose_wrapped = True # type: ignore[attr-defined] | |
| app.router.lifespan_context = wrapped | |
| def _warn_missing_email_hooks(self, mounted: set[str]) -> None: | |
| # The verify router exposes email verification and password reset, which | |
| # only deliver anything if the matching send_* hook is registered. | |
| # Without it the endpoint still returns 200 and the token is dropped. | |
| if "verify" not in mounted: | |
| return | |
| missing = [ | |
| event | |
| for event in ("send_verification_email", "send_password_reset_email") | |
| if not self.hooks.has_listeners(event) | |
| ] | |
| if missing: | |
| warnings.warn( | |
| f"The verify router is mounted but no hook is registered for " | |
| f"{', '.join(missing)}; those tokens are generated but never delivered. " | |
| "Register the hook(s) with fullauth.hooks.on(...) before init_app(), " | |
| "or drop the verify router via init_app(include_routers=...).", | |
| UserWarning, | |
| stacklevel=3, | |
| ) | |
| async def get_custom_claims(self, user: UserSchema) -> dict[str, Any]: | |
| if not self.on_create_token_claims: | |
| return {} | |
| claims = await self.on_create_token_claims(user) | |
| if not isinstance(claims, dict): | |
| raise TypeError( | |
| f"on_create_token_claims must return a dict, got {type(claims).__name__}" | |
| ) | |
| reserved = self._RESERVED_CLAIM_KEYS & claims.keys() | |
| if reserved: | |
| raise ValueError(f"Custom claims contain reserved keys: {', '.join(sorted(reserved))}") | |
| return claims | |
| async def check_auth_rate_limit(self, route_name: str, client_ip: str) -> None: | |
| await self.auth_rate_limiter.check(route_name, client_ip) | |
| async def enforce_rate_limit(self, request: Request, route_name: str) -> None: | |
| """Resolve the client IP and apply the auth rate limit for ``route_name``.""" | |
| client_ip = get_client_ip( | |
| request, self.config.TRUSTED_PROXY_HEADERS, self.config.TRUSTED_PROXY_COUNT | |
| ) | |
| await self.check_auth_rate_limit(route_name, client_ip) | |
| async def aclose(self) -> None: | |
| """Close pooled resources: Redis connections and OAuth HTTP clients. | |
| Idempotent. ``init_app()`` runs this on app shutdown by wrapping the | |
| app's lifespan, so it fires even under a custom ``lifespan``. You only | |
| need to call it yourself when managing FullAuth without ``init_app()``. | |
| Each resource is closed independently: a failure closing one (for | |
| example a Redis socket error during shutdown) is logged and does not | |
| prevent the others from closing, so nothing leaks. | |
| """ | |
| closers: list[tuple[str, Coroutine[Any, Any, Any]]] = [ | |
| ("token blacklist", self.token_engine.blacklist.aclose()), | |
| ] | |
| if self.lockout is not None: | |
| closers.append(("lockout store", self.lockout.aclose())) | |
| closers.append(("auth rate limiter", self.auth_rate_limiter.aclose())) | |
| if self.challenge_store is not None: | |
| closers.append(("passkey challenge store", self.challenge_store.aclose())) | |
| for name, provider in self.oauth_providers.items(): | |
| closers.append((f"oauth provider '{name}'", provider.aclose())) | |
| results = await asyncio.gather(*(coro for _, coro in closers), return_exceptions=True) | |
| for (label, _), result in zip(closers, results, strict=True): | |
| if isinstance(result, Exception): | |
| logger.warning( | |
| "Error closing %s during shutdown: %s", label, result, exc_info=result | |
| ) | |
| # ── composable routers ────────────────────────────────────────── | |
| def auth_router(self) -> APIRouter: | |
| if self._auth_router is None: | |
| from fastapi_fullauth.routers.auth import create_auth_router | |
| self._auth_router = create_auth_router( | |
| create_user_schema=self.adapter._create_user_schema, | |
| user_schema=self.adapter._user_schema, | |
| login_field=self.config.LOGIN_FIELD, | |
| login_response_schema=self.login_response_schema, | |
| message_response_schema=self.message_response_schema, | |
| ) | |
| return self._auth_router | |
| def profile_router(self) -> APIRouter: | |
| if self._profile_router is None: | |
| from fastapi_fullauth.routers.profile import create_profile_router | |
| self._profile_router = create_profile_router( | |
| user_schema=self.adapter._user_schema, | |
| message_response_schema=self.message_response_schema, | |
| ) | |
| return self._profile_router | |
| def verify_router(self) -> APIRouter: | |
| if self._verify_router is None: | |
| from fastapi_fullauth.routers.verify import create_verify_router | |
| self._verify_router = create_verify_router( | |
| message_response_schema=self.message_response_schema, | |
| ) | |
| return self._verify_router | |
| def admin_router(self) -> APIRouter: | |
| if self._admin_router is None: | |
| from fastapi_fullauth.routers.admin import create_admin_router | |
| self._admin_router = create_admin_router() | |
| return self._admin_router | |
| def oauth_router(self) -> APIRouter | None: | |
| if not self.oauth_providers: | |
| return None | |
| from fastapi_fullauth.routers.oauth import create_oauth_router | |
| return create_oauth_router( | |
| user_schema=self.adapter._user_schema, | |
| login_response_schema=self.login_response_schema, | |
| ) | |
| def passkey_router(self) -> APIRouter | None: | |
| if not self.config.PASSKEY_ENABLED: | |
| return None | |
| if self._passkey_router is None: | |
| from fastapi_fullauth.routers.passkey import create_passkey_router | |
| self._passkey_router = create_passkey_router( | |
| user_schema=self.adapter._user_schema, | |
| login_response_schema=self.login_response_schema, | |
| ) | |
| return self._passkey_router | |
| def sessions_router(self) -> APIRouter: | |
| if self._sessions_router is None: | |
| from fastapi_fullauth.routers.sessions import create_sessions_router | |
| self._sessions_router = create_sessions_router() | |
| return self._sessions_router | |
| _ROUTER_NAMES: set[RouterName] = { | |
| "auth", | |
| "profile", | |
| "verify", | |
| "admin", | |
| "oauth", | |
| "passkey", | |
| "sessions", | |
| } | |
| def _build_router(self, exclude: set[str] | None = None) -> APIRouter: | |
| """Build combined router, optionally excluding named sub-routers.""" | |
| exclude = exclude or set() | |
| prefix = self.config.API_PREFIX.rstrip("/") + self.config.AUTH_ROUTER_PREFIX | |
| router = APIRouter(prefix=prefix, tags=self.config.ROUTER_TAGS) # type: ignore[arg-type] | |
| if "auth" not in exclude: | |
| router.include_router(self.auth_router) | |
| if "profile" not in exclude: | |
| router.include_router(self.profile_router) | |
| if "verify" not in exclude: | |
| router.include_router(self.verify_router) | |
| if "admin" not in exclude and self.adapter.supports_feature("role"): | |
| router.include_router(self.admin_router) | |
| if ( | |
| "oauth" not in exclude | |
| and self.adapter.supports_feature("oauth") | |
| and self.oauth_router is not None | |
| ): | |
| router.include_router(self.oauth_router) | |
| if ( | |
| "passkey" not in exclude | |
| and self.adapter.supports_feature("passkey") | |
| and self.passkey_router is not None | |
| ): | |
| router.include_router(self.passkey_router) | |
| if "sessions" not in exclude and self.adapter.supports_feature("session"): | |
| router.include_router(self.sessions_router) | |
| return router | |
| def router(self) -> APIRouter: | |
| """Combined router with all route groups. Used by init_app().""" | |
| if self._router is None: | |
| self._router = self._build_router() | |
| return self._router | |
| def bind(self, app: FastAPI) -> None: | |
| """Bind this FullAuth instance to a FastAPI app. | |
| Required when using composable routers without init_app(). | |
| Sets app.state.fullauth so dependencies can resolve. | |
| Called automatically by init_app(). | |
| Unlike init_app(), this registers no shutdown cleanup: call | |
| ``await fullauth.aclose()`` in your own shutdown to release pooled | |
| Redis connections and OAuth HTTP clients. | |
| """ | |
| app.state.fullauth = self | |
| def init_app( | |
| self, | |
| app: FastAPI, | |
| *, | |
| include_routers: list[RouterName] | None = None, | |
| ) -> None: | |
| """Bind FullAuth to a FastAPI app and register auth routers. | |
| Middleware is intentionally not wired here = import what you want from | |
| ``fastapi_fullauth.middleware`` and call ``app.add_middleware(...)`` | |
| yourself. | |
| Registers ``aclose()`` on app shutdown to release pooled resources. This | |
| composes with a custom ``lifespan`` (the existing lifespan is wrapped), | |
| so you do not need to call ``aclose()`` yourself. | |
| Args: | |
| app: The FastAPI application. | |
| include_routers: Allowlist of router names to register. ``None`` | |
| registers every available router (default). Pass an explicit | |
| list (e.g. ``["auth", "profile"]``) to opt in selectively. | |
| """ | |
| if getattr(app.state, "_fullauth_app_wired", False): | |
| warnings.warn( | |
| "init_app() called more than once on the same app; ignoring. " | |
| "Routers are already wired.", | |
| UserWarning, | |
| stacklevel=2, | |
| ) | |
| return | |
| app.state._fullauth_app_wired = True | |
| self.bind(app) | |
| self._register_aclose(app) | |
| self._warn_cookie_backend_without_csrf(app) | |
| if include_routers is None: | |
| mounted: set[str] = set(self._ROUTER_NAMES) | |
| else: | |
| unknown = set(include_routers) - self._ROUTER_NAMES | |
| if unknown: | |
| raise ValueError( | |
| f"Unknown routers: {', '.join(sorted(unknown))}. " | |
| f"Valid names: {', '.join(sorted(self._ROUTER_NAMES))}" | |
| ) | |
| mounted = set(include_routers) | |
| self._warn_missing_email_hooks(mounted) | |
| if include_routers is None: | |
| app.include_router(self.router) | |
| else: | |
| exclude: set[str] = {n for n in self._ROUTER_NAMES if n not in mounted} | |
| app.include_router(self._build_router(exclude=exclude)) | |
Xet Storage Details
- Size:
- 21.1 kB
- Xet hash:
- 359c15d6c547c350575650343a53eecb098c7e2f4387021aaf224ab1e1e92268
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.