feat: add core application constants, ownership verification, and repository utilities
- Introduced application-wide constants for file uploads, image processing, pagination, and authentication in `constants.py`. - Implemented synchronous and asynchronous board ownership verification functions in `ownership.py`. - Created a base repository class with common CRUD operations in `repository.py`. - Added standard response utilities for error and success messages in `responses.py`. - Refactored image validation to utilize constants for file size and MIME types. - Enhanced frontend components with consistent styling and validation utilities for forms. - Established global styles for buttons, forms, loading indicators, and messages to ensure a cohesive UI experience.
This commit is contained in:
38
backend/app/core/constants.py
Normal file
38
backend/app/core/constants.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""Application-wide constants."""
|
||||
|
||||
# File upload limits
|
||||
MAX_IMAGE_SIZE = 52_428_800 # 50MB in bytes
|
||||
MAX_ZIP_SIZE = 209_715_200 # 200MB in bytes
|
||||
|
||||
# Image processing
|
||||
MAX_IMAGE_DIMENSION = 10_000 # Max width or height in pixels
|
||||
THUMBNAIL_SIZES = {
|
||||
"low": 800, # For slow connections (<1 Mbps)
|
||||
"medium": 1600, # For medium connections (1-5 Mbps)
|
||||
"high": 3200, # For fast connections (>5 Mbps)
|
||||
}
|
||||
|
||||
# Pagination defaults
|
||||
DEFAULT_PAGE_SIZE = 50
|
||||
MAX_PAGE_SIZE = 100
|
||||
|
||||
# Board limits
|
||||
MAX_BOARD_TITLE_LENGTH = 255
|
||||
MAX_BOARD_DESCRIPTION_LENGTH = 1000
|
||||
MAX_IMAGES_PER_BOARD = 1000
|
||||
|
||||
# Authentication
|
||||
TOKEN_EXPIRE_HOURS = 168 # 7 days
|
||||
PASSWORD_MIN_LENGTH = 8
|
||||
|
||||
# Supported image formats
|
||||
ALLOWED_MIME_TYPES = {
|
||||
"image/jpeg",
|
||||
"image/jpg",
|
||||
"image/png",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
"image/svg+xml",
|
||||
}
|
||||
|
||||
ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"}
|
||||
69
backend/app/core/ownership.py
Normal file
69
backend/app/core/ownership.py
Normal file
@@ -0,0 +1,69 @@
|
||||
"""Ownership verification utilities."""
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database.models.board import Board
|
||||
|
||||
|
||||
def verify_board_ownership_sync(db: Session, board_id: UUID, user_id: UUID) -> Board:
|
||||
"""
|
||||
Verify board ownership (synchronous).
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
board_id: Board UUID
|
||||
user_id: User UUID
|
||||
|
||||
Returns:
|
||||
Board instance if owned by user
|
||||
|
||||
Raises:
|
||||
HTTPException: 404 if board not found or not owned by user
|
||||
"""
|
||||
stmt = select(Board).where(
|
||||
Board.id == board_id,
|
||||
Board.user_id == user_id,
|
||||
Board.is_deleted == False, # noqa: E712
|
||||
)
|
||||
|
||||
board = db.execute(stmt).scalar_one_or_none()
|
||||
|
||||
if not board:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Board {board_id} not found")
|
||||
|
||||
return board
|
||||
|
||||
|
||||
async def verify_board_ownership_async(db: AsyncSession, board_id: UUID, user_id: UUID) -> Board:
|
||||
"""
|
||||
Verify board ownership (asynchronous).
|
||||
|
||||
Args:
|
||||
db: Async database session
|
||||
board_id: Board UUID
|
||||
user_id: User UUID
|
||||
|
||||
Returns:
|
||||
Board instance if owned by user
|
||||
|
||||
Raises:
|
||||
HTTPException: 404 if board not found or not owned by user
|
||||
"""
|
||||
stmt = select(Board).where(
|
||||
Board.id == board_id,
|
||||
Board.user_id == user_id,
|
||||
Board.is_deleted == False, # noqa: E712
|
||||
)
|
||||
|
||||
result = await db.execute(stmt)
|
||||
board = result.scalar_one_or_none()
|
||||
|
||||
if not board:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Board {board_id} not found")
|
||||
|
||||
return board
|
||||
119
backend/app/core/repository.py
Normal file
119
backend/app/core/repository.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Base repository with common database operations."""
|
||||
|
||||
from typing import TypeVar
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# Type variable for model classes
|
||||
ModelType = TypeVar("ModelType")
|
||||
|
||||
|
||||
class BaseRepository[ModelType]:
|
||||
"""Base repository with common CRUD operations."""
|
||||
|
||||
def __init__(self, model: type[ModelType], db: Session | AsyncSession):
|
||||
"""
|
||||
Initialize repository.
|
||||
|
||||
Args:
|
||||
model: SQLAlchemy model class
|
||||
db: Database session (sync or async)
|
||||
"""
|
||||
self.model = model
|
||||
self.db = db
|
||||
|
||||
def get_by_id_sync(self, id: UUID) -> ModelType | None:
|
||||
"""
|
||||
Get entity by ID (synchronous).
|
||||
|
||||
Args:
|
||||
id: Entity UUID
|
||||
|
||||
Returns:
|
||||
Entity if found, None otherwise
|
||||
"""
|
||||
return self.db.query(self.model).filter(self.model.id == id).first()
|
||||
|
||||
async def get_by_id_async(self, id: UUID) -> ModelType | None:
|
||||
"""
|
||||
Get entity by ID (asynchronous).
|
||||
|
||||
Args:
|
||||
id: Entity UUID
|
||||
|
||||
Returns:
|
||||
Entity if found, None otherwise
|
||||
"""
|
||||
stmt = select(self.model).where(self.model.id == id)
|
||||
result = await self.db.execute(stmt)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
def count_sync(self, **filters) -> int:
|
||||
"""
|
||||
Count entities with optional filters (synchronous).
|
||||
|
||||
Args:
|
||||
**filters: Column filters (column_name=value)
|
||||
|
||||
Returns:
|
||||
Count of matching entities
|
||||
"""
|
||||
query = self.db.query(func.count(self.model.id))
|
||||
for key, value in filters.items():
|
||||
query = query.filter(getattr(self.model, key) == value)
|
||||
return query.scalar()
|
||||
|
||||
async def count_async(self, **filters) -> int:
|
||||
"""
|
||||
Count entities with optional filters (asynchronous).
|
||||
|
||||
Args:
|
||||
**filters: Column filters (column_name=value)
|
||||
|
||||
Returns:
|
||||
Count of matching entities
|
||||
"""
|
||||
stmt = select(func.count(self.model.id))
|
||||
for key, value in filters.items():
|
||||
stmt = stmt.where(getattr(self.model, key) == value)
|
||||
result = await self.db.execute(stmt)
|
||||
return result.scalar_one()
|
||||
|
||||
def delete_sync(self, id: UUID) -> bool:
|
||||
"""
|
||||
Delete entity by ID (synchronous).
|
||||
|
||||
Args:
|
||||
id: Entity UUID
|
||||
|
||||
Returns:
|
||||
True if deleted, False if not found
|
||||
"""
|
||||
entity = self.get_by_id_sync(id)
|
||||
if not entity:
|
||||
return False
|
||||
|
||||
self.db.delete(entity)
|
||||
self.db.commit()
|
||||
return True
|
||||
|
||||
async def delete_async(self, id: UUID) -> bool:
|
||||
"""
|
||||
Delete entity by ID (asynchronous).
|
||||
|
||||
Args:
|
||||
id: Entity UUID
|
||||
|
||||
Returns:
|
||||
True if deleted, False if not found
|
||||
"""
|
||||
entity = await self.get_by_id_async(id)
|
||||
if not entity:
|
||||
return False
|
||||
|
||||
await self.db.delete(entity)
|
||||
await self.db.commit()
|
||||
return True
|
||||
75
backend/app/core/responses.py
Normal file
75
backend/app/core/responses.py
Normal file
@@ -0,0 +1,75 @@
|
||||
"""Standard response utilities."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import status
|
||||
|
||||
|
||||
class ErrorResponse:
|
||||
"""Standard error response formats."""
|
||||
|
||||
@staticmethod
|
||||
def not_found(resource: str = "Resource") -> dict[str, Any]:
|
||||
"""404 Not Found response."""
|
||||
return {
|
||||
"status_code": status.HTTP_404_NOT_FOUND,
|
||||
"detail": f"{resource} not found",
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def forbidden(message: str = "Access denied") -> dict[str, Any]:
|
||||
"""403 Forbidden response."""
|
||||
return {
|
||||
"status_code": status.HTTP_403_FORBIDDEN,
|
||||
"detail": message,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def unauthorized(message: str = "Authentication required") -> dict[str, Any]:
|
||||
"""401 Unauthorized response."""
|
||||
return {
|
||||
"status_code": status.HTTP_401_UNAUTHORIZED,
|
||||
"detail": message,
|
||||
"headers": {"WWW-Authenticate": "Bearer"},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def bad_request(message: str) -> dict[str, Any]:
|
||||
"""400 Bad Request response."""
|
||||
return {
|
||||
"status_code": status.HTTP_400_BAD_REQUEST,
|
||||
"detail": message,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def conflict(message: str) -> dict[str, Any]:
|
||||
"""409 Conflict response."""
|
||||
return {
|
||||
"status_code": status.HTTP_409_CONFLICT,
|
||||
"detail": message,
|
||||
}
|
||||
|
||||
|
||||
class SuccessResponse:
|
||||
"""Standard success response formats."""
|
||||
|
||||
@staticmethod
|
||||
def created(data: dict[str, Any], message: str = "Created successfully") -> dict[str, Any]:
|
||||
"""201 Created response."""
|
||||
return {
|
||||
"message": message,
|
||||
"data": data,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def ok(data: dict[str, Any] | None = None, message: str = "Success") -> dict[str, Any]:
|
||||
"""200 OK response."""
|
||||
response = {"message": message}
|
||||
if data:
|
||||
response["data"] = data
|
||||
return response
|
||||
|
||||
@staticmethod
|
||||
def no_content() -> None:
|
||||
"""204 No Content response."""
|
||||
return None
|
||||
Reference in New Issue
Block a user