ZCore LogoZCore
Api reference

BaseAuth

API reference for the generic BaseAuth authentication template, dynamic cache TTL, and context binding pipeline.

BaseAuth is a generic Template-Method authentication dependency. It coordinates JWT decoding, automatic user session caching, active-state assertions, and dynamically binds schema attributes directly onto the shared ZContext.

Class Definition

from typing import Generic, TypeVar, Any
from pydantic import BaseModel
from zcore import BaseAuth

T = TypeVar("T", bound=BaseModel)

class BaseAuth(Generic[T]):
    def __init__(
        self,
        user_schema: type[T],
        identity_claim: str = "sub",
        token_type: str = "access",
        cache_prefix: str = "auth",
        cache_ttl: int | None = None,
        auto_error: bool = True
    ) -> None:
        ...

Initialization Parameters

Prop

Type


Methods

fetch_user

Fetches the active user record from persistent storage. This is the Template Method hook that must be implemented by concrete subclass implementations in your application layer.

async def fetch_user(self, identity: str) -> Any: ...

Prop

Type

__call__

Executes the core request interception authentication workflow. Functions as a callable FastAPI dependency (Depends(auth_instance)).

async def __call__(
    self, 
    request: Request, 
    token: str | None = Depends(oauth2_scheme)
) -> T | None: ...

Prop

Type


Execution Flow & Context Binding

The BaseAuth Pipeline:

  1. Token Extraction: Extracts the Bearer token via OAuth2PasswordBearer(tokenUrl="token", auto_error=False).
  2. Token & Claims Verification: If no token is provided and auto_error=False, it exits early returning None. Otherwise, decodes the token using Security.decode_jwt(), validating the signature, expiration, and asserting type == token_type.
  3. Cache-Aside Check: Checks BaseCache(prefix="auth") for key user:{identity}. If a cache hit occurs, it deserializes directly into user_schema.
  4. Database Resolution: If a cache miss occurs, invokes await self.fetch_user(identity), asserts is_active == True, validates with user_schema.model_validate(db_user), and populates the cache using the resolved cache_ttl (settings.AUTH_CACHE_TTL).
  5. Dynamic Context Population:
    • user.id $\rightarrow$ ctx.user_id
    • user.all_restricted_fields $\rightarrow$ ctx.restricted_fields (as an immutable frozenset)
    • All remaining fields (e.g., scopes, roles, email) $\rightarrow$ ctx.set(field_name, value)

On this page