Comprehensive type stubs for Django framework enabling static type checking with mypy
—
Django's authentication system provides user management, permissions, groups, and session-based authentication with customizable backends and password validation.
Core functions for user authentication and session management.
def authenticate(request: HttpRequest = None, **credentials) -> Optional[User]:
"""
Verify user credentials against authentication backends.
Args:
request: HTTP request object (optional)
**credentials: Authentication credentials (username, password, etc.)
Returns:
Authenticated user object or None if authentication fails
"""
def login(request: HttpRequest, user: AbstractBaseUser, backend: str = None) -> None:
"""
Log user into current session.
Args:
request: HTTP request object
user: User object to authenticate
backend: Authentication backend used (optional)
"""
def logout(request: HttpRequest) -> None:
"""
Log user out of current session.
Args:
request: HTTP request object
"""
def get_user_model() -> Type[AbstractBaseUser]:
"""
Get the active user model for the current Django project.
Returns:
User model class
"""
def get_user(request: HttpRequest) -> Union[AbstractBaseUser, AnonymousUser]:
"""
Get user from request session.
Args:
request: HTTP request object
Returns:
User object or AnonymousUser if not authenticated
"""
def update_session_auth_hash(request: HttpRequest, user: AbstractBaseUser) -> None:
"""
Update session authentication hash after password change.
Args:
request: HTTP request object
user: User with updated password
"""User model classes and authentication interfaces.
class AbstractBaseUser(models.Model):
"""
Base user model providing core authentication functionality.
Abstract base class with password management and authentication interface.
"""
password: models.CharField
last_login: models.DateTimeField
is_active: bool = True
USERNAME_FIELD: str = 'username'
EMAIL_FIELD: str = 'email'
REQUIRED_FIELDS: list = []
def set_password(self, raw_password: str) -> None: ...
def check_password(self, raw_password: str) -> bool: ...
def set_unusable_password(self) -> None: ...
def has_usable_password(self) -> bool: ...
def get_session_auth_hash(self) -> str: ...
def get_username(self) -> str: ...
def clean(self) -> None: ...
def natural_key(self) -> tuple: ...
def is_anonymous(self) -> bool: ...
def is_authenticated(self) -> bool: ...
def get_full_name(self) -> str: ...
def get_short_name(self) -> str: ...
class AbstractUser(AbstractBaseUser, PermissionsMixin):
"""
Complete user model with username and permission support.
Full-featured user model with built-in fields and permission system.
"""
username: models.CharField
first_name: models.CharField
last_name: models.CharField
email: models.EmailField
is_staff: models.BooleanField
is_active: models.BooleanField
date_joined: models.DateTimeField
objects: BaseUserManager
USERNAME_FIELD: str = 'username'
EMAIL_FIELD: str = 'email'
REQUIRED_FIELDS: list = ['email']
def clean(self) -> None: ...
def get_full_name(self) -> str: ...
def get_short_name(self) -> str: ...
def email_user(self, subject: str, message: str, from_email: str = None, **kwargs) -> None: ...
class User(AbstractUser):
"""
Default Django user model.
Ready-to-use user model with all standard fields and functionality.
"""
class AnonymousUser:
"""
User object representing unauthenticated visitors.
Provides consistent interface for anonymous users.
"""
id: None = None
pk: None = None
username: str = ''
is_staff: bool = False
is_active: bool = False
is_superuser: bool = False
def __str__(self) -> str: ...
def __eq__(self, other) -> bool: ...
def __hash__(self) -> int: ...
def save(self) -> None: ...
def delete(self) -> None: ...
def set_password(self, raw_password: str) -> None: ...
def check_password(self, raw_password: str) -> bool: ...
def is_anonymous(self) -> bool: ...
def is_authenticated(self) -> bool: ...
def get_username(self) -> str: ...
def get_user_permissions(self, obj=None) -> set: ...
def get_all_permissions(self, obj=None) -> set: ...
def get_group_permissions(self, obj=None) -> set: ...
def has_perm(self, perm: str, obj=None) -> bool: ...
def has_perms(self, perm_list: list, obj=None) -> bool: ...
def has_module_perms(self, module: str) -> bool: ...Manager classes for user model database operations.
class BaseUserManager(models.Manager):
"""
Base manager for user models with authentication support.
Provides user creation methods and authentication utilities.
"""
def make_random_password(self, length: int = 10, allowed_chars: str = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789') -> str: ...
def get_by_natural_key(self, username: str): ...
def create_user(self, username: str, email: str = None, password: str = None, **extra_fields): ...
def create_superuser(self, username: str, email: str = None, password: str = None, **extra_fields): ...
def with_perm(self, perm: str, is_active: bool = True, include_superusers: bool = True, backend: str = None, obj=None): ...
class UserManager(BaseUserManager):
"""
Manager for Django's built-in User model.
Extends BaseUserManager with email-based user creation.
"""
def _create_user(self, username: str, email: str, password: str, **extra_fields): ...
def create_user(self, username: str, email: str = '', password: str = None, **extra_fields): ...
def create_superuser(self, username: str, email: str = None, password: str = None, **extra_fields): ...Classes and functions for managing user permissions and authorization.
class Permission(models.Model):
"""
Individual permission that can be granted to users or groups.
Represents a specific permission with content type and codename.
"""
name: models.CharField
content_type: models.ForeignKey
codename: models.CharField
objects: models.Manager
def __str__(self) -> str: ...
def natural_key(self) -> tuple: ...
class Group(models.Model):
"""
User group for organizing permissions.
Groups allow batch permission assignment to multiple users.
"""
name: models.CharField
permissions: models.ManyToManyField
objects: models.Manager
def __str__(self) -> str: ...
def natural_key(self) -> tuple: ...
class PermissionsMixin(models.Model):
"""
Mixin adding permission functionality to user models.
Provides permission checking and group membership methods.
"""
is_superuser: models.BooleanField
groups: models.ManyToManyField
user_permissions: models.ManyToManyField
def get_user_permissions(self, obj=None) -> set: ...
def get_group_permissions(self, obj=None) -> set: ...
def get_all_permissions(self, obj=None) -> set: ...
def has_perm(self, perm: str, obj=None) -> bool: ...
def has_perms(self, perm_list: list, obj=None) -> bool: ...
def has_module_perms(self, app_label: str) -> bool: ...
def get_permission_codename(action: str, opts) -> str:
"""
Generate permission codename for model action.
Args:
action: Permission action (add, change, delete, view)
opts: Model meta options
Returns:
Permission codename string
"""Backend classes for customizing authentication logic.
class BaseBackend:
"""
Base authentication backend interface.
Abstract base class for implementing custom authentication.
"""
def authenticate(self, request: HttpRequest, **credentials): ...
def get_user(self, user_id: int): ...
def get_user_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
def get_group_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
def get_all_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
def has_perm(self, user_obj: AbstractBaseUser, perm: str, obj=None) -> bool: ...
def has_module_perms(self, user_obj: AbstractBaseUser, app_label: str) -> bool: ...
def with_perm(self, perm: str, is_active: bool = True, include_superusers: bool = True, obj=None): ...
class ModelBackend(BaseBackend):
"""
Default Django authentication backend.
Authenticates against Django user model with username/password.
"""
def authenticate(self, request: HttpRequest, username: str = None, password: str = None, **kwargs): ...
def user_can_authenticate(self, user: AbstractBaseUser) -> bool: ...
def _get_user_permissions(self, user_obj: AbstractBaseUser) -> set: ...
def _get_group_permissions(self, user_obj: AbstractBaseUser) -> set: ...
def _get_permissions(self, user_obj: AbstractBaseUser, obj, from_name: str) -> set: ...
def get_user_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
def get_group_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
def get_all_permissions(self, user_obj: AbstractBaseUser, obj=None) -> set: ...
def has_perm(self, user_obj: AbstractBaseUser, perm: str, obj=None) -> bool: ...
def has_module_perms(self, user_obj: AbstractBaseUser, app_label: str) -> bool: ...
def with_perm(self, perm: str, is_active: bool = True, include_superusers: bool = True, obj=None): ...
def get_user(self, user_id: int): ...
class AllowAllUsersModelBackend(ModelBackend):
"""
Authentication backend allowing inactive users.
Similar to ModelBackend but doesn't check is_active flag.
"""
def user_can_authenticate(self, user: AbstractBaseUser) -> bool: ...
class RemoteUserBackend(ModelBackend):
"""
Backend for remote user authentication (e.g., web server auth).
Authenticates users based on REMOTE_USER header.
"""
create_unknown_user: bool = True
def authenticate(self, request: HttpRequest, remote_user: str): ...
def clean_username(self, username: str) -> str: ...
def configure_user(self, request: HttpRequest, user: AbstractBaseUser, created: bool = True): ...
def user_can_authenticate(self, user: AbstractBaseUser) -> bool: ...
def get_backends() -> list:
"""
Get list of configured authentication backends.
Returns:
List of authentication backend instances
"""
def load_backend(path: str) -> BaseBackend:
"""
Load authentication backend by dotted path.
Args:
path: Dotted path to backend class
Returns:
Backend instance
"""Password strength validation and policy enforcement.
def validate_password(password: str, user: AbstractBaseUser = None, password_validators: list = None) -> None:
"""
Validate password against configured validators.
Args:
password: Password to validate
user: User object for context (optional)
password_validators: List of validator instances (optional)
Raises:
ValidationError: If password validation fails
"""
def password_changed(password: str, user: AbstractBaseUser = None, password_validators: list = None) -> None:
"""
Inform validators that password has been changed.
Args:
password: New password
user: User object (optional)
password_validators: List of validator instances (optional)
"""
def password_validators_help_texts(password_validators: list = None) -> list:
"""
Get help texts from password validators.
Args:
password_validators: List of validator instances (optional)
Returns:
List of help text strings
"""
def password_validators_help_text_html(password_validators: list = None) -> str:
"""
Get HTML formatted help text from password validators.
Args:
password_validators: List of validator instances (optional)
Returns:
HTML formatted help text
"""
class CommonPasswordValidator:
"""
Password validator that rejects common passwords.
Validates against list of common passwords from database.
"""
DEFAULT_PASSWORD_LIST_PATH: str
def __init__(self, password_list_path: str = None): ...
def validate(self, password: str, user: AbstractBaseUser = None) -> None: ...
def get_help_text(self) -> str: ...
class MinimumLengthValidator:
"""
Password validator enforcing minimum length requirement.
"""
def __init__(self, min_length: int = 8): ...
def validate(self, password: str, user: AbstractBaseUser = None) -> None: ...
def get_help_text(self) -> str: ...
class AttributeSimilarityValidator:
"""
Password validator preventing passwords similar to user attributes.
"""
DEFAULT_USER_ATTRIBUTES: tuple = ('username', 'first_name', 'last_name', 'email')
def __init__(self, user_attributes: tuple = None, max_similarity: float = 0.7): ...
def validate(self, password: str, user: AbstractBaseUser = None) -> None: ...
def get_help_text(self) -> str: ...
class NumericPasswordValidator:
"""
Password validator rejecting entirely numeric passwords.
"""
def validate(self, password: str, user: AbstractBaseUser = None) -> None: ...
def get_help_text(self) -> str: ...Classes for password hashing and verification.
class BasePasswordHasher:
"""
Base password hasher interface.
Abstract base class for implementing password hashing algorithms.
"""
algorithm: str = None
library: str = None
def encode(self, password: str, salt: str) -> str: ...
def verify(self, password: str, encoded: str) -> bool: ...
def safe_summary(self, encoded: str) -> dict: ...
def harden_runtime(self, password: str, encoded: str) -> None: ...
def must_update(self, encoded: str) -> bool: ...
def check_password(password: str, encoded: str, setter=None, preferred: str = 'default') -> bool:
"""
Check password against encoded hash.
Args:
password: Raw password to check
encoded: Encoded password hash
setter: Function to update hash if needed
preferred: Preferred hasher algorithm
Returns:
True if password matches hash
"""
def make_password(password: str, salt: str = None, hasher: str = 'default') -> str:
"""
Hash password with salt using specified algorithm.
Args:
password: Raw password to hash
salt: Salt for hashing (generated if None)
hasher: Hasher algorithm name
Returns:
Encoded password hash
"""
def is_password_usable(encoded: str) -> bool:
"""
Check if password hash is usable for authentication.
Args:
encoded: Password hash
Returns:
True if hash is usable
"""
def identify_hasher(encoded: str) -> BasePasswordHasher:
"""
Identify hasher used for encoded password.
Args:
encoded: Password hash
Returns:
Hasher instance for the algorithm
"""Decorators for protecting views with authentication requirements.
def login_required(function=None, redirect_field_name: str = 'next', login_url: str = None):
"""
Decorator requiring user authentication for view access.
Args:
function: View function to protect
redirect_field_name: URL parameter for redirect after login
login_url: Login page URL
Returns:
Decorated view function
"""
def permission_required(perm: str, login_url: str = None, raise_exception: bool = False):
"""
Decorator requiring specific permission for view access.
Args:
perm: Required permission string
login_url: Login page URL
raise_exception: Raise PermissionDenied instead of redirect
Returns:
Decorator function
"""
def user_passes_test(test_func, login_url: str = None, redirect_field_name: str = 'next'):
"""
Decorator requiring user to pass custom test function.
Args:
test_func: Function taking user and returning boolean
login_url: Login page URL
redirect_field_name: URL parameter for redirect after login
Returns:
Decorator function
"""Session constants and utilities for authentication state management.
SESSION_KEY: str = '_auth_user_id' # Session key for user ID
BACKEND_SESSION_KEY: str = '_auth_user_backend' # Session key for auth backend
HASH_SESSION_KEY: str = '_auth_user_hash' # Session key for password hash
REDIRECT_FIELD_NAME: str = 'next' # Default redirect field name
def get_user_model() -> Type[AbstractBaseUser]:
"""
Get the active user model class.
Returns:
User model class from AUTH_USER_MODEL setting
"""Signals for authentication events and user lifecycle.
user_logged_in: Signal = ...
"""
Signal sent when user logs in successfully.
Args:
sender: User model class
request: HttpRequest object
user: User instance that logged in
"""
user_login_failed: Signal = ...
"""
Signal sent when user login fails.
Args:
sender: None or User model class
credentials: Failed login credentials
request: HttpRequest object
"""
user_logged_out: Signal = ...
"""
Signal sent when user logs out.
Args:
sender: User model class
request: HttpRequest object
user: User instance that logged out
"""Context processors adding authentication data to templates.
def auth(request: HttpRequest) -> dict:
"""
Add authentication context to templates.
Args:
request: HTTP request object
Returns:
Dictionary with user and perms keys
"""Middleware for handling user authentication in requests.
class AuthenticationMiddleware:
"""
Middleware that adds user attribute to requests.
Associates user with request based on session authentication.
"""
def __init__(self, get_response): ...
def __call__(self, request: HttpRequest) -> HttpResponse: ...
class RemoteUserMiddleware:
"""
Middleware for remote user authentication.
Authenticates users based on REMOTE_USER header from web server.
"""
header: str = 'REMOTE_USER'
force_logout_if_no_header: bool = True
def __init__(self, get_response): ...
def __call__(self, request: HttpRequest) -> HttpResponse: ...
def process_request(self, request: HttpRequest) -> None: ...
def clean_username(self, username: str, request: HttpRequest) -> str: ...
class PersistentRemoteUserMiddleware(RemoteUserMiddleware):
"""
Remote user middleware that doesn't force logout.
Allows users to remain logged in without REMOTE_USER header.
"""
force_logout_if_no_header: bool = FalseInstall with Tessl CLI
npx tessl i tessl/pypi-django-stubs