Initial commit: WealthWise financial analytics platform
This commit is contained in:
1
backend/app/core/__init__.py
Normal file
1
backend/app/core/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# Core package - configuration and database
|
||||
129
backend/app/core/config.py
Normal file
129
backend/app/core/config.py
Normal file
@@ -0,0 +1,129 @@
|
||||
"""WealthWise application configuration management.
|
||||
|
||||
This module provides centralized configuration management using Pydantic Settings v2.
|
||||
Configuration values are loaded from environment variables and .env files.
|
||||
"""
|
||||
|
||||
from functools import lru_cache
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from pydantic import Field, field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""Application settings management.
|
||||
|
||||
All configuration values are loaded from environment variables.
|
||||
The .env file is automatically loaded when present.
|
||||
System environment variables override values in .env.
|
||||
|
||||
Attributes:
|
||||
PROJECT_NAME: Application name for documentation and logging
|
||||
API_V1_STR: Base path for API v1 endpoints
|
||||
VERSION: Application version string
|
||||
DATABASE_URL: PostgreSQL connection string (Supabase Transaction Pooler format)
|
||||
SUPABASE_JWT_SECRET: JWT secret for Supabase authentication
|
||||
DEBUG: Enable debug mode (default: False)
|
||||
CORS_ORIGINS: Comma-separated list of allowed CORS origins
|
||||
"""
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore", # Allow extra env vars without raising errors
|
||||
case_sensitive=True,
|
||||
)
|
||||
|
||||
# Application Info
|
||||
PROJECT_NAME: str = Field(default="WealthWise", description="Application name")
|
||||
API_V1_STR: str = Field(default="/api/v1", description="API v1 base path")
|
||||
VERSION: str = Field(default="1.0.0", description="Application version")
|
||||
|
||||
# Security
|
||||
SECRET_KEY: str = Field(
|
||||
default="dev-secret-key-change-in-production",
|
||||
description="Secret key for JWT signing",
|
||||
)
|
||||
ALGORITHM: str = Field(
|
||||
default="HS256",
|
||||
description="JWT signing algorithm",
|
||||
)
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = Field(
|
||||
default=30,
|
||||
description="JWT token expiration in minutes",
|
||||
)
|
||||
|
||||
# Database - Local PostgreSQL (Docker)
|
||||
DATABASE_URL: str = Field(
|
||||
default="postgresql+asyncpg://postgres:postgres@localhost:5432/wealthwise",
|
||||
description="PostgreSQL async connection string",
|
||||
)
|
||||
|
||||
# Database Pool Configuration
|
||||
DB_POOL_SIZE: int = Field(default=20, ge=1, le=100, description="Connection pool size")
|
||||
DB_MAX_OVERFLOW: int = Field(default=10, ge=0, le=50, description="Max overflow connections")
|
||||
DB_POOL_PRE_PING: bool = Field(
|
||||
default=True,
|
||||
description="Verify connections before using from pool",
|
||||
)
|
||||
DB_ECHO: bool = Field(default=False, description="Echo SQL queries to stdout")
|
||||
|
||||
# API Configuration
|
||||
DEBUG: bool = Field(default=False, description="Debug mode")
|
||||
CORS_ORIGINS: str = Field(
|
||||
default="http://localhost:5173,http://localhost:3000",
|
||||
description="Comma-separated list of allowed CORS origins",
|
||||
)
|
||||
|
||||
# Logging
|
||||
LOG_LEVEL: str = Field(default="INFO", pattern="^(DEBUG|INFO|WARNING|ERROR|CRITICAL)$")
|
||||
|
||||
@property
|
||||
def cors_origins_list(self) -> list[str]:
|
||||
"""Parse CORS_ORIGINS string into a list.
|
||||
|
||||
Returns:
|
||||
List of origin strings
|
||||
"""
|
||||
return [origin.strip() for origin in self.CORS_ORIGINS.split(",") if origin.strip()]
|
||||
|
||||
@field_validator("DATABASE_URL")
|
||||
@classmethod
|
||||
def validate_database_url(cls, v: Optional[str]) -> Any:
|
||||
"""Validate and ensure proper asyncpg driver in DATABASE_URL.
|
||||
|
||||
Args:
|
||||
v: Database URL string
|
||||
|
||||
Returns:
|
||||
Validated database URL with asyncpg driver
|
||||
|
||||
Raises:
|
||||
ValueError: If URL format is invalid
|
||||
"""
|
||||
if not v:
|
||||
raise ValueError("DATABASE_URL cannot be empty")
|
||||
|
||||
# Ensure asyncpg driver is used
|
||||
if v.startswith("postgresql://"):
|
||||
v = v.replace("postgresql://", "postgresql+asyncpg://", 1)
|
||||
elif not v.startswith("postgresql+asyncpg://"):
|
||||
raise ValueError(
|
||||
"DATABASE_URL must use postgresql+asyncpg:// driver for async support"
|
||||
)
|
||||
|
||||
return v
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def get_settings() -> Settings:
|
||||
"""Get cached settings instance.
|
||||
|
||||
This function uses LRU caching to avoid re-reading configuration
|
||||
on every call. Settings are loaded once at application startup.
|
||||
|
||||
Returns:
|
||||
Settings instance with all configuration values
|
||||
"""
|
||||
return Settings()
|
||||
123
backend/app/core/db.py
Normal file
123
backend/app/core/db.py
Normal file
@@ -0,0 +1,123 @@
|
||||
"""WealthWise database configuration and session management.
|
||||
|
||||
This module provides:
|
||||
- Async SQLAlchemy engine with connection pooling
|
||||
- Async session factory for database operations
|
||||
- FastAPI dependency for session injection
|
||||
- Connection health checking utilities
|
||||
"""
|
||||
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncEngine,
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
from sqlalchemy.pool import NullPool
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession as SQLModelAsyncSession
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
# Create async engine with connection pooling
|
||||
# Supabase Transaction Pooler (port 6543) supports high concurrency
|
||||
engine: AsyncEngine = create_async_engine(
|
||||
settings.DATABASE_URL,
|
||||
echo=settings.DB_ECHO,
|
||||
pool_size=settings.DB_POOL_SIZE,
|
||||
max_overflow=settings.DB_MAX_OVERFLOW,
|
||||
pool_pre_ping=settings.DB_POOL_PRE_PING,
|
||||
# Connection pool settings for production
|
||||
pool_recycle=3600, # Recycle connections after 1 hour
|
||||
pool_timeout=30, # Wait up to 30 seconds for available connection
|
||||
# Async-specific settings
|
||||
future=True,
|
||||
)
|
||||
|
||||
# Create async session factory
|
||||
# expire_on_commit=False allows accessing attributes after session closes
|
||||
AsyncSessionLocal = async_sessionmaker(
|
||||
engine,
|
||||
class_=SQLModelAsyncSession,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
autocommit=False,
|
||||
)
|
||||
|
||||
|
||||
async def get_session() -> AsyncGenerator[SQLModelAsyncSession, None]:
|
||||
"""FastAPI dependency that provides an async database session.
|
||||
|
||||
This generator yields a database session for use in API endpoints.
|
||||
It automatically handles transaction rollback on errors and ensures
|
||||
proper session cleanup.
|
||||
|
||||
Usage:
|
||||
@app.get("/items")
|
||||
async def get_items(session: AsyncSession = Depends(get_session)):
|
||||
result = await session.execute(select(Item))
|
||||
return result.scalars().all()
|
||||
|
||||
Yields:
|
||||
AsyncSession: Database session instance
|
||||
|
||||
Raises:
|
||||
SQLAlchemyError: Re-raised after rollback if database error occurs
|
||||
"""
|
||||
session: SQLModelAsyncSession = AsyncSessionLocal()
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except SQLAlchemyError as e:
|
||||
await session.rollback()
|
||||
raise e
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
|
||||
async def close_engine() -> None:
|
||||
"""Close all database connections.
|
||||
|
||||
Call this during application shutdown to properly release
|
||||
all database connections in the pool.
|
||||
"""
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
async def check_db_connection() -> bool:
|
||||
"""Verify database connectivity by executing a simple query.
|
||||
|
||||
Returns:
|
||||
True if database is accessible, False otherwise
|
||||
"""
|
||||
try:
|
||||
async with AsyncSessionLocal() as session:
|
||||
result = await session.execute("SELECT 1")
|
||||
return result.scalar() == 1
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# For Alembic migrations (sync operations)
|
||||
def create_sync_engine():
|
||||
"""Create synchronous engine for Alembic migrations.
|
||||
|
||||
Returns:
|
||||
SyncEngine: Synchronous SQLAlchemy engine
|
||||
"""
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
# Convert async URL to sync URL
|
||||
sync_url = settings.DATABASE_URL.replace(
|
||||
"postgresql+asyncpg://", "postgresql://"
|
||||
)
|
||||
|
||||
return create_engine(
|
||||
sync_url,
|
||||
echo=settings.DB_ECHO,
|
||||
)
|
||||
112
backend/app/core/security.py
Normal file
112
backend/app/core/security.py
Normal file
@@ -0,0 +1,112 @@
|
||||
"""Security utilities for authentication and password management.
|
||||
|
||||
This module provides:
|
||||
- Password hashing and verification using bcrypt
|
||||
- JWT token creation and validation
|
||||
- Security-related helper functions
|
||||
"""
|
||||
|
||||
import bcrypt
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
from jose import jwt
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verify a plain password against a hashed password.
|
||||
|
||||
Args:
|
||||
plain_password: The plain text password to verify
|
||||
hashed_password: The bcrypt hashed password from database
|
||||
|
||||
Returns:
|
||||
True if password matches, False otherwise
|
||||
"""
|
||||
return bcrypt.checkpw(
|
||||
plain_password.encode('utf-8'),
|
||||
hashed_password.encode('utf-8')
|
||||
)
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
"""Generate a bcrypt hash from a plain password.
|
||||
|
||||
Args:
|
||||
password: The plain text password to hash
|
||||
|
||||
Returns:
|
||||
Bcrypt hashed password string
|
||||
"""
|
||||
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
||||
|
||||
|
||||
def create_access_token(
|
||||
data: dict[str, Any],
|
||||
expires_delta: Optional[timedelta] = None,
|
||||
) -> str:
|
||||
"""Create a JWT access token.
|
||||
|
||||
This function creates a JWT token with the provided data payload.
|
||||
The token includes an expiration time and is signed with the
|
||||
application's secret key.
|
||||
|
||||
Args:
|
||||
data: Dictionary of claims to encode in the token (e.g., {"sub": user_id})
|
||||
expires_delta: Optional custom expiration time. Defaults to settings.ACCESS_TOKEN_EXPIRE_MINUTES
|
||||
|
||||
Returns:
|
||||
Encoded JWT string
|
||||
|
||||
Example:
|
||||
>>> token = create_access_token({"sub": str(user.id)})
|
||||
>>> # Use token in Authorization: Bearer <token> header
|
||||
"""
|
||||
to_encode = data.copy()
|
||||
|
||||
# Calculate expiration time
|
||||
if expires_delta:
|
||||
expire = datetime.now(timezone.utc) + expires_delta
|
||||
else:
|
||||
expire = datetime.now(timezone.utc) + timedelta(
|
||||
minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
|
||||
)
|
||||
|
||||
# Add expiration and issued at claims
|
||||
to_encode.update({
|
||||
"exp": expire,
|
||||
"iat": datetime.now(timezone.utc),
|
||||
"type": "access",
|
||||
})
|
||||
|
||||
# Encode the JWT
|
||||
encoded_jwt = jwt.encode(
|
||||
to_encode,
|
||||
settings.SECRET_KEY,
|
||||
algorithm=settings.ALGORITHM,
|
||||
)
|
||||
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict[str, Any]:
|
||||
"""Decode and validate a JWT access token.
|
||||
|
||||
Args:
|
||||
token: The JWT string to decode
|
||||
|
||||
Returns:
|
||||
Dictionary containing the token payload
|
||||
|
||||
Raises:
|
||||
jwt.JWTError: If token is invalid or expired
|
||||
"""
|
||||
return jwt.decode(
|
||||
token,
|
||||
settings.SECRET_KEY,
|
||||
algorithms=[settings.ALGORITHM],
|
||||
)
|
||||
Reference in New Issue
Block a user