Some checks failed
- Add Development URL Quick Reference section to url-routing overview with all login URLs, entry points, and full examples - Replace /shop/ path segments with /storefront/ across 50 docs files - Update file references: shop_pages.py → storefront_pages.py, templates/shop/ → templates/storefront/, api/v1/shop/ → api/v1/storefront/ - Preserve domain references (orion.shop) and /store/ staff dashboard paths - Archive docs left unchanged (historical) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
333 lines
9.3 KiB
Markdown
333 lines
9.3 KiB
Markdown
# 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_store
|
|
- require_customer
|
|
- create_default_admin_user
|
|
|
|
---
|
|
|
|
## Multi-Tenant Context Management
|
|
|
|
### StoreContextManager
|
|
|
|
Detects and manages store 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 → Store)
|
|
- Subdomain routing (store1.platform.com → Store)
|
|
- Path-based routing (/store/store1/ → Store)
|
|
- Clean path extraction for nested routing
|
|
|
|
::: middleware.store_context.StoreContextManager
|
|
options:
|
|
show_source: false
|
|
heading_level: 4
|
|
show_root_heading: false
|
|
|
|
### StoreContextMiddleware
|
|
|
|
ASGI middleware that wraps StoreContextManager for FastAPI integration.
|
|
|
|
::: middleware.store_context.StoreContextMiddleware
|
|
options:
|
|
show_source: false
|
|
heading_level: 4
|
|
show_root_heading: false
|
|
|
|
---
|
|
|
|
## Frontend Type Detection
|
|
|
|
### FrontendType
|
|
|
|
Enum defining all possible frontend types in the application.
|
|
|
|
::: app.modules.enums.FrontendType
|
|
options:
|
|
show_source: false
|
|
heading_level: 4
|
|
show_root_heading: false
|
|
members:
|
|
- PLATFORM
|
|
- ADMIN
|
|
- STORE
|
|
- STOREFRONT
|
|
|
|
### FrontendDetector
|
|
|
|
Centralized class for detecting which frontend a request targets based on URL patterns.
|
|
|
|
**Detection Rules (Priority Order):**
|
|
1. Admin subdomain (`admin.*`) → ADMIN
|
|
2. Path-based detection:
|
|
- `/admin/*`, `/api/v1/admin/*` → ADMIN
|
|
- `/store/*`, `/api/v1/store/*` → STORE
|
|
- `/storefront/*`, `/stores/*` → STOREFRONT
|
|
- `/api/v1/platform/*` → PLATFORM
|
|
3. Store subdomain → STOREFRONT
|
|
4. Store context set → STOREFRONT
|
|
5. Default → PLATFORM
|
|
|
|
::: app.core.frontend_detector.FrontendDetector
|
|
options:
|
|
show_source: false
|
|
heading_level: 4
|
|
show_root_heading: false
|
|
|
|
### FrontendTypeMiddleware
|
|
|
|
ASGI middleware for frontend type detection. Must run AFTER StoreContextMiddleware.
|
|
|
|
::: middleware.frontend_type.FrontendTypeMiddleware
|
|
options:
|
|
show_source: false
|
|
heading_level: 4
|
|
show_root_heading: false
|
|
|
|
> **Note**: The old `RequestContext` enum and `ContextMiddleware` are deprecated.
|
|
> See [Frontend Detection Architecture](../architecture/frontend-detection.md) for migration guide.
|
|
|
|
---
|
|
|
|
## Theme Management
|
|
|
|
### ThemeContextManager
|
|
|
|
Manages store-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.LoggingMiddleware
|
|
options:
|
|
show_source: false
|
|
heading_level: 4
|
|
show_root_heading: false
|
|
|
|
---
|
|
|
|
## Path-Based Routing Solution
|
|
|
|
**Modern Approach: Double Router Mounting**
|
|
|
|
Instead of using middleware to rewrite paths, the application registers storefront routes **twice** with different prefixes:
|
|
|
|
```python
|
|
# In main.py
|
|
app.include_router(storefront_pages.router, prefix="/storefront")
|
|
app.include_router(storefront_pages.router, prefix="/stores/{store_code}/storefront")
|
|
```
|
|
|
|
**How It Works:**
|
|
- **Subdomain/Custom Domain Mode**: Routes match `/storefront/*` prefix
|
|
- **Path-Based Development Mode**: Routes match `/stores/{store_code}/storefront/*` prefix
|
|
- FastAPI handles routing naturally without path manipulation
|
|
- Store code is available as a path parameter when needed
|
|
|
|
**Benefits:**
|
|
- ✅ No middleware complexity
|
|
- ✅ Explicit route definitions
|
|
- ✅ FastAPI native routing
|
|
- ✅ Store code accessible via path parameter
|
|
|
|
**Note:** Previous implementations used `path_rewrite_middleware` to rewrite paths at runtime. This approach has been deprecated in favor of double mounting, which is simpler and more maintainable.
|
|
|
|
---
|
|
|
|
## 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[PlatformContextMiddleware]
|
|
C --> D[StoreContextMiddleware]
|
|
D --> E[FrontendTypeMiddleware]
|
|
E --> F[LanguageMiddleware]
|
|
F --> G[ThemeContextMiddleware]
|
|
G --> H[Application Routes]
|
|
H --> I[Response]
|
|
```
|
|
|
|
**Critical Dependencies:**
|
|
1. **LoggingMiddleware** runs first for request timing
|
|
2. **PlatformContextMiddleware** detects platform and sets platform context
|
|
3. **StoreContextMiddleware** detects store and sets clean_path
|
|
4. **FrontendTypeMiddleware** detects frontend type (ADMIN/STORE/STOREFRONT/PLATFORM)
|
|
5. **LanguageMiddleware** resolves language based on frontend type
|
|
6. **ThemeContextMiddleware** loads store theme based on context
|
|
|
|
**Note:** Path-based routing (e.g., `/platforms/{platform_code}/storefront/{store_code}/*`) is handled by double router mounting in `main.py`, not by middleware. In production (subdomain/custom domain), `PlatformContextMiddleware` rewrites the path to prepend `/storefront/` internally.
|
|
|
|
---
|
|
|
|
## Request State Variables
|
|
|
|
Middleware components inject the following variables into `request.state`:
|
|
|
|
| Variable | Set By | Type | Description |
|
|
|----------|--------|------|-------------|
|
|
| `platform` | PlatformContextMiddleware | Platform | Current platform object |
|
|
| `store` | StoreContextMiddleware | Store | Current store object |
|
|
| `store_id` | StoreContextMiddleware | int | Current store ID |
|
|
| `clean_path` | StoreContextMiddleware | str | Path without store prefix |
|
|
| `frontend_type` | FrontendTypeMiddleware | FrontendType | Frontend type (ADMIN/STORE/STOREFRONT/PLATFORM) |
|
|
| `language` | LanguageMiddleware | str | Detected language code |
|
|
| `theme` | ThemeContextMiddleware | dict | Store theme configuration |
|
|
|
|
**Usage in Routes:**
|
|
```python
|
|
from fastapi import Request
|
|
from app.modules.enums import FrontendType
|
|
from middleware.frontend_type import get_frontend_type
|
|
|
|
@app.get("/storefront/products")
|
|
async def get_products(request: Request):
|
|
store = request.state.store
|
|
frontend_type = get_frontend_type(request)
|
|
theme = request.state.theme
|
|
|
|
if frontend_type == FrontendType.STOREFRONT:
|
|
return {"store": store.name, "frontend": frontend_type.value}
|
|
```
|
|
|
|
---
|
|
|
|
## 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
|
|
|
|
- [Frontend Detection Architecture](../architecture/frontend-detection.md) - Frontend type detection system
|
|
- [Middleware Architecture](../architecture/middleware.md) - Middleware stack overview
|
|
- [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
|