Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /mdfarhankc_fastapi-fullauth /fastapi_fullauth /routers /passkey.py
| import logging | |
| from typing import TYPE_CHECKING, Any, cast | |
| from uuid import UUID | |
| from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response | |
| from pydantic import BaseModel | |
| from fastapi_fullauth.adapters.base import PasskeyAdapterMixin | |
| from fastapi_fullauth.dependencies.current_user import CurrentUser, get_fullauth | |
| from fastapi_fullauth.protection.challenges import ChallengeStore | |
| from fastapi_fullauth.routers._schemas import LoginResponse, build_login_response_model | |
| from fastapi_fullauth.routers._transport import write_tokens | |
| from fastapi_fullauth.types import TokenPair, UserSchema, UserSchemaType | |
| from fastapi_fullauth.utils import request_session_metadata | |
| logger = logging.getLogger("fastapi_fullauth.routers.passkey") | |
| if TYPE_CHECKING: | |
| from fastapi_fullauth.fullauth import FullAuth | |
| class RegisterCompleteRequest(BaseModel): | |
| challenge_key: str | |
| credential: dict[str, Any] | |
| device_name: str = "" | |
| class AuthenticateBeginRequest(BaseModel): | |
| email: str | None = None | |
| class AuthenticateCompleteRequest(BaseModel): | |
| challenge_key: str | |
| credential: dict[str, Any] | |
| class PasskeyResponse(BaseModel): | |
| id: UUID | |
| device_name: str | |
| transports: list[str] | |
| backed_up: bool | |
| created_at: str | None = None | |
| last_used_at: str | None = None | |
| def create_passkey_router( | |
| user_schema: type[UserSchemaType] = UserSchema, # type: ignore[assignment] | |
| login_response_schema: type[LoginResponse] = LoginResponse, | |
| ) -> APIRouter: | |
| LoginResponse = build_login_response_model(user_schema, base=login_response_schema) # noqa: N806 | |
| router = APIRouter() | |
| async def register_begin( | |
| user: CurrentUser, | |
| fullauth: "FullAuth" = Depends(get_fullauth), | |
| ) -> dict[str, Any]: | |
| from fastapi_fullauth.flows.passkey import begin_registration | |
| if not fullauth.config.PASSKEY_ENABLED: | |
| raise HTTPException(status_code=404, detail="Passkeys are not enabled") | |
| if not isinstance(fullauth.adapter, PasskeyAdapterMixin): | |
| raise HTTPException(status_code=501, detail="Adapter does not support passkeys") | |
| # Narrowed by FullAuthConfig._validate_passkey_config at construction time: | |
| # PASSKEY_RP_ID is non-None and challenge_store is set when PASSKEY_ENABLED=True. | |
| rp_id = cast("str", fullauth.config.PASSKEY_RP_ID) | |
| challenge_store = cast("ChallengeStore", fullauth.challenge_store) | |
| return await begin_registration( | |
| user=user, | |
| rp_id=rp_id, | |
| rp_name=fullauth.config.PASSKEY_RP_NAME or rp_id, | |
| challenge_store=challenge_store, | |
| adapter=fullauth.adapter, | |
| challenge_ttl=fullauth.config.PASSKEY_CHALLENGE_TTL, | |
| require_user_verification=fullauth.config.PASSKEY_REQUIRE_USER_VERIFICATION, | |
| ) | |
| async def register_complete( | |
| user: CurrentUser, | |
| data: RegisterCompleteRequest, | |
| fullauth: "FullAuth" = Depends(get_fullauth), | |
| ) -> PasskeyResponse: | |
| from fastapi_fullauth.flows.passkey import complete_registration | |
| if not isinstance(fullauth.adapter, PasskeyAdapterMixin): | |
| raise HTTPException(status_code=501, detail="Adapter does not support passkeys") | |
| origins = fullauth.config.PASSKEY_ORIGINS | |
| if not origins: | |
| raise HTTPException(status_code=500, detail="PASSKEY_ORIGINS not configured") | |
| rp_id = cast("str", fullauth.config.PASSKEY_RP_ID) | |
| challenge_store = cast("ChallengeStore", fullauth.challenge_store) | |
| try: | |
| passkey = await complete_registration( | |
| challenge_key=data.challenge_key, | |
| credential=data.credential, | |
| device_name=data.device_name, | |
| user=user, | |
| rp_id=rp_id, | |
| expected_origin=origins, | |
| challenge_store=challenge_store, | |
| adapter=fullauth.adapter, | |
| require_user_verification=fullauth.config.PASSKEY_REQUIRE_USER_VERIFICATION, | |
| ) | |
| except ValueError as e: | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| except Exception: | |
| logger.exception("Passkey registration failed") | |
| raise HTTPException(status_code=400, detail="Passkey registration failed") | |
| return PasskeyResponse( | |
| id=passkey.id, | |
| device_name=passkey.device_name, | |
| transports=passkey.transports, | |
| backed_up=passkey.backed_up, | |
| created_at=passkey.created_at.isoformat() if passkey.created_at else None, | |
| last_used_at=None, | |
| ) | |
| async def authenticate_begin( | |
| request: Request, | |
| data: AuthenticateBeginRequest = Body(AuthenticateBeginRequest()), | |
| fullauth: "FullAuth" = Depends(get_fullauth), | |
| ) -> dict[str, Any]: | |
| from fastapi_fullauth.flows.passkey import begin_authentication | |
| if not fullauth.config.PASSKEY_ENABLED: | |
| raise HTTPException(status_code=404, detail="Passkeys are not enabled") | |
| if not isinstance(fullauth.adapter, PasskeyAdapterMixin): | |
| raise HTTPException(status_code=501, detail="Adapter does not support passkeys") | |
| await fullauth.enforce_rate_limit(request, "passkey-authenticate") | |
| user_id = None | |
| email_provided = bool(data.email) | |
| if data.email: | |
| user = await fullauth.adapter.get_user_by_email(data.email) | |
| if user: | |
| user_id = user.id | |
| rp_id = cast("str", fullauth.config.PASSKEY_RP_ID) | |
| challenge_store = cast("ChallengeStore", fullauth.challenge_store) | |
| return await begin_authentication( | |
| rp_id=rp_id, | |
| challenge_store=challenge_store, | |
| adapter=fullauth.adapter, | |
| user_id=user_id, | |
| email_provided=email_provided, | |
| challenge_ttl=fullauth.config.PASSKEY_CHALLENGE_TTL, | |
| ) | |
| async def authenticate_complete( | |
| data: AuthenticateCompleteRequest, | |
| request: Request, | |
| response: Response, | |
| fullauth: "FullAuth" = Depends(get_fullauth), | |
| ) -> TokenPair: | |
| from fastapi_fullauth.flows.passkey import complete_authentication | |
| if not isinstance(fullauth.adapter, PasskeyAdapterMixin): | |
| raise HTTPException(status_code=501, detail="Adapter does not support passkeys") | |
| await fullauth.enforce_rate_limit(request, "passkey-authenticate") | |
| origins = fullauth.config.PASSKEY_ORIGINS | |
| if not origins: | |
| raise HTTPException(status_code=500, detail="PASSKEY_ORIGINS not configured") | |
| rp_id = cast("str", fullauth.config.PASSKEY_RP_ID) | |
| challenge_store = cast("ChallengeStore", fullauth.challenge_store) | |
| user_agent, ip_address = request_session_metadata( | |
| request, fullauth.config.TRUSTED_PROXY_HEADERS, fullauth.config.TRUSTED_PROXY_COUNT | |
| ) | |
| try: | |
| token_pair, user = await complete_authentication( | |
| challenge_key=data.challenge_key, | |
| credential=data.credential, | |
| rp_id=rp_id, | |
| expected_origin=origins, | |
| challenge_store=challenge_store, | |
| adapter=fullauth.adapter, | |
| passkey_adapter=fullauth.adapter, | |
| token_engine=fullauth.token_engine, | |
| require_user_verification=fullauth.config.PASSKEY_REQUIRE_USER_VERIFICATION, | |
| user_agent=user_agent, | |
| ip_address=ip_address, | |
| ) | |
| except Exception: | |
| # Uniform 401 for every failure (unknown credential, bad signature, | |
| # clone detection, inactive user) so this login-equivalent endpoint | |
| # can't be used to enumerate credentials or account state. The | |
| # specific reason is logged server-side. | |
| logger.exception("Passkey authentication failed") | |
| raise HTTPException(status_code=401, detail="Passkey authentication failed") | |
| token_pair = await write_tokens(response, fullauth, token_pair) | |
| await fullauth.hooks.emit("after_login", user=user) | |
| if user is not None: | |
| return LoginResponse( | |
| access_token=token_pair.access_token, | |
| refresh_token=token_pair.refresh_token, | |
| token_type=token_pair.token_type, | |
| expires_in=token_pair.expires_in, | |
| user=user, | |
| ) | |
| return token_pair | |
| async def list_passkeys( | |
| user: CurrentUser, | |
| fullauth: "FullAuth" = Depends(get_fullauth), | |
| ) -> list[PasskeyResponse]: | |
| if not isinstance(fullauth.adapter, PasskeyAdapterMixin): | |
| raise HTTPException(status_code=501, detail="Adapter does not support passkeys") | |
| passkeys = await fullauth.adapter.get_user_passkeys(user.id) | |
| return [ | |
| PasskeyResponse( | |
| id=pk.id, | |
| device_name=pk.device_name, | |
| transports=pk.transports, | |
| backed_up=pk.backed_up, | |
| created_at=pk.created_at.isoformat() if pk.created_at else None, | |
| last_used_at=pk.last_used_at.isoformat() if pk.last_used_at else None, | |
| ) | |
| for pk in passkeys | |
| ] | |
| async def delete_passkey( | |
| passkey_id: UUID, | |
| user: CurrentUser, | |
| fullauth: "FullAuth" = Depends(get_fullauth), | |
| ) -> None: | |
| if not isinstance(fullauth.adapter, PasskeyAdapterMixin): | |
| raise HTTPException(status_code=501, detail="Adapter does not support passkeys") | |
| passkeys = await fullauth.adapter.get_user_passkeys(user.id) | |
| if not any(pk.id == passkey_id for pk in passkeys): | |
| raise HTTPException(status_code=404, detail="Passkey not found") | |
| await fullauth.adapter.delete_passkey(passkey_id) | |
| logger.info("Passkey deleted: user_id=%s, passkey_id=%s", user.id, passkey_id) | |
| return router | |
Xet Storage Details
- Size:
- 11 kB
- Xet hash:
- 938d2d5f3020fcba4e2366615dc8d737b4c863a0672b18e5ed5af6572e0f0d46
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.