lback.auth package

This file serves as the initialization point for the ‘lback_framework/lback/auth’ package. It is designed to expose the core components necessary for handling various authentication and authorization mechanisms within the Lback web framework. This package centralizes the definition and management of security-related functionalities, including different authentication schemes, password management, and permission enforcement.

Key Components Exposed by this Package:

  1. SessionAuth (from .session_auth): Manages session-based authentication for users. This component is typically responsible for creating and managing user sessions, storing session data (e.g., user ID) on the server and providing a session ID to the client (often via cookies). It handles login, logout, and session validation to maintain user state across requests.

  2. PermissionRequired (from .permissions): A decorator or utility class used to enforce permissions on views or specific actions. This component ensures that only users with the necessary permissions are allowed to access certain resources or perform specific operations. It integrates with the authentication system to check a user’s assigned roles or permissions.

  3. PasswordHasher (from .password_hashing): Provides utilities for securely hashing and verifying user passwords. This component is critical for protecting sensitive user credentials by converting plain-text passwords into irreversible hash values before storage, and then securely comparing them during login attempts without exposing the original password. It typically supports various hashing algorithms.

  4. OAuth2Auth (from .oauth): Implements support for the OAuth 2.0 authorization framework. This component enables Lback applications to integrate with external identity providers (e.g., Google, Facebook) for user authentication and authorization, allowing users to grant limited access to their data without sharing their credentials directly with the application.

  5. JWTAuth (from .jwt_auth): Implements JSON Web Token (JWT) based authentication. This component handles the creation, signing, and validation of JWTs, which are commonly used for stateless authentication in APIs. It allows users to obtain a token upon successful login, which they then include in subsequent requests to prove their identity without needing to re-authenticate with each request.

  6. AdminAuth (from .adminauth): Specifically handles authentication logic for the administrative interface. This component might extend or specialize the general authentication mechanisms to cater to the unique requirements of admin users, potentially including stricter security policies or different login flows for administrative access.

Submodules

lback.auth.adminauth module

class lback.auth.adminauth.AdminAuth(admin_user_manager: AdminUserManager, session_manager: SessionManager)[source][source]

Bases: object

Handles authentication and authorization logic specifically for Admin Users. Acts as a bridge between AdminUserManager, SessionManager, and the Auth utilities. Integrates SignalDispatcher to emit events related to admin authentication and authorization.

__init__(admin_user_manager: AdminUserManager, session_manager: SessionManager)[source][source]

Initialize AdminAuth with necessary managers. Emits ‘admin_auth_initialized’ signal.

Parameters:
  • admin_user_manager (AdminUserManager) – Instance of AdminUserManager.

  • session_manager (SessionManager) – Instance of SessionManager for managing sessions.

is_admin_logged_in(request: Request) bool[source][source]

Checks if an admin user is currently logged in via session. Emits ‘admin_authentication_check’ signal, with outcome.

Parameters:

request – The incoming request object. Assumes request.session is a valid AppSession instance.

Returns:

True if a user ID is found in the session and is marked as admin, False otherwise.

login(request: Request, db_session: Session, username: str, password: str) Any | None[source][source]

Authenticates an admin user and logs them in using session authentication. Emits ‘admin_login_attempt’, ‘admin_login_successful’, or ‘admin_login_failed’ signals.

Parameters:
  • request – The incoming request object.

  • db_session – The database session.

  • username – The username for login.

  • password – The plain text password for login.

Returns:

The authenticated AdminUser object if successful, otherwise None.

logout(request: Request) bool[source][source]

Logs out the current admin user by ending their session. Emits ‘admin_logout_attempt’ and ‘admin_logout_successful’ signals.

Parameters:

request – The incoming request object. Assumes request.session is a valid AppSession instance.

Returns:

True if logout process was attempted (session object provided), False otherwise. Note: The actual session deletion is handled by AppSession.delete().

register(db_session: Session, username: str, email: str, password: str) bool[source][source]

Registers a new admin user. Emits ‘admin_registration_attempt’, ‘admin_registration_successful’, or ‘admin_registration_failed’ signals.

Parameters:
  • db_session – The database session.

  • username – The username for the new admin.

  • email – The email for the new admin.

  • password – The plain text password for the new admin.

Returns:

True if registration is successful, False otherwise.

lback.auth.jwt_auth module

class lback.auth.jwt_auth.JWTAuth(secret: str, algorithm: str = 'HS256', access_exp: int = 3600, refresh_exp: int = 86400)[source][source]

