revamping documentation
This commit is contained in:
305
docs/backend/middleware-reference.md
Normal file
305
docs/backend/middleware-reference.md
Normal file
@@ -0,0 +1,305 @@
|
||||
# API Reference
|
||||
|
||||
Complete technical reference for all middleware components, utilities, and core classes.
|
||||
|
||||
## Overview
|
||||
|
||||
This reference provides detailed API documentation for all internal modules and classes. All documentation is auto-generated from source code docstrings.
|
||||
|
||||
---
|
||||
|
||||
## Authentication & Authorization
|
||||
|
||||
### AuthManager
|
||||
|
||||
The core authentication manager handling JWT tokens, password hashing, and role-based access control.
|
||||
|
||||
::: middleware.auth.AuthManager
|
||||
options:
|
||||
show_source: false
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
show_root_toc_entry: false
|
||||
members:
|
||||
- __init__
|
||||
- hash_password
|
||||
- verify_password
|
||||
- authenticate_user
|
||||
- create_access_token
|
||||
- verify_token
|
||||
- get_current_user
|
||||
- require_role
|
||||
- require_admin
|
||||
- require_vendor
|
||||
- require_customer
|
||||
- create_default_admin_user
|
||||
|
||||
---
|
||||
|
||||
## Multi-Tenant Context Management
|
||||
|
||||
### VendorContextManager
|
||||
|
||||
Detects and manages vendor context from custom domains, subdomains, or path-based routing. This is the foundation of the multi-tenant system.
|
||||
|
||||
**Key Features:**
|
||||
- Custom domain routing (customdomain.com → Vendor)
|
||||
- Subdomain routing (vendor1.platform.com → Vendor)
|
||||
- Path-based routing (/vendor/vendor1/ → Vendor)
|
||||
- Clean path extraction for nested routing
|
||||
|
||||
::: middleware.vendor_context.VendorContextManager
|
||||
options:
|
||||
show_source: false
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
|
||||
### VendorContextMiddleware
|
||||
|
||||
ASGI middleware that wraps VendorContextManager for FastAPI integration.
|
||||
|
||||
::: middleware.vendor_context.VendorContextMiddleware
|
||||
options:
|
||||
show_source: false
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
|
||||
---
|
||||
|
||||
## Request Context Detection
|
||||
|
||||
### RequestContext
|
||||
|
||||
Enum defining all possible request context types in the application.
|
||||
|
||||
::: middleware.context_middleware.RequestContext
|
||||
options:
|
||||
show_source: false
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
members:
|
||||
- API
|
||||
- ADMIN
|
||||
- VENDOR_DASHBOARD
|
||||
- SHOP
|
||||
- FALLBACK
|
||||
|
||||
### ContextManager
|
||||
|
||||
Detects the type of request (API, Admin, Vendor Dashboard, Shop) based on URL patterns.
|
||||
|
||||
**Context Detection Rules:**
|
||||
- `/api/` → API context
|
||||
- `/admin/` → Admin context
|
||||
- `/vendor/` → Vendor Dashboard context
|
||||
- `/shop/` → Shop context
|
||||
- Default → Fallback context
|
||||
|
||||
::: middleware.context_middleware.ContextManager
|
||||
options:
|
||||
show_source: false
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
|
||||
### ContextMiddleware
|
||||
|
||||
ASGI middleware for context detection. Must run AFTER VendorContextMiddleware.
|
||||
|
||||
::: middleware.context_middleware.ContextMiddleware
|
||||
options:
|
||||
show_source: false
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
|
||||
---
|
||||
|
||||
## Theme Management
|
||||
|
||||
### ThemeContextManager
|
||||
|
||||
Manages vendor-specific theme configuration and injection into request context.
|
||||
|
||||
::: middleware.theme_context.ThemeContextManager
|
||||
options:
|
||||
show_source: false
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
|
||||
### ThemeContextMiddleware
|
||||
|
||||
ASGI middleware for theme injection. Must run AFTER ContextDetectionMiddleware.
|
||||
|
||||
::: middleware.theme_context.ThemeContextMiddleware
|
||||
options:
|
||||
show_source: false
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
|
||||
---
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
### RateLimiter
|
||||
|
||||
In-memory rate limiter using a sliding window algorithm for request throttling.
|
||||
|
||||
**Features:**
|
||||
- Sliding window algorithm for accurate rate limiting
|
||||
- Per-client tracking
|
||||
- Automatic cleanup of old entries
|
||||
- Configurable limits and time windows
|
||||
|
||||
::: middleware.rate_limiter.RateLimiter
|
||||
options:
|
||||
show_source: false
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
|
||||
### Rate Limiting Decorator
|
||||
|
||||
Decorator for applying rate limits to FastAPI endpoints.
|
||||
|
||||
::: middleware.decorators.rate_limit
|
||||
options:
|
||||
show_source: true
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
|
||||
**Usage Example:**
|
||||
```python
|
||||
from middleware.decorators import rate_limit
|
||||
|
||||
@app.post("/api/v1/resource")
|
||||
@rate_limit(max_requests=10, window_seconds=60)
|
||||
async def create_resource():
|
||||
return {"status": "created"}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Logging & Monitoring
|
||||
|
||||
### LoggingMiddleware
|
||||
|
||||
Middleware for request/response logging and performance monitoring.
|
||||
|
||||
**Logged Information:**
|
||||
- Request method, path, and client IP
|
||||
- Response status code
|
||||
- Request processing time
|
||||
- Errors and exceptions
|
||||
|
||||
**Added Headers:**
|
||||
- `X-Process-Time`: Request processing duration in seconds
|
||||
|
||||
::: middleware.logging_middleware.LoggingMiddleware
|
||||
options:
|
||||
show_source: false
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
|
||||
---
|
||||
|
||||
## Path Rewriting
|
||||
|
||||
### path_rewrite_middleware
|
||||
|
||||
Middleware function that rewrites request paths for path-based vendor routing.
|
||||
|
||||
**Purpose:**
|
||||
Allows `/vendor/VENDORCODE/shop/products` to be internally routed as `/shop/products` for proper FastAPI route matching.
|
||||
|
||||
**Execution Order:**
|
||||
Must run AFTER VendorContextMiddleware and BEFORE ContextDetectionMiddleware.
|
||||
|
||||
::: middleware.path_rewrite_middleware.path_rewrite_middleware
|
||||
options:
|
||||
show_source: true
|
||||
heading_level: 4
|
||||
show_root_heading: false
|
||||
|
||||
---
|
||||
|
||||
## Middleware Execution Order
|
||||
|
||||
The middleware stack must be configured in the correct order for proper functionality:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Request] --> B[LoggingMiddleware]
|
||||
B --> C[VendorContextMiddleware]
|
||||
C --> D[PathRewriteMiddleware]
|
||||
D --> E[ContextMiddleware]
|
||||
E --> F[ThemeContextMiddleware]
|
||||
F --> G[Application Routes]
|
||||
G --> H[Response]
|
||||
```
|
||||
|
||||
**Critical Dependencies:**
|
||||
1. **VendorContextMiddleware** must run first to detect vendor
|
||||
2. **PathRewriteMiddleware** needs `clean_path` from VendorContext
|
||||
3. **ContextMiddleware** needs rewritten path
|
||||
4. **ThemeContextMiddleware** needs context type
|
||||
|
||||
---
|
||||
|
||||
## Request State Variables
|
||||
|
||||
Middleware components inject the following variables into `request.state`:
|
||||
|
||||
| Variable | Set By | Type | Description |
|
||||
|----------|--------|------|-------------|
|
||||
| `vendor` | VendorContextMiddleware | Vendor | Current vendor object |
|
||||
| `vendor_id` | VendorContextMiddleware | int | Current vendor ID |
|
||||
| `clean_path` | VendorContextMiddleware | str | Path without vendor prefix |
|
||||
| `context_type` | ContextMiddleware | RequestContext | Request context (API/Admin/Vendor/Shop) |
|
||||
| `theme` | ThemeContextMiddleware | dict | Vendor theme configuration |
|
||||
|
||||
**Usage in Routes:**
|
||||
```python
|
||||
from fastapi import Request
|
||||
|
||||
@app.get("/shop/products")
|
||||
async def get_products(request: Request):
|
||||
vendor = request.state.vendor
|
||||
context = request.state.context_type
|
||||
theme = request.state.theme
|
||||
return {"vendor": vendor.name, "context": context}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Error Handling
|
||||
All middleware should properly handle exceptions and log errors for debugging:
|
||||
|
||||
```python
|
||||
try:
|
||||
# Middleware logic
|
||||
except Exception as e:
|
||||
logger.error(f"Middleware error: {e}")
|
||||
raise
|
||||
```
|
||||
|
||||
### Performance
|
||||
- Keep middleware logic minimal and fast
|
||||
- Use async/await properly for non-blocking operations
|
||||
- Log performance metrics for monitoring
|
||||
|
||||
### Testing
|
||||
- Test middleware in isolation
|
||||
- Mock request.state for unit tests
|
||||
- Test middleware execution order
|
||||
- Verify error handling paths
|
||||
|
||||
For testing examples, see the [Testing Guide](../testing/testing-guide.md).
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Authentication Guide](../api/authentication.md) - User authentication and JWT tokens
|
||||
- [RBAC Documentation](../api/RBAC.md) - Role-based access control
|
||||
- [Error Handling](../api/error-handling.md) - Exception handling patterns
|
||||
- [Rate Limiting](../api/rate-limiting.md) - API rate limiting strategies
|
||||
Reference in New Issue
Block a user