JWT Allauth modules

Modules

Submodules

jwt_allauth.adapter module

class jwt_allauth.adapter.JWTAllAuthAdapter(request=None)[source]

Bases: DefaultAccountAdapter

Custom account adapter extending allauth’s DefaultAccountAdapter with JWT-specific email handling.

Provides enhanced email confirmation functionality with template path customization and JWT-related email content handling.

Key Features:

  • Email normalization (trimming and lowercasing)

  • Customizable template paths for verification emails

  • Dual template support (HTML/text) with fallback handling

  • Integration with JWT verification workflows

clean_email(email)[source]

Normalize email addresses by trimming whitespace and converting to lowercase.

Parameters:

email (str) – Raw email input

Returns:

Normalized email address

Return type:

str

render_mail(template_prefix, email, context, headers=None, subject_path=None, template_path=None)[source]

Render email message with support for multiple template formats and custom paths.

Behavior:

  • Generates multipart emails when both HTML and text templates exist

  • Uses custom template paths when provided

  • Automatically formats email subject

  • Supports HTML email content as primary when specified

Parameters:
  • template_prefix (str) – Base template path prefix

  • email (str|list) – Recipient email address(es)

  • context (dict) – Template context variables

  • headers (dict, optional) – Custom email headers

  • subject_path (str, optional) – Override path for subject template

  • template_path (str, optional) – Override path for body template

Returns:

Configured email message object

Return type:

EmailMessage

Raises:

TemplateDoesNotExist – If no valid template can be found

send_confirmation_mail(request, emailconfirmation, signup)[source]

Generate and send email confirmation message with context customization.

Context Includes:

  • User object

  • Verification code or URL (based on EMAIL_VERIFICATION_BY_CODE_ENABLED)

  • Site-specific information

Parameters:
  • request (HttpRequest) – Current request object

  • emailconfirmation (EmailConfirmation) – Email confirmation instance

  • signup (bool) – Flag indicating if this is a signup confirmation

Returns:

Confirmation key used in the email

Return type:

str

send_mail(template_prefix, email, context, subject_path=None, template_path=None)[source]

Construct and send email using template configuration.

Enhances Context With:

  • Current site information

  • Recipient email address

Parameters:
  • template_prefix (str) – Base path for template lookup

  • email (str|list) – Recipient email address(es)

  • context (dict) – Template context variables

  • subject_path (str, optional) – Custom path for subject template

  • template_path (str, optional) – Custom path for body template

jwt_allauth.exceptions module

exception jwt_allauth.exceptions.IncorrectCredentials(detail: dict[str, Any] | str | None = None, code: str | None = None)[source]

Bases: AuthenticationFailed

default_code: str = 'incorrect_credentials'
default_detail: str = 'Incorrect credentials'
status_code = 401
exception jwt_allauth.exceptions.NotVerifiedEmail(detail: dict[str, Any] | str | None = None, code: str | None = None)[source]

Bases: AuthenticationFailed

default_code: str = 'email_not_verified'
default_detail: str = 'User email is not verified'
status_code = 401

jwt_allauth.utils module

jwt_allauth.utils.allauth_authenticate(**kwargs)[source]

Authenticate user using allauth’s adapter with enhanced verification.

Parameters:

**kwargs – Authentication credentials (typically username/email + password)

Returns:

Authenticated user object

Return type:

User

Raises:
jwt_allauth.utils.get_client_ip(request)[source]

Extract client IP address from request metadata.

Priority:

  1. X-Forwarded-For header (first entry if multiple)

  2. REMOTE_ADDR meta value

Parameters:

request (HttpRequest) – Django request object

Returns:

Client IP address or None if not found

Return type:

str

jwt_allauth.utils.get_template_path(constant, default)[source]

Get template path from settings using TEMPLATE_PATHS configuration.

Parameters:
  • constant (str) – Key to look up in TEMPLATE_PATHS setting

  • default (str) – Default path if not found in settings

Returns:

Configured template path or default value

Return type:

str

jwt_allauth.utils.get_user_agent(f)[source]

Decorator that adds user agent and IP information to the request object.

Stores: - user_agent: Parsed user agent details - ip: Client IP address

Parameters:

f (function) – View method to decorate

Returns:

Decorated view method

Return type:

function

jwt_allauth.utils.import_callable(path_or_callable)[source]

Convert a Python path string to a callable object or return the input if already callable.

Parameters:

path_or_callable (str|callable) – Either a Python path string (module.attribute) or an already callable object

Returns:

The resolved callable object

Return type:

callable

Raises:

AssertionError – If input is string but not valid Python path

jwt_allauth.utils.is_email_verified(user, raise_exception=False)[source]

Check if user has a verified email address.

Parameters:
  • user (User) – User object to check

  • raise_exception (bool) – Whether to raise NotVerifiedEmail if unverified

Returns:

True if verified, False otherwise

Return type:

bool

Raises:

NotVerifiedEmail – If raise_exception=True and email is unverified

jwt_allauth.utils.load_user(f)[source]

Decorator that loads the complete user object from the database for stateless JWT authentication. This is necessary because JWT tokens only contain the user ID, and the full user object might be needed in the view methods.

Usage:

@load_user
def my_view_method(self, *args, **kwargs):
    # self.request.user will be the complete user object
    pass
jwt_allauth.utils.user_agent_dict(request)[source]