Bases: object

Utility class for creating, decoding, and validating JSON Web Tokens (JWT). Supports both access and refresh tokens. Integrates SignalDispatcher to emit events related to token lifecycle and validation.

__init__(secret: str, algorithm: str = 'HS256', access_exp: int = 3600, refresh_exp: int = 86400)[source][source]

Initializes the JWTAuth utility.

Parameters:
  • secret – The secret key used for signing and verifying tokens. Keep this secret and secure.

  • algorithm – The signing algorithm to use (default is HS256).

  • access_exp – Expiration time for access tokens in seconds (default is 1 hour).

  • refresh_exp – Expiration time for refresh tokens in seconds (default is 24 hours).

create_access_token(payload: Dict[str, Any]) str[source][source]

Creates a new access token. Emits ‘jwt_access_token_created’ signal on creation.

Parameters:

payload – A dictionary containing the data to encode in the token. Should NOT contain sensitive information like passwords. A ‘user_id’ or similar identifier is common.

Returns:

A signed JWT access token string.

create_refresh_token(payload: Dict[str, Any]) str[source][source]

Creates a new refresh token. Emits ‘jwt_refresh_token_created’ signal on creation.

Parameters:

payload – A dictionary containing the data to encode in the token. Should contain information needed to issue a new access token, like ‘user_id’.

Returns:

A signed JWT refresh token string.

decode_token(token: str) Dict[str, Any] | None[source][source]

Decodes a JWT token and verifies its signature and expiration. Emits ‘jwt_token_decoded’ on success. Emits ‘jwt_decode_failed’ on failure with specific error type.

Parameters:

token – The JWT token string to decode.

Returns:

A dictionary containing the decoded payload if valid, otherwise None.

get_payload(token: str) Dict[str, Any] | None[source][source]

Decodes a token and returns its payload if valid. Relies on decode_token for validation and signal emission.

Parameters:

token – The JWT token string.

Returns:

The decoded payload dictionary if the token is valid, otherwise None.

get_user_id(token: str) Any | None[source][source]

Decodes a token and returns the ‘user_id’ claim if the token is valid and the claim exists. Relies on decode_token for validation and signal emission.

Parameters:

token – The JWT token string.

Returns:

The value of the ‘user_id’ claim if found in a valid token, otherwise None.

is_token_valid(token: str, token_type: str | None = None) bool[source][source]

Checks if a JWT token is valid (signature and expiry) and optionally matches a specific type. This method primarily relies on decode_token, which emits failure signals. It adds a check for token type mismatch.

Parameters:
  • token – The JWT token string to validate.

  • token_type – Optional. The expected type of the token (‘access’ or ‘refresh’). If None, only checks signature and expiry.

Returns:

True if the token is valid and matches the type (if specified), False otherwise.

lback.auth.oauth module

class lback.auth.oauth.OAuth2Auth(client_id: str, client_secret: str, authorize_url: str, token_url: str, redirect_uri: str, scope: str = '')[source][source]

Bases: object

Utility class for interacting with an OAuth2 provider using the Authorization Code Grant flow. Provides methods for generating authorization URLs, fetching access tokens, and refreshing tokens. Integrates SignalDispatcher to emit events related to the OAuth2 flow.

__init__(client_id: str, client_secret: str, authorize_url: str, token_url: str, redirect_uri: str, scope: str = '')[source][source]

Initializes the OAuth2Auth utility.

Parameters:
  • client_id – The client ID obtained from the OAuth2 provider.

  • client_secret – The client secret obtained from the OAuth2 provider. Keep this secure.

  • authorize_url – The URL of the authorization endpoint of the OAuth2 provider.

  • token_url – The URL of the token endpoint of the OAuth2 provider.

  • redirect_uri – The redirect URI registered with the OAuth2 provider.

  • scope – The requested scope(s) (space-separated string). Defaults to “”.

fetch_token(code: str) Dict[str, Any] | None[source][source]

Exchanges an authorization code for an access token and optionally a refresh token. Emits ‘oauth2_token_fetched’ on success. Emits ‘oauth2_token_fetch_failed’ on failure.

Parameters:

code – The authorization code received from the OAuth2 provider.

Returns:

A dictionary containing the token response from the provider if successful, otherwise None. Expected keys often include ‘access_token’, ‘token_type’, ‘expires_in’, and optionally ‘refresh_token’.

