-
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field, field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
BACKEND_DIR = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=BACKEND_DIR / ".env", env_file_encoding="utf-8", extra="ignore"
|
||||
)
|
||||
|
||||
APP_NAME: str = "Saura Shakti API"
|
||||
ENVIRONMENT: str = "development" # development | test
|
||||
API_PREFIX: str = "/api"
|
||||
|
||||
DATABASE_URL: str
|
||||
DB_ECHO: bool = False
|
||||
|
||||
JWT_SECRET_KEY: str = Field(min_length=32)
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
JWT_EXPIRE_MINUTES: int = 120
|
||||
|
||||
# Comma-separated list in .env
|
||||
CORS_ORIGINS: str = "http://localhost:5173"
|
||||
|
||||
# Media / uploads
|
||||
UPLOAD_DIR: Path = BACKEND_DIR / "uploads"
|
||||
MEDIA_URL_PATH: str = "/media"
|
||||
MEDIA_BASE_URL: str = "http://localhost:8020/media"
|
||||
MAX_UPLOAD_SIZE_MB: int = 10
|
||||
MAX_FILES_PER_UPLOAD: int = 20
|
||||
MAX_IMAGE_PIXELS: int = 60_000_000 # guards against decompression bombs
|
||||
|
||||
# Watermark
|
||||
WATERMARK_LOGO_PATH: Path = BACKEND_DIR / "assets" / "watermark" / "logo.png"
|
||||
WATERMARK_WIDTH_RATIO: float = 0.18 # logo width relative to image width
|
||||
WATERMARK_MIN_WIDTH: int = 80
|
||||
WATERMARK_MAX_WIDTH: int = 600
|
||||
WATERMARK_MARGIN_RATIO: float = 0.03 # margin relative to the shorter image side
|
||||
WATERMARK_OPACITY: float = 0.75
|
||||
WATERMARK_SHADOW_OPACITY: float = 0.35
|
||||
|
||||
THUMBNAIL_MAX_SIZE: int = 640
|
||||
|
||||
# Email (quotations). If SMTP_HOST is empty, emails are written to OUTBOX_DIR as .eml files.
|
||||
SMTP_HOST: str = ""
|
||||
SMTP_PORT: int = 587
|
||||
SMTP_USER: str = ""
|
||||
SMTP_PASSWORD: str = ""
|
||||
SMTP_STARTTLS: bool = True
|
||||
MAIL_FROM: str = "Saura Shakti <no-reply@localhost>"
|
||||
OUTBOX_DIR: Path = BACKEND_DIR / "outbox"
|
||||
|
||||
# Simple in-memory rate limits (per client IP, per process)
|
||||
LOGIN_RATE_LIMIT_PER_MINUTE: int = 10
|
||||
PUBLIC_FORM_RATE_LIMIT_PER_MINUTE: int = 10
|
||||
|
||||
@field_validator("WATERMARK_OPACITY", "WATERMARK_SHADOW_OPACITY")
|
||||
@classmethod
|
||||
def _opacity_range(cls, v: float) -> float:
|
||||
if not 0 <= v <= 1:
|
||||
raise ValueError("opacity must be between 0 and 1")
|
||||
return v
|
||||
|
||||
@property
|
||||
def cors_origins_list(self) -> list[str]:
|
||||
return [o.strip() for o in self.CORS_ORIGINS.split(",") if o.strip()]
|
||||
|
||||
@property
|
||||
def max_upload_bytes(self) -> int:
|
||||
return self.MAX_UPLOAD_SIZE_MB * 1024 * 1024
|
||||
|
||||
@property
|
||||
def is_test(self) -> bool:
|
||||
return self.ENVIRONMENT == "test"
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings() # type: ignore[call-arg]
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
@@ -0,0 +1,19 @@
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
_engine_kwargs: dict = {"echo": settings.DB_ECHO, "pool_pre_ping": True}
|
||||
if settings.is_test:
|
||||
# Tests run each case in its own event loop; pooled connections can't cross loops.
|
||||
_engine_kwargs["poolclass"] = NullPool
|
||||
|
||||
engine = create_async_engine(settings.DATABASE_URL, **_engine_kwargs)
|
||||
SessionLocal = async_sessionmaker(engine, expire_on_commit=False, autoflush=False)
|
||||
|
||||
|
||||
async def get_db() -> AsyncIterator[AsyncSession]:
|
||||
async with SessionLocal() as session:
|
||||
yield session
|
||||
@@ -0,0 +1,68 @@
|
||||
from typing import Annotated
|
||||
|
||||
import jwt
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import decode_access_token
|
||||
from app.models import Admin, AdminRole
|
||||
|
||||
DbSession = Annotated[AsyncSession, Depends(get_db)]
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False, description="JWT from POST /api/auth/login")
|
||||
|
||||
|
||||
def _unauthorized(detail: str) -> HTTPException:
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=detail,
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
|
||||
async def get_current_admin(
|
||||
db: DbSession,
|
||||
credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(_bearer)],
|
||||
) -> Admin:
|
||||
if credentials is None or credentials.scheme.lower() != "bearer":
|
||||
raise _unauthorized("Not authenticated")
|
||||
try:
|
||||
payload = decode_access_token(credentials.credentials)
|
||||
admin_id = int(payload["sub"])
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise _unauthorized("Session expired. Please log in again.") from None
|
||||
except (jwt.PyJWTError, KeyError, ValueError):
|
||||
raise _unauthorized("Invalid authentication token") from None
|
||||
|
||||
admin = await db.get(Admin, admin_id)
|
||||
if admin is None or not admin.is_active:
|
||||
raise _unauthorized("Account not found or disabled")
|
||||
return admin
|
||||
|
||||
|
||||
CurrentAdmin = Annotated[Admin, Depends(get_current_admin)]
|
||||
|
||||
|
||||
def require_roles(*roles: AdminRole):
|
||||
allowed = set(roles)
|
||||
|
||||
async def checker(admin: CurrentAdmin) -> Admin:
|
||||
if admin.role not in allowed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You do not have permission to perform this action",
|
||||
)
|
||||
return admin
|
||||
|
||||
return checker
|
||||
|
||||
|
||||
# Convenience role groups
|
||||
ALL_ROLES = (AdminRole.SUPER_ADMIN, AdminRole.ADMIN, AdminRole.EDITOR)
|
||||
MANAGERS = (AdminRole.SUPER_ADMIN, AdminRole.ADMIN)
|
||||
|
||||
AnyAdmin = Annotated[Admin, Depends(require_roles(*ALL_ROLES))]
|
||||
ManagerAdmin = Annotated[Admin, Depends(require_roles(*MANAGERS))]
|
||||
SuperAdmin = Annotated[Admin, Depends(require_roles(AdminRole.SUPER_ADMIN))]
|
||||
@@ -0,0 +1,47 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import jwt
|
||||
from pwdlib import PasswordHash
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
_password_hash = PasswordHash.recommended() # Argon2id
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _password_hash.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, hashed: str) -> bool:
|
||||
return _password_hash.verify(password, hashed)
|
||||
|
||||
|
||||
# Used to keep login timing similar whether or not the email exists.
|
||||
DUMMY_HASH = hash_password("timing-equaliser-not-a-real-password")
|
||||
|
||||
|
||||
def create_access_token(subject: str, role: str) -> tuple[str, int]:
|
||||
expires_in = settings.JWT_EXPIRE_MINUTES * 60
|
||||
now = datetime.now(UTC)
|
||||
payload = {
|
||||
"sub": subject,
|
||||
"role": role,
|
||||
"type": "access",
|
||||
"iat": now,
|
||||
"exp": now + timedelta(seconds=expires_in),
|
||||
}
|
||||
token = jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||
return token, expires_in
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict:
|
||||
"""Raises jwt.PyJWTError on invalid/expired tokens."""
|
||||
payload = jwt.decode(
|
||||
token,
|
||||
settings.JWT_SECRET_KEY,
|
||||
algorithms=[settings.JWT_ALGORITHM],
|
||||
options={"require": ["sub", "exp", "iat"]},
|
||||
)
|
||||
if payload.get("type") != "access":
|
||||
raise jwt.InvalidTokenError("wrong token type")
|
||||
return payload
|
||||
Reference in New Issue
Block a user