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:
- Token Extraction: Extracts the Bearer token via
OAuth2PasswordBearer(tokenUrl="token", auto_error=False). - Token & Claims Verification: If no token is provided and
auto_error=False, it exits early returningNone. Otherwise, decodes the token usingSecurity.decode_jwt(), validating the signature, expiration, and assertingtype == token_type. - Cache-Aside Check: Checks
BaseCache(prefix="auth")for keyuser:{identity}. If a cache hit occurs, it deserializes directly intouser_schema. - Database Resolution: If a cache miss occurs, invokes
await self.fetch_user(identity), assertsis_active == True, validates withuser_schema.model_validate(db_user), and populates the cache using the resolvedcache_ttl(settings.AUTH_CACHE_TTL). - Dynamic Context Population:
user.id$\rightarrow$ctx.user_iduser.all_restricted_fields$\rightarrow$ctx.restricted_fields(as an immutablefrozenset)- All remaining fields (e.g.,
scopes,roles,email) $\rightarrow$ctx.set(field_name, value)