lback.middlewares package
This file serves as the initialization point for the ‘lback_framework/lback/middlewares’ package. It is designed to expose the core components necessary for implementing various middleware functionalities within the Lback web framework. This package centralizes the definition and management of middleware that process requests and responses globally or for specific routes, enhancing application behavior for concerns like authentication, security, logging, and session management.
—
Key Components Exposed by this Package:
AuthMiddleware (from .auth_midlewares): A middleware component responsible for handling authentication processes. This middleware intercepts incoming requests to verify user credentials or session tokens, ensuring that only authenticated users can access protected resources. It integrates with the framework’s authentication system.
BodyParsingMiddleware (from .body_parsing_middleware): A middleware component designed to parse the body of incoming HTTP requests. This is crucial for handling different content types (e.g., JSON, form data, multipart/form-data for file uploads) and making the parsed data easily accessible to view functions.
CORSMiddleware (from .cors): A middleware component that implements Cross-Origin Resource Sharing (CORS) policies. This middleware adds appropriate HTTP headers to responses, allowing web browsers to permit cross-origin requests to the Lback application, which is essential for single-page applications (SPAs) or APIs consumed from different domains.
CSRFMiddleware (from .csrf): A middleware component that provides Cross-Site Request Forgery (CSRF) protection. This middleware helps prevent malicious attacks where unauthorized commands are transmitted from a user that the web application trusts. It typically involves generating and validating CSRF tokens.
DebugMiddleware (from .debug): A middleware component that provides debugging functionalities, typically active only in development environments. This might include displaying detailed error messages, logging request/response information, or providing tools for inspecting application state during development.
LoggingMiddleware (from .logger): A middleware component responsible for logging incoming requests and outgoing responses. This middleware captures information such as request method, URL, status code, and response time, providing valuable data for monitoring and debugging the application.
MediaFilesMiddleware (from .media_files_middleware): A middleware component for serving user-uploaded media files. This middleware handles requests for files stored outside the static files directory, typically in a designated media folder, ensuring they are served correctly by the application.
Security Middlewares (from .security_middleware): A collection of middleware components focused on enhancing the application’s security posture.
- SecurityHeadersConfigurator: A utility or class for configuring various security-related
HTTP headers (e.g., X-Content-Type-Options, X-Frame-Options, Content-Security-Policy).
- SecurityHeadersMiddleware: Applies the configured security headers to all outgoing responses,
mitigating common web vulnerabilities.
- SQLInjectionDetectionMiddleware: A middleware specifically designed to detect and potentially
prevent SQL injection attempts by analyzing incoming request data for malicious patterns.
- SQLInjectionProtection: A utility or class that provides the core logic for SQL injection
protection, often used by the detection middleware.
SessionMiddleware (from .session_middleware): A middleware component that enables session management for the application. This middleware establishes and maintains user sessions across multiple requests, allowing the application to store and retrieve user-specific data (e.g., login status, shopping cart contents) between interactions.
SQLAlchemySessionMiddleware (from .sqlalchemy_middleware): A middleware component specifically for integrating SQLAlchemy sessions with the request lifecycle. This middleware typically manages the creation, usage, and closing of database sessions for each incoming request, ensuring proper database connection management.
StaticFilesMiddleware (from .static_files_middleware): A middleware component for serving static assets (e.g., CSS, JavaScript, images) directly from the application. This middleware intercepts requests for static files and serves them efficiently, typically in development environments, before a production web server takes over.
TimerMiddleware (from .timer): A middleware component designed to measure and log the time taken to process each request. This middleware can be useful for performance monitoring and identifying bottlenecks in the application’s request-response cycle.
Submodules
lback.middlewares.auth_midlewares module
- class lback.middlewares.auth_midlewares.AuthMiddleware(admin_user_manager: AdminUserManager, user_manager: UserManager, jwt_auth: JWTAuth)[source][source]
Bases:
BaseMiddlewareMiddleware to handle user authentication based on either session data or Authorization header (Bearer token). It attempts session authentication first (by checking data in request.session). If not found/valid, it attempts token authentication. Attaches the authenticated user (User or AdminUser) to request.user. Relies on SessionMiddleware to attach the session object to request.session for ALL requests. Requires SQLAlchemyMiddleware to run before it to provide the DB session. Requires the router/handler to set request.route_requires_auth for protected routes.
- __init__(admin_user_manager: AdminUserManager, user_manager: UserManager, jwt_auth: JWTAuth)[source][source]
Initializes AuthMiddleware with necessary managers and auth utilities. These dependencies should be initialized once globally (e.g., in core/server.py). :param admin_user_manager: The AdminUserManager instance. :param user_manager: The UserManager instance for regular users. :param jwt_auth_utility: The JWTAuth instance from auth.jwt_auth.
- process_request(request: Request)[source][source]
Processes the incoming request to authenticate the user via session data or token. Relies on request.session being populated by SessionMiddleware. Attaches request.user (User or AdminUser) if authenticated. Returns a Response if authentication/authorization fails AND the route requires auth, otherwise returns None.
lback.middlewares.body_parsing_middleware module
- class lback.middlewares.body_parsing_middleware.BodyParsingMiddleware(config: Any | None = None)[source][source]
Bases:
BaseMiddlewareMiddleware for parsing the request body based on Content-Type. Handles application/json, application/x-www-form-urlencoded, and multipart/form-data (using Werkzeug). Attaches parsed data to request.parsed_body (MultiDict) and uploaded files to request.files (dict of UploadedFile or list of UploadedFile).
lback.middlewares.cors module
- class lback.middlewares.cors.CORSMiddleware(allowed_origins=None)[source][source]
Bases:
BaseMiddleware- __init__(allowed_origins=None)[source][source]
Initialize the CORS middleware.
- Parameters:
allowed_origins (list) – A list of allowed origins. Use [‘*’] to allow all origins.
lback.middlewares.csrf module
- class lback.middlewares.csrf.CSRFMiddleware(session_manager: SessionManager)[source][source]
Bases:
BaseMiddlewareMiddleware to protect against Cross-Site Request Forgery (CSRF) attacks. Generates a CSRF token and adds it to the session and request context for GET requests. Checks the CSRF token for POST requests (or other methods that change state). Returns a Forbidden response if validation fails.
- __init__(session_manager: SessionManager)[source][source]
Initialize the CSRF middleware. :param session_manager: Instance of the session manager to manage sessions and CSRF tokens.
Note: While we store/retrieve token via UserSession, SessionManager might be needed for other potential CSRF related session operations or if UserSession doesn’t handle underlying session data persistence.
- process_request(request: Request) Response | None[source][source]
Processes the incoming request. For methods that require CSRF protection (e.g., POST, PUT, DELETE), validates the CSRF token. For safe methods (e.g., GET, HEAD, OPTIONS), ensures a CSRF token exists in the session and makes it available in context. :param request: The incoming Request object.
- Returns:
None if processing should continue, or a Response object (e.g., ForbiddenResponse) to short-circuit the request.
- process_response(request: Request, response: Response) Response[source][source]
Processes the outgoing response. (CSRFMiddleware typically doesn’t need to modify the response in the standard flow, as the token is handled in process_request and template context). However, some implementations might add the token to a response header for JS frameworks.
lback.middlewares.debug module
- class lback.middlewares.debug.DebugMiddleware(enabled=True, log_request=True, log_response=True, max_body_length=500)[source][source]
Bases:
BaseMiddlewareA middleware component designed for logging detailed information about incoming requests and outgoing responses within the web framework.
This middleware is primarily used during development and debugging phases to gain insights into the data flow, headers, and body content of HTTP communications. It can be enabled or disabled and configured to log either requests, responses, or both.
- __init__(enabled=True, log_request=True, log_response=True, max_body_length=500)[source][source]
Initializes the DebugMiddleware with logging preferences.
- Parameters:
enabled (bool) – A boolean indicating whether the middleware is active. If False, no logging will occur. Defaults to True.
log_request (bool) – A boolean indicating whether to log incoming request details. Defaults to True.
log_response (bool) – A boolean indicating whether to log outgoing response details. Defaults to True.
max_body_length (int) – The maximum length (in characters/bytes) for logging request and response bodies. Bodies exceeding this length will be truncated. Defaults to 500.
- process_request(request)[source][source]
Logs details of the incoming HTTP request if the middleware is enabled and configured for request logging.
This includes the request path, method, headers, and body (truncated if it exceeds max_body_length). As a BaseMiddleware method, it should return None to indicate that the request processing should continue to the next middleware or the view.
- Parameters:
request (Any) – The request object containing details about the incoming HTTP request. Expected to have path, method, headers, and body attributes.
- Returns:
None, allowing the request to proceed through the middleware stack.
- Return type:
None
- process_response(request, response)[source][source]
Logs details of the outgoing HTTP response if the middleware is enabled and configured for response logging.
This includes the response status code, and body (truncated if it exceeds max_body_length). As a BaseMiddleware method, it must return the response object, potentially modified, to be passed to the next middleware or back to the client.
- Parameters:
request (Any) – The original request object associated with this response.
response (Any) – The response object containing details about the outgoing HTTP response. Expected to have status_code and body attributes.
- Returns:
The response object, potentially after being logged.
- Return type:
Any
lback.middlewares.firewall_middleware module
- class lback.middlewares.firewall_middleware.FirewallMiddleware(firewall: AdvancedFirewall)[source][source]
Bases:
BaseMiddlewareMiddleware to check incoming requests against AdvancedFirewall rules.
- __init__(firewall: AdvancedFirewall)[source][source]
Initializes the FirewallMiddleware. :param firewall: An instance of the AdvancedFirewall class, configured with rules.
- process_request(request: Request) Response | None[source][source]
Processes the incoming request. Checks if the request is allowed by the firewall. :param request: The incoming Request object.
- Returns:
A Response object if the request is blocked (e.g., 403 Forbidden), otherwise None to allow the request to proceed.
- process_response(request: Request, response: Response) Response[source][source]
Abstract method to process the outgoing response after the view has been executed or a middleware has short-circuited the request.
Concrete middleware classes must implement this method. It can modify the response object before it is sent back to the client. This method is typically called in reverse order of middleware addition.
- Parameters:
request – The incoming request object (potentially modified by process_request chain).
response – The initial Response object generated by the view or a preceding middleware.
- Returns:
The modified or original Response object. Must always return a Response.
lback.middlewares.logger module
- class lback.middlewares.logger.LoggingMiddleware[source][source]
Bases:
BaseMiddlewareA middleware component for standardized logging of incoming HTTP requests and outgoing HTTP responses within the web application.
This middleware aims to provide a clear and concise log of basic request/response flow, which is essential for monitoring application activity, identifying patterns, and assisting in general troubleshooting. It also includes a mechanism to filter sensitive information like Authorization headers from the logs for security.
- process_request(request)[source][source]
Logs details of the incoming HTTP request.
This method captures the request method, path, and headers. Sensitive headers, such as ‘Authorization’, are filtered and obfuscated in the logs to prevent exposure of sensitive data. It returns None to allow the request to proceed through the middleware stack.
- Parameters:
request (Any) – The request object containing details about the incoming HTTP request. Expected to have method, path, and headers attributes.
- Returns:
None, allowing the request to proceed to the next middleware or view.
- Return type:
None
- process_response(request, response)[source][source]
Logs details of the outgoing HTTP response.
This method captures the request method, path, and the response’s status code, providing a quick overview of the outcome of the request. It must return the response object to continue the response processing.
- Parameters:
request (Any) – The original request object associated with this response.
response (Any) – The response object containing details about the outgoing HTTP response. Expected to have a status_code attribute.
- Returns:
The response object, potentially after being logged.
- Return type:
Any
lback.middlewares.media_files_middleware module
- class lback.middlewares.media_files_middleware.MediaFilesMiddleware[source][source]
Bases:
BaseMiddlewareMiddleware to serve user-uploaded media files during development. Only active when config.DEBUG is True. It uses UPLOAD_URL and UPLOAD_FOLDER from the application’s configuration.
- process_request(request)[source][source]
Processes the incoming request to check if it’s for a media file. If it is and the file exists, serves the file directly.
- Parameters:
request – The incoming request object. Expected to have ‘path’ and ‘config’ attributes.
- Returns:
A Response object if a media file is served, otherwise None to pass the request to the next middleware.
- process_response(request, response)[source][source]
Processes the outgoing response. For media files, this middleware usually returns a response directly, so this method might not be called for served files. It’s included for consistency with BaseMiddleware.
- Parameters:
request – The incoming request object.
response – The outgoing response object.
- Returns:
The response object.
lback.middlewares.rateLimiting_middleware module
- class lback.middlewares.rateLimiting_middleware.RateLimitingMiddleware(rate_limiter: RateLimiter)[source][source]
Bases:
BaseMiddlewareMiddleware to apply rate limiting to incoming requests using a RateLimiter instance. Takes a RateLimiter instance as a dependency.
- __init__(rate_limiter: RateLimiter)[source][source]
Initializes with a RateLimiter instance. :param rate_limiter: An instance of RateLimiter, configured with max requests and window. :param (a dependency).:
- process_request(request: Request) Response | None[source][source]
Applies rate limiting check to the incoming request. Returns a 429 Too Many Requests response if the limit is exceeded.
- process_response(request: Request, response: Response) Response[source][source]
Abstract method to process the outgoing response after the view has been executed or a middleware has short-circuited the request.
Concrete middleware classes must implement this method. It can modify the response object before it is sent back to the client. This method is typically called in reverse order of middleware addition.
- Parameters:
request – The incoming request object (potentially modified by process_request chain).
response – The initial Response object generated by the view or a preceding middleware.
- Returns:
The modified or original Response object. Must always return a Response.
lback.middlewares.security_headers_middleware module
- class lback.middlewares.security_headers_middleware.SecurityHeadersMiddleware(headers_configurator: SecurityHeadersConfigurator)[source][source]
Bases:
BaseMiddlewareMiddleware to add security headers to responses based on application configuration. Takes a SecurityHeadersConfigurator instance as a dependency.
- __init__(headers_configurator: SecurityHeadersConfigurator)[source][source]
Initializes with a SecurityHeadersConfigurator instance. :param headers_configurator: An instance of SecurityHeadersConfigurator, :param configured with application settings: :type configured with application settings: a dependency
lback.middlewares.session_middleware module
- class lback.middlewares.session_middleware.SessionMiddleware(session_manager: SessionManager)[source][source]
Bases:
BaseMiddlewareMiddleware to load session data at the start of the request and save session data (if modified) at the end of the request, using a database. Attaches a Session object (AppSession wrapper) to the request context using ‘session’. Handles session cookie reading and writing. Requires SQLAlchemyMiddleware to run before it to provide the DB session.
- __init__(session_manager: SessionManager)[source][source]
Initializes with a SessionManager instance (a dependency). :param session_manager: The SessionManager instance for session storage operations.
- process_request(request: Request) Response | None[source][source]
Abstract method to process the incoming request before it reaches the view.
Concrete middleware classes must implement this method. It can modify the request object or return a Response object to short-circuit the request processing chain and prevent the view from being called.
- Parameters:
request – The incoming request object.
- Returns:
A Response object to immediately return to the client (short-circuit), or None to allow the request to proceed to the next middleware or the view.
lback.middlewares.sql_injection_detection_middleware module
- class lback.middlewares.sql_injection_detection_middleware.SQLInjectionDetectionMiddleware[source][source]
Bases:
BaseMiddlewareMiddleware to detect potential SQL injection attempts in request body and query parameters.
- __init__()[source][source]
Initializes the SQLInjectionDetectionMiddleware. Note: This middleware uses class methods from SQLInjectionProtection, so it doesn’t require an instance of that class.
- process_request(request: Request) Response | None[source][source]
Checks request body and query parameters for suspicious SQL injection patterns. Returns a 400 Bad Request response if patterns are detected.
- process_response(request: Request, response: Response) Response[source][source]
Abstract method to process the outgoing response after the view has been executed or a middleware has short-circuited the request.
Concrete middleware classes must implement this method. It can modify the response object before it is sent back to the client. This method is typically called in reverse order of middleware addition.
- Parameters:
request – The incoming request object (potentially modified by process_request chain).
response – The initial Response object generated by the view or a preceding middleware.
- Returns:
The modified or original Response object. Must always return a Response.
lback.middlewares.sqlalchemy_middleware module
- class lback.middlewares.sqlalchemy_middleware.SQLAlchemySessionMiddleware(db_manager: DatabaseManager)[source][source]
Bases:
BaseMiddlewareMiddleware to manage a SQLAlchemy database session for each request. Creates a new session at the start of the request and closes it at the end. Attaches the session to the request context using the key ‘db_session’. Handles transaction management (commit or rollback) based on request outcome.
- __init__(db_manager: DatabaseManager)[source][source]
Initializes with a DatabaseManager instance (a dependency).
- Parameters:
db_manager – The DatabaseManager instance for session creation.
lback.middlewares.static_files_middleware module
- class lback.middlewares.static_files_middleware.StaticFilesMiddleware[source][source]
Bases:
BaseMiddlewareMiddleware to serve static files during development. Only active when config.DEBUG is True.
- process_request(request)[source][source]
Processes the incoming request to check if it’s for a static file. If it is and the file exists, serves the file directly.
- Parameters:
request – The incoming request object. Expected to have ‘path’ and ‘config’ attributes.
- Returns:
A Response object if a static file is served, otherwise None to pass the request to the next middleware.
lback.middlewares.timer module
- class lback.middlewares.timer.TimerMiddleware[source][source]
Bases:
BaseMiddlewareA middleware component that measures and logs the processing time for each HTTP request.
This middleware injects a start timestamp into the request object during the request processing phase and then calculates the total duration when the response is being processed. The duration is logged and also added as an ‘X-Response-Time’ header to the outgoing response.
- process_request(request)[source][source]
Records the starting timestamp for the incoming request.
This timestamp is stored as a private attribute _start_time on the request object, which will be used later during response processing to calculate the total request duration.
- Parameters:
request (Any) – The incoming request object.
- Returns:
None, allowing the request to proceed to the next middleware or view.
- Return type:
None
- process_response(request, response)[source][source]
Calculates the duration of the request and logs it, then adds it to the response headers.
This method retrieves the _start_time from the request object, calculates the elapsed time, logs this duration, and adds an X-Response-Time header to the outgoing response before returning it.
- Parameters:
request (Any) – The original request object, expected to have a _start_time attribute.
response (Any) – The outgoing response object.
- Returns:
The modified response object with the ‘X-Response-Time’ header.
- Return type:
Any