Generate a detailed dictionary of user agent information.

Includes:

  • Browser details (name, version)

  • OS details (name, version)

  • Device information (family, brand, model)

  • Network information (IP address)

  • Device type flags (mobile, tablet, PC, bot)

Parameters:

request (HttpRequest) – Django request object

Returns:

Structured user agent details. Empty dict if no request.

Return type:

dict

jwt_allauth.test module

class jwt_allauth.test.JAClient(token, staff_token, *args, **kwargs)[source]

Bases: Client

A custom Django test client for handling JWT authenticated requests.

Provides enhanced HTTP methods to automatically include JWT tokens in requests. Supports both regular user and staff user authentication through separate tokens.

All standard HTTP methods (post, get, patch, put, delete) are extended with:

  • Regular auth versions (auth_* methods) using default user token

  • Staff auth versions (staff_* methods) using staff user token

  • Optional direct token injection via access_token parameter

auth_delete(*args, **kwargs)[source]
auth_get(*args, **kwargs)[source]
auth_patch(*args, **kwargs)[source]
auth_post(*args, **kwargs)[source]
auth_put(*args, **kwargs)[source]
content_type = 'application/json'
delete(*args, access_token=None, **kwargs)[source]

Send a DELETE request to the server.

get(*args, access_token=None, **kwargs)[source]

Request a response from the server using GET.

patch(*args, access_token=None, **kwargs)[source]

Send a resource to the server using PATCH.

post(*args, access_token=None, **kwargs)[source]

Request a response from the server using POST.

put(*args, access_token=None, **kwargs)[source]

Send a resource to the server using PUT.

staff_delete(*args, **kwargs)[source]
staff_get(*args, **kwargs)[source]
staff_patch(*args, **kwargs)[source]
staff_post(*args, **kwargs)[source]
staff_put(*args, **kwargs)[source]
update_kwargs(access_token=None, default_auth=False, staff_auth=False, **kwargs)[source]
class jwt_allauth.test.JATestCase(methodName='runTest')[source]

Bases: TestCase

Base test case for JWT-authenticated endpoint testing.

Provides pre-configured user accounts and JWT tokens for testing:

  • Regular user with verified email

  • Staff user with verified email

  • Ready-to-use test client with authentication support

EMAIL = 'test@mail.com'
FIRST_NAME = 'name'
LAST_NAME = 'surname'
LOGIN_PAYLOAD = {'email': 'test@mail.com', 'password': 'Test-Passw0rd'}
PASS = 'Test-Passw0rd'
STAFF_EMAIL = 'test@staff.com'
STAFF_FIRST_NAME = 'staffname'
STAFF_LAST_NAME = 'staffsurname'
STAFF_PASS = 'Staff-Passw0rd'
STAFF_USER = None
USER = None
authenticate(user)[source]
property ja_client

Pre-configured test client with authentication tokens.

setUp()[source]

Configures test environment with regular and staff users, including:

  • User account creation

  • Email verification setup

  • JWT token generation

jwt_allauth.permissions module

class jwt_allauth.permissions.BasePermission[source]

Bases: BasePermission

Custom base permission class for role-based access control using JWT claims.

Extends DRF’s BasePermission to check for roles in the JWT payload. Automatically grants access to staff and superusers in addition to specified roles.

Behavior:

  • Checks JWT payload for ‘role’ claim

  • Allows access if role is in accepted_roles, STAFF_CODE, or SUPER_USER_CODE

  • Requires request.auth to contain decoded JWT payload

  • Staff and superusers (STAFF_CODE/SUPER_USER_CODE) always have access

Class Attributes:
accepted_roles (list): Required list of role codes that are allowed access.

Must be initialized in subclasses.

Raises:

ValueError – If accepted_roles is not properly initialized as a list

accepted_roles = None
has_permission(request, view)[source]

Determine if the request should be permitted based on JWT roles.

Parameters:
  • request (Request) – DRF request object containing JWT in auth attribute

  • view (View) – DRF view being accessed

Returns:

True if authorized, False otherwise

Return type:

bool

class jwt_allauth.permissions.BasePermissionStaffExcluded[source]

Bases: BasePermission

Custom base permission class for role-based access control using JWT claims.

Extends DRF’s BasePermission to check for roles in the JWT payload.

Behavior:

  • Checks JWT payload for ‘role’ claim

  • Allows access if role is in accepted_roles, STAFF_CODE, or SUPER_USER_CODE

  • Requires request.auth to contain decoded JWT payload

Class Attributes:
accepted_roles (list): Required list of role codes that are allowed access.

Must be initialized in subclasses.

Raises:

ValueError – If accepted_roles is not properly initialized as a list

accepted_roles = None
has_permission(request, view)[source]

Determine if the request should be permitted based on JWT roles.

Parameters:
  • request (Request) – DRF request object containing JWT in auth attribute

  • view (View) – DRF view being accessed

Returns:

True if authorized, False otherwise

Return type:

bool

Raises:

ValueError – If accepted_roles is not a list

jwt_allauth.apps module

class jwt_allauth.apps.JWTAllauthAppConfig(app_name, app_module)[source]

Bases: AppConfig

default_auto_field = 'django.db.models.BigAutoField'
name = 'jwt_allauth'
ready()[source]

Override this method in subclasses to run code when Django starts.

verbose_name = 'JWT Allauth'