get_authorize_url(state: str | None = None) str[source][source]

Generates the authorization URL to redirect the user to the OAuth2 provider. Emits ‘oauth2_authorize_url_generated’ signal.

Parameters:

state – An optional state parameter to maintain state between the request and the callback. Recommended for CSRF protection.

Returns:

The full authorization URL string.

refresh_token(refresh_token: str) Dict[str, Any] | None[source][source]

Exchanges a refresh token for a new access token and optionally a new refresh token. Emits ‘oauth2_token_refreshed’ on success. Emits ‘oauth2_token_refresh_failed’ on failure.

Parameters:

refresh_token – The refresh token obtained previously.

Returns:

A dictionary containing the new token response if successful, otherwise None. Expected keys often include ‘access_token’, ‘token_type’, ‘expires_in’, and optionally a new ‘refresh_token’.

lback.auth.password_hashing module

class lback.auth.password_hashing.PasswordHasher[source][source]

Bases: object

Utility class for securely hashing and verifying passwords using bcrypt. Bcrypt is a strong, adaptive hashing algorithm.

static generate_random_token(length: int = 32) str[source][source]

Generates a cryptographically strong, random string suitable for tokens (e.g., email verification).

Parameters:

length – The desired length of the token string.

Returns:

A random hexadecimal string of the specified length.

static hash_password(password: str) str[source][source]

Hashes a plain text password using bcrypt.

Parameters:

password – The plain text password string.

Returns:

A string containing the bcrypt hashed password.

Raises:

Exception – If hashing fails (e.g., due to encoding issues).

static verify_password(password: str, hashed: str) bool[source][source]

Verifies a plain text password against a bcrypt hashed password.

Parameters:
  • password – The plain text password string to verify.

  • hashed – The bcrypt hashed password string retrieved from storage.

Returns:

True if the password matches the hash, False otherwise.

Raises:

Exception – If verification fails (e.g., due to encoding issues or invalid hash format).

lback.auth.permissions module

class lback.auth.permissions.PermissionRequired(required_permissions: str | List[str] | Set[str] | Callable[[Request], str | List[str] | Set[str]])[source][source]

Bases: object

Decorates views to ensure the authenticated user has the necessary permissions. It checks for superuser status or individual permissions via the user’s has_permission method.

__call__(func: Callable) Callable[source][source]

The decorator logic. Wraps the view function to perform permission checks.

__init__(required_permissions: str | List[str] | Set[str] | Callable[[Request], str | List[str] | Set[str]])[source][source]

Initializes the decorator with the permission(s) needed.

has_permission(user: Any, required_permissions: Set[str]) bool[source][source]

Checks if the user possesses the required permissions. This method now directly uses the has_permission method from the user model.

lback.auth.session_auth module

class lback.auth.session_auth.SessionAuth(session_manager: SessionManager)[source][source]

Bases: object

Utility class for handling session-based authentication. Manages setting and getting user IDs and user types in the session data. Requires a SessionManager instance to interact with session storage.

__init__(session_manager: SessionManager)[source][source]

Initialize SessionAuth with a SessionManager instance. :param session_manager: The SessionManager instance. :type session_manager: SessionManager

get_current_user_id(request: Request) int | str | UUID | None[source][source]

Retrieves the authenticated user’s ID from the session data, ONLY if the session is active. :param request: The Request object, expected to have a ‘session’ attribute (AppSession instance).

Returns:

The user ID if authenticated and session is active, otherwise None.

is_authenticated(request: Request) bool[source][source]

Checks if a user is authenticated based on session data. :param request: The Request object, expected to have a ‘session’ attribute (AppSession instance).

Returns:

True if a user ID is found in the session data AND the session is active, False otherwise.

login(request: Request, user_id: int | str | UUID, user_type: str = 'user') bool[source][source]

Logs a user in by setting their ID and type in the session data. Assumes SessionMiddleware has run and populated request.session. :param request: The Request object, expected to have a ‘session’ attribute (AppSession instance). :param user_id: The ID of the user to log in. :param user_type: The type of the user (‘user’ or ‘admin’).

Returns:

True if the user ID was successfully set in an active session, False otherwise.

logout(request: Request) bool[source][source]

Logs out the current user by deleting their session. :param request: The Request object, expected to have a ‘session’ attribute (AppSession instance).

Returns:

True if a session object was available to attempt deletion, False otherwise.