

Article Topic: FBI Investigating Apparent Hack of Its Key National Criminal Justice Database
Context: Security breach investigation affecting national criminal justice infrastructure
| Service | Purpose | Free Tier Available |
|---|---|---|
| GitHub/GitLab | Version control & CI/CD | ✅ Yes |
| Vercel/Netlify | Frontend hosting | ✅ Yes |
| Railway/Render/Fly.io | Backend API hosting | ✅ Yes |
| PostgreSQL (Supabase/Neon/PlanetScale) | Database | ✅ Yes |
| Redis (Upstash/Redis Cloud) | Caching & sessions | ✅ Yes |
| Cloudinary/AWS S3 | Image/media storage | ✅ Yes |
| SendGrid/Resend | Transactional emails | ✅ Yes |
# Required versions (check with commands below)
node --version # >= 20.0.0
python --version # >= 3.11
pnpm --version # >= 8.0.0 (or npm/yarn)
docker --version # >= 24.0.0 (for local services)
git --version # >= 2.40.0
icarax-tech-blog/
├── backend/ # FastAPI Python backend
│ ├── app/
│ │ ├── api/ # API routes
│ │ ├── core/ # Config, security, database
│ │ ├── models/ # SQLAlchemy models
│ │ ├── schemas/ # Pydantic schemas
│ │ ├── services/ # Business logic
│ │ └── utils/ # Helpers
│ ├── tests/
│ ├── alembic/ # Migrations
│ ├── pyproject.toml
│ └── Dockerfile
├── frontend/ # Next.js 14+ TypeScript frontend
│ ├── src/
│ │ ├── app/ # App Router pages
│ │ ├── components/ # React components
│ │ ├── lib/ # Utilities, API client
│ │ ├── hooks/ # Custom hooks
│ │ └── types/ # TypeScript types
│ ├── public/
│ ├── package.json
│ └── Dockerfile
├── docker-compose.yml # Local development
├── .env.example
└── README.md
cd backend
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install dependencies
pip install --upgrade pip
pip install -r requirements.txt
# Or using poetry (recommended)
poetry install
backend/pyproject.toml
[project]
name = "icarax-blog-backend"
version = "1.0.0"
description = "ICARAX Tech Blog API - FBI Database Hack Coverage"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
# Core
"fastapi==0.109.0",
"uvicorn[standard]==0.27.0",
"gunicorn==21.2.0",
# Database
"sqlalchemy==2.0.25",
"alembic==1.13.1",
"asyncpg==0.29.0",
"psycopg2-binary==2.9.9",
# Auth & Security
"python-jose[cryptography]==3.3.0",
"passlib[bcrypt]==1.7.4",
"python-multipart==0.0.6",
"bcrypt==4.1.2",
# Validation & Serialization
"pydantic==2.5.3",
"pydantic-settings==2.1.0",
"pydantic-extra-types==2.4.0",
# Caching & Tasks
"redis==5.0.1",
"celery==5.3.6",
"flower==2.0.1",
# HTTP & External APIs
"httpx==0.26.0",
"requests==2.31.0",
# Utilities
"python-dotenv==1.0.0",
"python-slugify==8.0.1",
"markdown==3.5.1",
"bleach==6.1.0",
"dateutil==2.8.2",
"pytz==2023.3",
# Monitoring
"sentry-sdk[fastapi]==1.39.1",
"prometheus-client==0.19.0",
# Testing
"pytest==7.4.4",
"pytest-asyncio==0.23.3",
"pytest-cov==4.1.0",
"httpx==0.26.0",
"faker==22.0.0",
]
[tool.poetry.group.dev.dependencies]
ruff = "0.1.15"
black = "23.12.0"
mypy = "1.7.1"
pre-commit = "3.6.0"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
cd frontend
# Install dependencies
pnpm install
# Or with npm/yarn
npm install
# yarn install
frontend/package.json
{
"name": "icarax-blog-frontend",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"type-check": "tsc --noEmit",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
},
"dependencies": {
"next": "14.2.0",
"react": "18.3.0",
"react-dom": "18.3.0",
// Styling
"tailwindcss": "3.4.0",
"clsx": "2.1.0",
"tailwind-merge": "2.2.0",
"class-variance-authority": "0.7.0",
// UI Components
"@radix-ui/react-slot": "1.0.2",
"@radix-ui/react-dropdown-menu": "2.0.6",
"@radix-ui/react-dialog": "1.0.5",
"@radix-ui/react-tooltip": "1.0.7",
"@radix-ui/react-avatar": "1.0.4",
"@radix-ui/react-separator": "1.0.3",
"@radix-ui/react-scroll-area": "1.0.5",
"lucide-react": "0.363.0",
// Content & Markdown
"react-markdown": "9.0.1",
"rehype-highlight": "7.0.0",
"rehype-raw": "7.0.0",
"rehype-slug": "6.0.0",
"remark-gfm": "4.0.0",
// Data Fetching
"@tanstack/react-query": "5.28.0",
"axios": "1.6.8",
// Forms & Validation
"react-hook-form": "7.51.0",
"@hookform/resolvers": "3.3.4",
"zod": "3.22.4",
// Utilities
"date-fns": "3.6.0",
"slugify": "1.6.6",
"reading-time": "1.5.0",
"zustand": "4.5.2"
},
"devDependencies": {
"@types/node": "20.12.0",
"@types/react": "18.3.0",
"@types/react-dom": "18.3.0",
"typescript": "5.4.0",
"eslint": "8.57.0",
"eslint-config-next": "14.2.0",
"prettier": "3.2.0",
"prettier-plugin-tailwindcss": "0.5.0",
"jest": "29.7.0",
"@testing-library/react": "14.2.0",
"@testing-library/jest-dom": "6.4.0",
"@storybook/react": "8.0.0",
"@storybook/nextjs": "8.0.0"
}
}
docker-compose.yml
version: '3.8'
services:
postgres:
image: postgres:16-alpine
container_name: icarax-postgres
environment:
POSTGRES_DB: icarax_blog
POSTGRES_USER: icarax
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-dev_password}
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
- ./backend/init-scripts:/docker-entrypoint-initdb.d
healthcheck:
test: ["CMD-SHELL", "pg_isready -U icarax -d icarax_blog"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
container_name: icarax-redis
ports:
- "6379:6379"
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
backend:
build:
context: ./backend
dockerfile: Dockerfile.dev
container_name: icarax-backend
environment:
- DATABASE_URL=postgresql+asyncpg://icarax:${POSTGRES_PASSWORD:-dev_password}@postgres:5432/icarax_blog
- REDIS_URL=redis://redis:6379/0
- ENVIRONMENT=development
ports:
- "8000:8000"
volumes:
- ./backend:/app
- /app/__pycache__
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
frontend:
build:
context: ./frontend
dockerfile: Dockerfile.dev
container_name: icarax-frontend
environment:
- NEXT_PUBLIC_API_URL=http://localhost:8000
- NEXT_PUBLIC_SITE_URL=http://localhost:3000
ports:
- "3000:3000"
volumes:
- ./frontend:/app
- /app/node_modules
- /app/.next
depends_on:
- backend
command: pnpm dev
celery-worker:
build:
context: ./backend
dockerfile: Dockerfile.dev
container_name: icarax-celery
environment:
- DATABASE_URL=postgresql+asyncpg://icarax:${POSTGRES_PASSWORD:-dev_password}@postgres:5432/icarax_blog
- REDIS_URL=redis://redis:6379/0
- ENVIRONMENT=development
volumes:
- ./backend:/app
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
command: celery -A app.core.celery_app worker --loglevel=info --concurrency=4
flower:
build:
context: ./backend
dockerfile: Dockerfile.dev
container_name: icarax-flower
environment:
- REDIS_URL=redis://redis:6379/0
ports:
- "5555:5555"
depends_on:
- redis
- celery-worker
command: celery -A app.core.celery_app flower --port=5555
volumes:
postgres_data:
redis_data:
networks:
default:
name: icarax-network
backend/app/core/config.py
"""
Core configuration for ICARAX Tech Blog Backend.
Handles environment variables, secrets, and application settings.
"""
from functools import lru_cache
from typing import List, Optional
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic_extra_types.color import Color
class Settings(BaseSettings):
"""Application settings loaded from environment variables."""
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=True,
extra="ignore",
)
# ============================================================
# Application
# ============================================================
APP_NAME: str = "ICARAX Tech Blog API"
APP_VERSION: str = "1.0.0"
ENVIRONMENT: str = Field(default="development", pattern="^(development|staging|production)$")
DEBUG: bool = False
API_V1_PREFIX: str = "/api/v1"
# ============================================================
# Server
# ============================================================
HOST: str = "0.0.0.0"
PORT: int = 8000
WORKERS: int = 4
# ============================================================
# Database
# ============================================================
DATABASE_URL: str = Field(..., description="PostgreSQL async connection string")
DATABASE_POOL_SIZE: int = 20
DATABASE_MAX_OVERFLOW: int = 10
DATABASE_POOL_TIMEOUT: int = 30
# ============================================================
# Redis
# ============================================================
REDIS_URL: str = Field(default="redis://localhost:6379/0")
REDIS_MAX_CONNECTIONS: int = 50
# ============================================================
# Security & Auth
# ============================================================
SECRET_KEY: str = Field(..., min_length=32, description="JWT signing key (min 32 chars)")
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
PASSWORD_RESET_EXPIRE_HOURS: int = 1
# Password requirements
MIN_PASSWORD_LENGTH: int = 12
REQUIRE_UPPERCASE: bool = True
REQUIRE_LOWERCASE: bool = True
REQUIRE_NUMBERS: bool = True
REQUIRE_SPECIAL_CHARS: bool = True
# ============================================================
# CORS
# ============================================================
CORS_ORIGINS: List[str] = Field(
default=["http://localhost:3000", "http://localhost:3001"],
description="Allowed CORS origins"
)
CORS_ALLOW_CREDENTIALS: bool = True
CORS_ALLOW_METHODS: List[str] = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
CORS_ALLOW_HEADERS: List[str] = ["*"]
# ============================================================
# Email (SendGrid/Resend)
# ============================================================
EMAIL_PROVIDER: str = Field(default="sendgrid", pattern="^(sendgrid|resend|smtp)$")
SENDGRID_API_KEY: Optional[str] = None
RESEND_API_KEY: Optional[str] = None
SMTP_HOST: Optional[str] = None
SMTP_PORT: int = 587
SMTP_USER: Optional[str] = None
SMTP_PASSWORD: Optional[str] = None
SMTP_TLS: bool = True
EMAIL_FROM: str = "noreply@icarax.tech"
EMAIL_FROM_NAME: str = "ICARAX Tech Blog"
# ============================================================
# Media Storage (Cloudinary/S3)
# ============================================================
MEDIA_PROVIDER: str = Field(default="cloudinary", pattern="^(cloudinary|s3|local)$")
CLOUDINARY_CLOUD_NAME: Optional[str] = None
CLOUDINARY_API_KEY: Optional[str] = None
CLOUDINARY_API_SECRET: Optional[str] = None
AWS_ACCESS_KEY_ID: Optional[str] = None
AWS_SECRET_ACCESS_KEY: Optional[str] = None
AWS_S3_BUCKET: Optional[str] = None
AWS_S3_REGION: str = "us-east-1"
LOCAL_MEDIA_PATH: str = "./media"
LOCAL_MEDIA_URL: str = "/media"
# ============================================================
# External APIs
# ============================================================
NEWS_API_KEY: Optional[str] = None
GITHUB_TOKEN: Optional[str] = None
# ============================================================
# Monitoring
# ============================================================
SENTRY_DSN: Optional[str] = None
SENTRY_TRACES_SAMPLE_RATE: float = 0.1
SENTRY_PROFILES_SAMPLE_RATE: float = 0.1
# ============================================================
# Rate Limiting
# ============================================================
RATE_LIMIT_REQUESTS: int = 100
RATE_LIMIT_WINDOW_SECONDS: int = 60
# ============================================================
# Pagination
# ============================================================
DEFAULT_PAGE_SIZE: int = 20
MAX_PAGE_SIZE: int = 100
# ============================================================
# Article Specific
# ============================================================
ARTICLE_SLUG_MAX_LENGTH: int = 100
ARTICLE_EXCERPT_MAX_LENGTH: int = 300
FEATURED_IMAGE_MAX_SIZE_MB: int = 5
ALLOWED_IMAGE_TYPES: List[str] = ["image/jpeg", "image/png", "image/webp", "image/avif"]
@field_validator("CORS_ORIGINS", mode="before")
@classmethod
def parse_cors_origins(cls, v: str | List[str]) -> List[str]:
if isinstance(v, str):
return [origin.strip() for origin in v.split(",")]
return v
@property
def is_development(self) -> bool:
return self.ENVIRONMENT == "development"
@property
def is_production(self) -> bool:
return self.ENVIRONMENT == "production"
@lru_cache
def get_settings() -> Settings:
"""Cached settings instance for dependency injection."""
return Settings()
# Global settings instance
settings = get_settings()
backend/app/core/database.py
"""
Database configuration and session management.
Uses SQLAlchemy 2.0 async patterns with proper connection pooling.
"""
from contextlib import asynccontextmanager
from typing import AsyncGenerator, Optional
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.pool import NullPool
from sqlalchemy import event, text
from app.core.config import settings
class Base(DeclarativeBase):
"""Base class for all SQLAlchemy models."""
pass
class DatabaseManager:
"""Manages database connections and sessions."""
def __init__(self) -> None:
self._engine: Optional[AsyncEngine] = None
self._session_factory: Optional[async_sessionmaker[AsyncSession]] = None
def init_engine(self) -> AsyncEngine:
"""Initialize the async database engine with connection pooling."""
if self._engine is not None:
return self._engine
# Use NullPool for testing, QueuePool for production
poolclass = NullPool if settings.is_development else None
self._engine = create_async_engine(
settings.DATABASE_URL,
echo=settings.DEBUG,
poolclass=poolclass,
pool_size=settings.DATABASE_POOL_SIZE if not settings.is_development else 5,
max_overflow=settings.DATABASE_MAX_OVERFLOW if not settings.is_development else 0,
pool_timeout=settings.DATABASE_POOL_TIMEOUT,
pool_pre_ping=True, # Verify connections before use
connect_args={
"server_settings": {
"application_name": "icarax_blog",
"jit": "off", # Disable JIT for better latency
},
"command_timeout": 60,
} if not settings.is_development else {},
)
# Add connection event listeners for monitoring
@event.listens_for(self._engine.sync_engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
"""Set PostgreSQL-specific settings on connect."""
pass # PostgreSQL doesn't need PRAGMA
return self._engine
def get_session_factory(self) -> async_sessionmaker[AsyncSession]:
"""Get or create the async session factory."""
if self._session_factory is None:
engine = self.init_engine()
self._session_factory = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
autocommit=False,
)
return self._session_factory
@asynccontextmanager
async def session(self) -> AsyncGenerator[AsyncSession, None]:
"""Provide a transactional scope for database operations."""
session_factory = self.get_session_factory()
async with session_factory() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
async def close(self) -> None:
"""Close all database connections."""
if self._engine:
await self._engine.dispose()
self._engine = None
self._session_factory = None
async def health_check(self) -> bool:
"""Check database connectivity."""
try:
async with self.session() as session:
await session.execute(text("SELECT 1"))
return True
except Exception:
return False
# Global database manager instance
db_manager = DatabaseManager()
# Dependency for FastAPI
async def get_db() -> AsyncGenerator[AsyncSession, None]:
"""FastAPI dependency for database sessions."""
async with db_manager.session() as session:
yield session
# Initialize on module import (for Alembic)
def init_db() -> None:
"""Initialize database engine."""
db_manager.init_engine()
backend/app/core/security.py
"""
Security utilities: password hashing, JWT tokens, API keys.
"""
import secrets
import hashlib
from datetime import datetime, timedelta, UTC
from typing import Optional, Dict, Any
from jose import jwt, JWTError
from passlib.context import CryptContext
from pydantic import SecretStr
from app.core.config import settings
# Password hashing context
pwd_context = CryptContext(
schemes=["bcrypt"],
deprecated="auto",
bcrypt__rounds=12, # Adjust based on hardware (12 = ~250ms)
)
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verify a plain password against its hash."""
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
"""Hash a password using bcrypt."""
return pwd_context.hash(password)
def generate_secure_token(length: int = 32) -> str:
"""Generate a cryptographically secure random token."""
return secrets.token_urlsafe(length)
def generate_api_key(prefix: str = "icarax") -> str:
"""Generate an API key with prefix."""
return f"{prefix}_{secrets.token_urlsafe(24)}"
def hash_api_key(api_key: str) -> str:
"""Hash an API key for storage (SHA-256)."""
return hashlib.sha256(api_key.encode()).hexdigest()
def create_access_token(
subject: str,
expires_delta: Optional[timedelta] = None,
additional_claims: Optional[Dict[str, Any]] = None,
) -> str:
"""
Create a JWT access token.
Args:
subject: User ID or identifier
expires_delta: Custom expiration (default from settings)
additional_claims: Extra claims to include
Returns:
Encoded JWT token
"""
if expires_delta:
expire = datetime.now(UTC) + expires_delta
else:
expire = datetime.now(UTC) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
claims = {
"sub": str(subject),
"exp": expire,
"iat": datetime.now(UTC),
"type": "access",
"jti": generate_secure_token(16), # JWT ID for revocation
}
if additional_claims:
claims.update(additional_claims)
return jwt.encode(claims, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
def create_refresh_token(subject: str) -> str:
"""Create a long-lived refresh token."""
expire = datetime.now(UTC) + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
claims = {
"sub": str(subject),
"exp": expire,
"iat": datetime.now(UTC),
"type": "refresh",
"jti": generate_secure_token(16),
}
return jwt.encode(claims, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
def decode_token(token: str) -> Optional[Dict[str, Any]]:
"""
Decode and validate a JWT token.
Returns:
Token payload if valid, None if invalid/expired
"""
try:
payload = jwt.decode(
token,
settings.SECRET_KEY,
algorithms=[settings.ALGORITHM],
options={"verify_aud": False},
)
return payload
except JWTError:
return None
def get_token_expiry(token: str) -> Optional[datetime]:
"""Get expiration datetime from token without full validation."""
try:
payload = jwt.get_unverified_claims(token)
exp = payload.get("exp")
if exp:
return datetime.fromtimestamp(exp, UTC)
except Exception:
pass
return None
class TokenData:
"""Parsed token data container."""
def __init__(self, payload: Dict[str, Any]):
self.user_id: str = payload.get("sub", "")
self.token_type: str = payload.get("type", "")
self.expires_at: datetime = datetime.fromtimestamp(payload.get("exp", 0), UTC)
self.issued_at: datetime = datetime.fromtimestamp(payload.get("iat", 0), UTC)
self.jti: str = payload.get("jti", "")
self.scopes: list[str] = payload.get("scopes", [])
self.raw: Dict[str, Any] = payload
@property
def is_expired(self) -> bool:
return datetime.now(UTC) >= self.expires_at
@property
def is_access_token(self) -> bool:
return self.token_type == "access"
@property
def is_refresh_token(self) -> bool:
return self.token_type == "refresh"
def parse_token(token: str) -> Optional[TokenData]:
"""Parse token into structured data."""
payload = decode_token(token)
if payload:
return TokenData(payload)
return None
backend/app/models/article.py
"""
SQLAlchemy models for articles, categories, tags, and authors.
"""
import enum
from datetime import datetime, UTC
from typing import Optional, List
from uuid import uuid4
from sqlalchemy import (
String, Text, DateTime, ForeignKey, Enum, Index, UniqueConstraint,
Integer, Boolean, BigInteger, func, select
)
from sqlalchemy.dialects.postgresql import UUID, JSONB, TSVECTOR
from sqlalchemy.orm import Mapped, mapped_column, relationship, declared_attr
from app.core.database import Base
class ArticleStatus(str, enum.Enum):
"""Publication status of an article."""
DRAFT = "draft"
PENDING_REVIEW = "pending_review"
SCHEDULED = "scheduled"
PUBLISHED = "published"
ARCHIVED = "archived"
REJECTED = "rejected"
class Article(Base):
"""Main article model with full-text search support."""
__tablename__ = "articles"
__table_args__ = (
Index("ix_articles_status_published", "status", "published_at"),
Index("ix_articles_author_status", "author_id", "status"),
Index("ix_articles_slug", "slug", unique=True),
Index("ix_articles_search_vector", "search_vector", postgresql_using="gin"),
{"comment": "Tech blog articles with full-text search"},
)
# Primary key
id: Mapped[UUID] = mapped_column(
UUID(as_uuid=True),
primary_key=True,
default=uuid4,
comment="Unique article identifier"
)
# Content fields
title: Mapped[str] = mapped_column(
String(255),
nullable=False,
index=True,
comment="Article title"
)
slug: Mapped[str] = mapped_column(
String(255),
nullable=False,
unique=True,
index=True,
comment="URL-friendly slug"
)
excerpt: Mapped[Optional[str]] = mapped_column(
Text,
nullable=True,
comment="Short description for previews"
)
content: Mapped[str] = mapped_column(
Text,
nullable=False,
comment="Full article content (Markdown)"
)
content_html: Mapped[Optional[str]] = mapped_column(
Text,
nullable=True,
comment="Rendered HTML content"
)
# SEO fields
meta_title: Mapped[Optional[str]] = mapped_column(
String(60),
nullable=True,
comment="SEO title (max 60 chars)"
)
meta_description: Mapped[Optional[str]] = mapped_column(
String(160),
nullable=True,
comment="SEO description (max 160 chars)"
)
canonical_url: Mapped[Optional[str]] = mapped_column(
String(500),
nullable=True,
comment="Canonical URL for syndicated content"
)
# Status & publishing
status: Mapped[ArticleStatus] = mapped_column(
Enum(ArticleStatus, native_enum=False),
default=ArticleStatus.DRAFT,
nullable=False,
index=True,
comment="Publication status"
)
is_featured: Mapped[bool] = mapped_column(
Boolean,
default=False,
nullable=False,
index=True,
comment="Featured article flag"
)
is_breaking_news: Mapped[bool] = mapped_column(
Boolean,
default=False,
nullable=False,
comment="Breaking news banner"
)
published_at: Mapped[Optional[datetime]] = mapped_column(
DateTime(timezone=True),
nullable=True,
index=True,
comment="Publication timestamp"
)
scheduled_at: Mapped[Optional[datetime]] = mapped_column(
DateTime(timezone=True),
nullable=True,
index=True,
comment="Scheduled publication time"
)
# Media
featured_image_url: Mapped[Optional[str]] = mapped_column(
String(500),
nullable=True,
comment="Featured image URL"
)
featured_image_alt: Mapped[Optional[str]] = mapped_column(
String(255),
nullable=True,
comment="Alt text for featured image"
)
featured_image_caption: Mapped[Optional[str]] = mapped_column(
Text,
nullable=True,
comment="Image caption/credit"
)
# Metrics
view_count: Mapped[int] = mapped_column(
Integer,
default=0,
nullable=False,
comment="Page view count"
)
read_time_minutes: Mapped[int] = mapped_column(
Integer,
default=0,
nullable=False,
comment="Estimated reading time"
)
word_count: Mapped[int] = mapped_column(
Integer,
default=0,
nullable=False,
comment="Word count"
)
# Relationships
author_id: Mapped[UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("users.id", ondelete="RESTRICT"),
nullable=False,
index=True,
comment="Author reference"
)
category_id: Mapped[Optional[UUID]] = mapped_column(
UUID(as_uuid=True),
ForeignKey("categories.id", ondelete="SET NULL"),
nullable=True,
index=True,
comment="Category reference"
)
# Relationships (defined as strings to avoid circular imports)
author: Mapped["User"] = relationship(
"User",
back_populates="articles",
lazy="selectin"
)
category: Mapped[Optional["Category"]] = relationship(
"Category",
back_populates="articles",
lazy="selectin"
)
tags: Mapped[List["Tag"]] = relationship(
"Tag",
secondary="article_tags",
back_populates="articles",
lazy="selectin"
)
comments: Mapped[List["Comment"]] = relationship(
"Comment",
back_populates="article",
lazy="dynamic",
cascade="all
---
## Next Steps
1. **Get API Access** - Sign up at the official website
2. **Try the Examples** - Run the code snippets above
3. **Read the Docs** - Check official documentation
4. **Join Communities** - Discord, Reddit, GitHub discussions
5. **Experiment** - Build something cool!
## Further Reading
- [TechCrunch AI](https://techcrunch.com/category/artificial-intelligence/)
- [The Verge](https://www.theverge.com/technology)
- [Wired AI](https://www.wired.com/tag/artificial-intelligence/)
- [Medium AI](https://medium.com/topic/artificial-intelligence)
**Source:** [Security Week AI](https://www.securityweek.com/fbi-investigating-apparent-hack-of-its-key-national-criminal-justice-database-ap-source-says/)
---
*Follow ICARAX for more AI insights and tutorials.*
