fixing DQ issues
This commit is contained in:
@@ -1,4 +1,12 @@
|
||||
# middleware/auth.py
|
||||
"""Summary description ....
|
||||
|
||||
This module provides classes and functions for:
|
||||
- ....
|
||||
- ....
|
||||
- ....
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
@@ -30,17 +38,17 @@ class AuthManager:
|
||||
self.token_expire_minutes = int(os.getenv("JWT_EXPIRE_MINUTES", "30"))
|
||||
|
||||
def hash_password(self, password: str) -> str:
|
||||
"""Hash password using bcrypt"""
|
||||
"""Hash password using bcrypt."""
|
||||
return pwd_context.hash(password)
|
||||
|
||||
def verify_password(self, plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verify password against hash"""
|
||||
"""Verify password against hash."""
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
def authenticate_user(
|
||||
self, db: Session, username: str, password: str
|
||||
) -> Optional[User]:
|
||||
"""Authenticate user and return user object if valid"""
|
||||
"""Authenticate user and return user object if valid."""
|
||||
user = (
|
||||
db.query(User)
|
||||
.filter((User.username == username) | (User.email == username))
|
||||
@@ -64,7 +72,7 @@ class AuthManager:
|
||||
return user
|
||||
|
||||
def create_access_token(self, user: User) -> Dict[str, Any]:
|
||||
"""Create JWT access token for user"""
|
||||
"""Create JWT access token for user."""
|
||||
expires_delta = timedelta(minutes=self.token_expire_minutes)
|
||||
expire = datetime.utcnow() + expires_delta
|
||||
|
||||
@@ -86,7 +94,7 @@ class AuthManager:
|
||||
}
|
||||
|
||||
def verify_token(self, token: str) -> Dict[str, Any]:
|
||||
"""Verify JWT token and return user data"""
|
||||
"""Verify JWT token and return user data."""
|
||||
try:
|
||||
payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
|
||||
|
||||
@@ -126,7 +134,7 @@ class AuthManager:
|
||||
def get_current_user(
|
||||
self, db: Session, credentials: HTTPAuthorizationCredentials
|
||||
) -> User:
|
||||
"""Get current authenticated user from database"""
|
||||
"""Get current authenticated user from database."""
|
||||
user_data = self.verify_token(credentials.credentials)
|
||||
|
||||
user = db.query(User).filter(User.id == user_data["user_id"]).first()
|
||||
@@ -139,7 +147,7 @@ class AuthManager:
|
||||
return user
|
||||
|
||||
def require_role(self, required_role: str):
|
||||
"""Decorator to require specific role"""
|
||||
"""Require specific role."""
|
||||
|
||||
def decorator(func):
|
||||
def wrapper(current_user: User, *args, **kwargs):
|
||||
@@ -155,13 +163,13 @@ class AuthManager:
|
||||
return decorator
|
||||
|
||||
def require_admin(self, current_user: User):
|
||||
"""Require admin role"""
|
||||
"""Require admin role."""
|
||||
if current_user.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="Admin privileges required")
|
||||
return current_user
|
||||
|
||||
def create_default_admin_user(self, db: Session):
|
||||
"""Create default admin user if it doesn't exist"""
|
||||
"""Create default admin user if it doesn't exist."""
|
||||
admin_user = db.query(User).filter(User.username == "admin").first()
|
||||
|
||||
if not admin_user:
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
# middleware/decorators.py
|
||||
"""Summary description ....
|
||||
|
||||
This module provides classes and functions for:
|
||||
- ....
|
||||
- ....
|
||||
- ....
|
||||
"""
|
||||
|
||||
from functools import wraps
|
||||
|
||||
from fastapi import HTTPException
|
||||
@@ -10,7 +18,7 @@ rate_limiter = RateLimiter()
|
||||
|
||||
|
||||
def rate_limit(max_requests: int = 100, window_seconds: int = 3600):
|
||||
"""Rate limiting decorator for FastAPI endpoints"""
|
||||
"""Rate limiting decorator for FastAPI endpoints."""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
# middleware/error_handler.py
|
||||
"""Summary description ....
|
||||
|
||||
This module provides classes and functions for:
|
||||
- ....
|
||||
- ....
|
||||
- ....
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
@@ -9,7 +17,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def custom_http_exception_handler(request: Request, exc: HTTPException):
|
||||
"""Custom HTTP exception handler"""
|
||||
"""Handle HTTP exception."""
|
||||
logger.error(
|
||||
f"HTTP {exc.status_code}: {exc.detail} - {request.method} {request.url}"
|
||||
)
|
||||
@@ -27,7 +35,7 @@ async def custom_http_exception_handler(request: Request, exc: HTTPException):
|
||||
|
||||
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
"""Handle Pydantic validation errors"""
|
||||
"""Handle Pydantic validation errors."""
|
||||
logger.error(f"Validation error: {exc.errors()} - {request.method} {request.url}")
|
||||
|
||||
return JSONResponse(
|
||||
@@ -44,7 +52,7 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
||||
|
||||
|
||||
async def general_exception_handler(request: Request, exc: Exception):
|
||||
"""Handle unexpected exceptions"""
|
||||
"""Handle unexpected exceptions."""
|
||||
logger.error(
|
||||
f"Unexpected error: {str(exc)} - {request.method} {request.url}", exc_info=True
|
||||
)
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
# middleware/logging_middleware.py
|
||||
"""Summary description ....
|
||||
|
||||
This module provides classes and functions for:
|
||||
- ....
|
||||
- ....
|
||||
- ....
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Callable
|
||||
@@ -10,9 +18,10 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LoggingMiddleware(BaseHTTPMiddleware):
|
||||
"""Middleware for request/response logging and performance monitoring"""
|
||||
"""Middleware for request/response logging and performance monitoring."""
|
||||
|
||||
async def dispatch(self, request: Request, call_next: Callable) -> Response:
|
||||
"""Dispatch."""
|
||||
# Start timing
|
||||
start_time = time.time()
|
||||
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
# middleware/rate_limiter.py
|
||||
"""Summary description ....
|
||||
|
||||
This module provides classes and functions for:
|
||||
- ....
|
||||
- ....
|
||||
- ....
|
||||
"""
|
||||
|
||||
import logging
|
||||
from collections import defaultdict, deque
|
||||
from datetime import datetime, timedelta
|
||||
@@ -8,7 +16,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""In-memory rate limiter using sliding window"""
|
||||
"""In-memory rate limiter using sliding window."""
|
||||
|
||||
def __init__(self):
|
||||
"""Class constructor."""
|
||||
@@ -21,7 +29,8 @@ class RateLimiter:
|
||||
self, client_id: str, max_requests: int, window_seconds: int
|
||||
) -> bool:
|
||||
"""
|
||||
Check if client is allowed to make a request
|
||||
Check if client is allowed to make a request.
|
||||
|
||||
Uses sliding window algorithm
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
@@ -50,7 +59,7 @@ class RateLimiter:
|
||||
return False
|
||||
|
||||
def _cleanup_old_entries(self):
|
||||
"""Clean up old entries to prevent memory leaks"""
|
||||
"""Clean up old entries to prevent memory leaks."""
|
||||
cutoff_time = datetime.utcnow() - timedelta(hours=24)
|
||||
|
||||
clients_to_remove = []
|
||||
@@ -72,7 +81,7 @@ class RateLimiter:
|
||||
)
|
||||
|
||||
def get_client_stats(self, client_id: str) -> Dict[str, int]:
|
||||
"""Get statistics for a specific client"""
|
||||
"""Get statistics for a specific client."""
|
||||
client_requests = self.clients.get(client_id, deque())
|
||||
|
||||
now = datetime.utcnow()
|
||||
|
||||
Reference in New Issue
Block a user