Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /mdfarhankc_fastapi-fullauth /fastapi_fullauth /routers /auth.py
| import contextlib | |
| import logging | |
| from typing import TYPE_CHECKING, cast | |
| from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response | |
| from pydantic import BaseModel, ValidationError | |
| from fastapi_fullauth.dependencies.current_user import _extract_token, get_fullauth | |
| from fastapi_fullauth.exceptions import ( | |
| CREDENTIALS_EXCEPTION, | |
| USER_EXISTS_EXCEPTION, | |
| AccountLockedError, | |
| AuthenticationError, | |
| InvalidPasswordError, | |
| TokenError, | |
| UserAlreadyExistsError, | |
| ) | |
| from fastapi_fullauth.flows.login import login | |
| from fastapi_fullauth.flows.logout import logout | |
| from fastapi_fullauth.flows.refresh import refresh | |
| from fastapi_fullauth.flows.register import register | |
| from fastapi_fullauth.routers._schemas import ( | |
| LoginResponse, | |
| LogoutRequest, | |
| MessageResponse, | |
| RefreshRequest, | |
| build_login_model, | |
| build_login_response_model, | |
| ) | |
| from fastapi_fullauth.routers._transport import resolve_refresh_token, write_tokens | |
| from fastapi_fullauth.types import ( | |
| CreateUserSchema, | |
| CreateUserSchemaType, | |
| TokenPair, | |
| UserSchema, | |
| UserSchemaType, | |
| ) | |
| from fastapi_fullauth.utils import request_session_metadata | |
| logger = logging.getLogger("fastapi_fullauth.router") | |
| if TYPE_CHECKING: | |
| from fastapi_fullauth.fullauth import FullAuth | |
| def create_auth_router( | |
| create_user_schema: type[CreateUserSchemaType] = CreateUserSchema, # type: ignore[assignment] | |
| user_schema: type[UserSchemaType] = UserSchema, # type: ignore[assignment] | |
| login_field: str = "email", | |
| login_response_schema: type[LoginResponse] = LoginResponse, | |
| message_response_schema: type[MessageResponse] = MessageResponse, | |
| ) -> APIRouter: | |
| LoginRequest = build_login_model(login_field) # noqa: N806 | |
| LoginResponse = build_login_response_model(user_schema, base=login_response_schema) # noqa: N806 | |
| router = APIRouter() | |
| async def register_route( | |
| request: Request, | |
| response: Response, | |
| fullauth: "FullAuth" = Depends(get_fullauth), | |
| data: create_user_schema = Body(...), # type: ignore[valid-type] | |
| ) -> UserSchema | MessageResponse: | |
| await fullauth.enforce_rate_limit(request, "register") | |
| anti_enum = fullauth.config.PREVENT_REGISTRATION_ENUMERATION | |
| generic = message_response_schema( | |
| detail="If this email isn't already registered, a verification email has been sent." | |
| ) | |
| try: | |
| user = await register( | |
| fullauth.adapter, | |
| data, | |
| login_field=login_field, | |
| hash_algorithm=fullauth.config.PASSWORD_HASH_ALGORITHM, | |
| password_validator=fullauth.password_validator, | |
| ) | |
| except InvalidPasswordError as e: | |
| raise HTTPException(status_code=422, detail=str(e)) | |
| except UserAlreadyExistsError: | |
| if anti_enum: | |
| response.status_code = 202 | |
| return generic | |
| raise USER_EXISTS_EXCEPTION | |
| await fullauth.hooks.emit("after_register", user=user) | |
| if anti_enum: | |
| response.status_code = 202 | |
| return generic | |
| return user | |
| async def login_route( | |
| data: LoginRequest, # type: ignore[valid-type] | |
| request: Request, | |
| response: Response, | |
| fullauth: "FullAuth" = Depends(get_fullauth), | |
| ) -> TokenPair: | |
| await fullauth.enforce_rate_limit(request, "login") | |
| # LoginRequest is built dynamically via create_model from `login_field` | |
| # and "password", so static type checkers can't see either field. Go | |
| # through model_dump() (typed via the BaseModel cast) and pluck both. | |
| fields = cast("BaseModel", data).model_dump() | |
| identifier: str = fields[login_field] | |
| password: str = fields["password"] | |
| user = await fullauth.adapter.get_user_by_field(login_field, identifier) | |
| user_agent, ip_address = request_session_metadata( | |
| request, fullauth.config.TRUSTED_PROXY_HEADERS, fullauth.config.TRUSTED_PROXY_COUNT | |
| ) | |
| try: | |
| tokens = await login( | |
| adapter=fullauth.adapter, | |
| token_engine=fullauth.token_engine, | |
| identifier=identifier, | |
| password=password, | |
| login_field=login_field, | |
| lockout=fullauth.lockout, | |
| extra_claims_provider=fullauth.get_custom_claims, | |
| user=user, | |
| hash_algorithm=fullauth.config.PASSWORD_HASH_ALGORITHM, | |
| prevent_timing_attacks=fullauth.config.PREVENT_LOGIN_TIMING_ATTACKS, | |
| user_agent=user_agent, | |
| ip_address=ip_address, | |
| ) | |
| except (AccountLockedError, AuthenticationError): | |
| raise CREDENTIALS_EXCEPTION | |
| tokens = await write_tokens(response, fullauth, tokens) | |
| await fullauth.hooks.emit("after_login", user=user) | |
| if user is not None: | |
| return LoginResponse( | |
| access_token=tokens.access_token, | |
| refresh_token=tokens.refresh_token, | |
| token_type=tokens.token_type, | |
| expires_in=tokens.expires_in, | |
| user=user, | |
| ) | |
| return tokens | |
| async def refresh_route( | |
| request: Request, | |
| response: Response, | |
| fullauth: "FullAuth" = Depends(get_fullauth), | |
| data: RefreshRequest | None = Body(None), | |
| ) -> TokenPair: | |
| await fullauth.enforce_rate_limit(request, "refresh") | |
| refresh_token = await resolve_refresh_token( | |
| request, fullauth, data.refresh_token if data else None | |
| ) | |
| if refresh_token is None: | |
| raise CREDENTIALS_EXCEPTION | |
| user_agent, ip_address = request_session_metadata( | |
| request, fullauth.config.TRUSTED_PROXY_HEADERS, fullauth.config.TRUSTED_PROXY_COUNT | |
| ) | |
| try: | |
| tokens = await refresh( | |
| fullauth.adapter, | |
| fullauth.token_engine, | |
| refresh_token, | |
| extra_claims_provider=fullauth.get_custom_claims, | |
| user_agent=user_agent, | |
| ip_address=ip_address, | |
| ) | |
| except (TokenError, AuthenticationError): | |
| raise CREDENTIALS_EXCEPTION | |
| return await write_tokens(response, fullauth, tokens) | |
| async def logout_route( | |
| request: Request, | |
| fullauth: "FullAuth" = Depends(get_fullauth), | |
| token: str = Depends(_extract_token), | |
| data: LogoutRequest | None = Body(None), | |
| ) -> Response: | |
| try: | |
| payload = await fullauth.token_engine.decode_token(token, expected_type="access") | |
| except TokenError: | |
| raise CREDENTIALS_EXCEPTION | |
| # A session token must not carry a purpose (password-reset / email-verify | |
| # tokens are access-typed but purpose-scoped); reject them as the session | |
| # dependencies do, so a purpose-scoped token can't be used to log out. | |
| if payload.extra.get("purpose"): | |
| raise CREDENTIALS_EXCEPTION | |
| refresh_token = await resolve_refresh_token( | |
| request, fullauth, data.refresh_token if data else None | |
| ) | |
| await logout( | |
| fullauth.token_engine, | |
| payload, | |
| adapter=fullauth.adapter, | |
| refresh_token=refresh_token, | |
| ) | |
| with contextlib.suppress(ValueError, ValidationError): | |
| await fullauth.hooks.emit( | |
| "after_logout", user_id=fullauth.adapter.parse_user_id(payload.sub) | |
| ) | |
| response = Response(status_code=204) | |
| for backend in fullauth.backends: | |
| await backend.delete_token(response) | |
| await backend.delete_refresh_token(response) | |
| return response | |
| return router | |
Xet Storage Details
- Size:
- 8.8 kB
- Xet hash:
- 6f0aebdc404b0cdb9a712ba9add4030b7a542d6623fc0e7a118645db59794300
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.