Models
jwtlib.models
jwtlib Models: Structured Data for Authentication
This package defines the core data models used by jwtlib. These models are
categorized into request payloads, response objects, persistence documents,
and security context.
Model Categories
1. API Requests
- RegisterRequest: Payload for creating new user accounts.
- LoginRequest: User credentials for issuing JWTs.
- IntrospectRequest: Internal payload for service-to-service token verification.
2. API Responses
- PublicUser: A safe, non-sensitive projection of a user profile.
- LoginResponse: Contains the issued
access_tokenand thePublicUser. - LogoutResponse: Instruction for clients to clear stateless session state.
3. Internal & Security
- User: The MongoDB-backed persistence model (Confined to repository layer).
- TokenPayload: Decoded claims from a validated JWT (sub, exp).
- IntrospectResponse: Structured result of a token validity check.
Usage Patterns
Validating an Auth Request
from jwtlib.models import LoginRequest
from pydantic import ValidationError
try:
auth_data = LoginRequest(username="tester", password="secure_password")
except ValidationError as e:
print(f"Invalid request data: {e.json()}")
Projecting a User to Public View
from jwtlib.models import User, PublicUser
# Assuming 'db_user' is an instance of User fetched from MongoDB
user_profile = PublicUser.model_validate(db_user, from_attributes=True)
print(f"Safe to return: {user_profile.username} ({user_profile.email})")
All models are built on Pydantic v2 and provide full type safety for both static analysis (Mypy/Pyright) and runtime validation.
IntrospectRequest
Bases: BaseModel
Payload for requesting token introspection.
Used by internal services to verify the validity of a JWT and retrieve the associated public user information.
Fields
token: JWT access token to introspect.
Notes
- Intended for service-to-service communication.
- Not meant for direct end-user consumption.
IntrospectResponse
Bases: BaseModel
Result of a token introspection operation.
This model communicates whether a JWT is valid and, if so, provides the associated public user information.
Fields
active: Indicates whether the token is valid and active. user: Public user details if the token is valid; otherwise null.
Notes
- This model is designed to avoid raising exceptions.
- All introspection outcomes are represented as data.
LoginRequest
Bases: IdentityMixin, PasswordMixin
Payload for authenticating a user and issuing a JWT.
This model is used to verify user credentials and request an access token.
Fields
username: Username identifier. password: Plain-text password to be verified.
Notes
- Successful authentication results in a LoginResponse.
- Failed authentication raises an AuthError.
LoginResponse
Bases: BaseModel
Response returned after successful authentication.
Contains the issued JWT access token and the authenticated user's public profile.
Fields
access_token: JWT access token for authenticated requests. user: Public profile of the authenticated user.
Notes
- The token is stateless and must be stored client-side.
- Token expiration and validation are handled elsewhere.
LogoutResponse
Bases: BaseModel
Response returned after a logout operation.
Since logout is stateless, this response serves only as a confirmation message instructing the client to discard its token.
Fields
message: Human-readable logout confirmation.
PublicUser
Bases: IdentityMixin, ActiveStateMixin
Public-facing user representation returned by authentication APIs.
This model represents a user profile that is safe to expose outside the authentication system.
Fields
username: Unique username identifier. email: User's email address. is_active: Whether the user account is active.
Notes
- Contains no sensitive data.
- Can be constructed from persistence models via
from_attributes.
RegisterRequest
Bases: IdentityMixin, PasswordMixin
Payload for registering a new user account.
This model contains the minimum required identity and credential information to create a new user.
Fields
username: Unique username identifier. email: User's email address. password: Plain-text password (to be hashed by the repository layer).
Notes
- Validation and normalization handled by mixins.
- This model is never returned in responses.
TokenPayload
Bases: BaseModel
Decoded JWT payload.
Represents the validated claims extracted from a JWT after signature verification. This model is used internally to enforce required claims and provide a typed interface to token data.
Fields
sub: Subject claim identifying the user (typically a username or user ID). exp: Expiration time as a Unix timestamp (seconds since epoch).
Notes
- This model assumes the JWT signature has already been verified.
- No authorization decisions should be made solely on this model.
- Additional claims may exist but are intentionally ignored.
User
Bases: BaseDocument, IdentityMixin, ActiveStateMixin
Internal user persistence model.
Represents a user record as stored in the database. This model includes sensitive fields and is strictly confined to the persistence layer.
Fields
hashed_password: Secure hash of the user's password.
Notes
- This model MUST NOT be returned from authentication APIs.
- Consumers should use
PublicUserinstead. - Password verification is handled by the repository layer.
- Inherits identity and active-state behavior via mixins.