364 lines
11 KiB
Python
364 lines
11 KiB
Python
"""
|
|
Main FastAPI application for Newzy news application.
|
|
"""
|
|
|
|
import re
|
|
from contextlib import asynccontextmanager
|
|
from datetime import timedelta
|
|
|
|
from datetime import timedelta
|
|
from fastapi import Depends, FastAPI, HTTPAuthorizationCredentials, HTTPException, status
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.security import HTTPBearer
|
|
from pydantic import ValidationError
|
|
from sqlalchemy import desc, asc
|
|
import jwt
|
|
from fastapi.responses import JSONResponse
|
|
from pydantic import ValidationError
|
|
from sqlalchemy.orm import Session
|
|
|
|
from config import settings
|
|
from db.session import engine, Base
|
|
from models.article import Article
|
|
from models.author import Author
|
|
from models.category import Category
|
|
|
|
# Import auth module
|
|
from app.auth import (
|
|
hash_password,
|
|
verify_password,
|
|
create_token,
|
|
get_current_user,
|
|
get_current_admin,
|
|
SECRET_KEY,
|
|
)
|
|
from app.models import User
|
|
from app.database import get_db
|
|
from app.schemas import (
|
|
RegisterIn,
|
|
LoginIn,
|
|
TokenOut,
|
|
MeOut,
|
|
ArticleIn,
|
|
ArticleOut,
|
|
ArticleAdminIn,
|
|
ArticleAdminOut,
|
|
PaginatedResponse,
|
|
)
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""Application lifespan event handlers."""
|
|
# On startup - create database tables
|
|
Base.metadata.create_all(bind=engine)
|
|
yield
|
|
# On shutdown - cleanup if needed
|
|
|
|
|
|
app = FastAPI(
|
|
title=settings.APP_NAME,
|
|
version=settings.APP_VERSION,
|
|
description="Newzy News Application Backend API",
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
# Exception handlers
|
|
|
|
|
|
@app.exception_handler(ValidationError)
|
|
async def validation_exception_handler(request, exc):
|
|
"""Handle Pydantic validation errors."""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
content={"detail": "Validation error", "message": str(exc)},
|
|
)
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def general_exception_handler(request, exc):
|
|
"""Handle unhandled exceptions."""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
content={"detail": "Internal server error"},
|
|
)
|
|
|
|
|
|
# Health check endpoint
|
|
@app.get("/health", tags=["Health"])
|
|
async def health_check():
|
|
"""Check if the application is running."""
|
|
return {"status": "healthy"}
|
|
|
|
|
|
# Version endpoint
|
|
@app.get("/api/v1/version", tags=["Info"])
|
|
async def get_version():
|
|
"""Get application version information."""
|
|
return {
|
|
"version": settings.APP_VERSION,
|
|
"application": settings.APP_NAME,
|
|
}
|
|
|
|
|
|
# ==================== Authentication Endpoints ====================
|
|
|
|
@app.post("/api/auth/register", response_model=TokenOut, status_code=201, tags=["Authentication"])
|
|
async def register(payload: RegisterIn, db: Session = Depends(get_db)):
|
|
"""Register new user with username and password."""
|
|
# Validate username format (alphanumeric and underscores, 3-20 chars)
|
|
if not re.match(r'^[a-zA-Z0-9_]{3,20}$', payload.username):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Invalid username: must be 3-20 alphanumeric characters or underscores"
|
|
)
|
|
|
|
# Check user doesn't already exist
|
|
existing = db.query(User).filter(User.username == payload.username).first()
|
|
if existing:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail="Username already exists"
|
|
)
|
|
|
|
# Create user with hashed password using PBKDF2
|
|
new_user = User(
|
|
username=payload.username,
|
|
password_hash=hash_password(payload.password)
|
|
)
|
|
db.add(new_user)
|
|
db.commit()
|
|
db.refresh(new_user)
|
|
|
|
return TokenOut(
|
|
token=create_token(new_user.username),
|
|
username=new_user.username,
|
|
is_admin=new_user.is_admin,
|
|
)
|
|
|
|
|
|
@app.post("/api/auth/login", response_model=TokenOut, tags=["Authentication"])
|
|
async def login(payload: LoginIn, db: Session = Depends(get_db)):
|
|
"""Authenticate user and return JWT token."""
|
|
user = db.query(User).filter(User.username == payload.username).first()
|
|
|
|
if not user or not verify_password(payload.password, user.password_hash):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid username or password"
|
|
)
|
|
|
|
return TokenOut(
|
|
token=create_token(user.username),
|
|
username=user.username,
|
|
is_admin=user.is_admin,
|
|
)
|
|
|
|
|
|
@app.post("/api/auth/logout", status_code=204, tags=["Authentication"])
|
|
async def logout(current_user: dict = Depends(get_current_user)):
|
|
"""Logout (stateless - token discarded on client side)."""
|
|
# Server-side logout is stateless with JWT - no action needed
|
|
return None
|
|
|
|
|
|
@app.get("/api/auth/me", response_model=MeOut, tags=["Authentication"])
|
|
async def get_current_user_info(
|
|
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Return current user data based on Bearer token."""
|
|
if credentials is None:
|
|
raise HTTPException(status_code=401, detail="Not authenticated")
|
|
|
|
try:
|
|
payload = jwt.decode(
|
|
credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM]
|
|
)
|
|
except jwt.PyJWTError as e:
|
|
raise HTTPException(status_code=401, detail="Invalid or expired token")
|
|
|
|
username = payload.get("sub")
|
|
user = db.query(User).filter(User.username == username).first()
|
|
|
|
if not user:
|
|
raise HTTPException(status_code=401, detail="Unknown user")
|
|
|
|
return MeOut(username=user.username, is_admin=user.is_admin)
|
|
|
|
|
|
# ==================== Admin Endpoints ====================
|
|
|
|
@app.get("/api/admin/items", response_model=PaginatedResponse, tags=["Admin"])
|
|
async def list_admin_items(
|
|
page: int = 1,
|
|
page_size: int = 20,
|
|
search: str = "",
|
|
sort_by: str = "created_at",
|
|
sort_order: str = "desc",
|
|
db: Session = Depends(get_db),
|
|
current_user: dict = Depends(get_current_admin),
|
|
):
|
|
"""
|
|
List all articles with pagination, search, and sorting.
|
|
Only accessible to admin users.
|
|
"""
|
|
# Build query for total count
|
|
query = db.query(Article).filter(Article.published == True)
|
|
|
|
# Apply search filter (case-insensitive match on title or url)
|
|
if search:
|
|
search_pattern = f"%{search}%"
|
|
query = query.filter(
|
|
(Article.title.ilike(search_pattern)) |
|
|
(Article.url.ilike(search_pattern))
|
|
)
|
|
|
|
# Apply sorting
|
|
if sort_by == "title":
|
|
order_clause = asc(Article.title) if sort_order == "asc" else desc(Article.title)
|
|
else: # default to created_at descending
|
|
order_clause = desc(Article.created_at)
|
|
|
|
query = query.order_by(order_clause)
|
|
|
|
total = query.count()
|
|
|
|
# Pagination
|
|
offset = (page - 1) * page_size
|
|
articles = query.offset(offset).limit(page_size).all()
|
|
|
|
total_pages = (total + page_size - 1) // page_size if total > 0 else 1
|
|
|
|
return {
|
|
"items": [ArticleAdminOut.model_validate(a) for a in articles],
|
|
"total": total,
|
|
"page": page,
|
|
"page_size": page_size,
|
|
"total_pages": total_pages,
|
|
}
|
|
|
|
|
|
@app.get("/api/admin/items/{item_id}", response_model=ArticleAdminOut, tags=["Admin"])
|
|
async def get_admin_item(item_id: int, db: Session = Depends(get_db), current_user: dict = Depends(get_current_admin)):
|
|
"""
|
|
Get a single article by ID. Only accessible to admin users.
|
|
"""
|
|
article = db.query(Article).filter(Article.id == item_id).first()
|
|
if not article:
|
|
raise HTTPException(status_code=404, detail="Article not found")
|
|
|
|
return ArticleAdminOut.model_validate(article)
|
|
|
|
|
|
@app.post("/api/admin/items", response_model=ArticleAdminOut, status_code=201, tags=["Admin"])
|
|
async def create_admin_item(payload: ArticleAdminIn, db: Session = Depends(get_db), current_user: dict = Depends(get_current_admin)):
|
|
"""
|
|
Create a new article. Only accessible to admin users.
|
|
"""
|
|
# Validate URL if provided
|
|
url = payload.url.strip() if payload.url else ""
|
|
if url and not re.match(r'^https?://', url):
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="Invalid URL format. Must start with http:// or https://"
|
|
)
|
|
|
|
article = Article(
|
|
title=payload.title.strip(),
|
|
url=url,
|
|
content=payload.content,
|
|
points=payload.points,
|
|
author_id=current_user["id"] if "id" in current_user else 1, # Use admin ID as default author
|
|
)
|
|
|
|
db.add(article)
|
|
db.commit()
|
|
db.refresh(article)
|
|
|
|
return ArticleAdminOut.model_validate(article)
|
|
|
|
|
|
@app.put("/api/admin/items/{item_id}", response_model=ArticleAdminOut, tags=["Admin"])
|
|
async def update_admin_item(
|
|
item_id: int,
|
|
payload: ArticleAdminIn,
|
|
db: Session = Depends(get_db),
|
|
current_user: dict = Depends(get_current_admin),
|
|
):
|
|
"""
|
|
Update an existing article. Only accessible to admin users.
|
|
"""
|
|
# Get existing article
|
|
article = db.query(Article).filter(Article.id == item_id).first()
|
|
if not article:
|
|
raise HTTPException(status_code=404, detail="Article not found")
|
|
|
|
# Validate URL if provided
|
|
url = payload.url.strip() if payload.url else ""
|
|
if url and not re.match(r'^https?://', url):
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="Invalid URL format. Must start with http:// or https://"
|
|
)
|
|
|
|
# Update fields
|
|
article.title = payload.title.strip()
|
|
article.url = url
|
|
article.content = payload.content
|
|
article.points = payload.points
|
|
|
|
db.commit()
|
|
db.refresh(article)
|
|
|
|
return ArticleAdminOut.model_validate(article)
|
|
|
|
|
|
@app.delete("/api/admin/items/{item_id}", status_code=204, tags=["Admin"])
|
|
async def delete_admin_item(
|
|
item_id: int,
|
|
db: Session = Depends(get_db),
|
|
current_user: dict = Depends(get_current_admin),
|
|
):
|
|
"""
|
|
Soft-delete an article by setting published=False.
|
|
Only accessible to admin users.
|
|
"""
|
|
article = db.query(Article).filter(Article.id == item_id).first()
|
|
if not article:
|
|
raise HTTPException(status_code=404, detail="Article not found")
|
|
|
|
# Soft delete by setting published=False
|
|
article.published = False
|
|
db.commit()
|
|
|
|
return None
|
|
|
|
@app.get("/api/articles", response_model=list[Article], tags=["Articles"])
|
|
async def list_articles(db: Session = Depends(get_db)):
|
|
"""List all articles (placeholder)."""
|
|
return []
|
|
|
|
|
|
@app.get("/api/authors", response_model=list[Author], tags=["Authors"])
|
|
async def list_authors(db: Session = Depends(get_db)):
|
|
"""List all authors (placeholder)."""
|
|
return []
|
|
|
|
|
|
@app.get("/api/categories", response_model=list[Category], tags=["Categories"])
|
|
async def list_categories(db: Session = Depends(get_db)):
|
|
"""List all categories (placeholder)."""
|
|
return []
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
uvicorn.run(
|
|
"main:app",
|
|
host="0.0.0.0",
|
|
port=8000,
|
|
reload=settings.DEBUG,
|
|
)
|