final commit

This commit is contained in:
Newzy Developer committed 2026-10-30 12:10:49 +00:00
1 parent 0ffbba3bed
commit 7b242b8685
39 files changed
+5524 -65

No files matched your search

+3
View File
@@ -27,3 +27,6 @@ Dockerfile
htmlcov/
.pytest_cache/
.coverage.*
# Development data
data/
+28
View File
@@ -0,0 +1,28 @@
"""
Newzy application backend app module.
"""
from .auth import (
PBKDF2_ITERATIONS,
TOKEN_TTL_SECONDS,
create_token,
get_current_user,
hash_password,
SECRET_KEY,
verify_password,
)
from .database import get_db, utcnow
from .models import User
__all__ = [
"User",
"hash_password",
"verify_password",
"create_token",
"get_current_user",
"get_db",
"utcnow",
"SECRET_KEY",
"TOKEN_TTL_SECONDS",
"PBKDF2_ITERATIONS",
]
+115
View File
@@ -0,0 +1,115 @@
"""
Authentication module for Newzy application.
Provides password hashing (PBKDF2), JWT token creation/verification, and
dependencies for Bearer token authentication.
"""
import hashlib
import os
import secrets
import time
from typing import Optional
import jwt
from fastapi import Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session
from . import models
from .database import get_db
# JWT signing key - override with HN_SECRET_KEY in production
SECRET_KEY = os.environ.get("HN_SECRET_KEY", "newzy-dev-secret-change-me")
ALGORITHM = "HS256"
TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days
# Password hashing iterations - minimum 120,000 for security
PBKDF2_ITERATIONS = 120_000
_bearer = HTTPBearer(auto_error=False)
def hash_password(password: str) -> str:
"""Generate password hash with random salt using PBKDF2-HMAC-SHA256."""
salt = secrets.token_hex(16)
digest = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
).hex()
return f"{salt}${digest}"
def verify_password(password: str, stored: str) -> bool:
"""Verify password against stored hash."""
try:
salt, digest = stored.split("$", 1)
except ValueError:
return False
candidate = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
).hex()
return secrets.compare_digest(candidate, digest)
def create_token(username: str) -> str:
"""Create JWT token for user with 7-day expiry."""
now = int(time.time())
payload = {
"sub": username,
"iat": now,
"exp": now + TOKEN_TTL_SECONDS
}
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
def get_current_user(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer),
db: Session = Depends(get_db),
) -> dict:
"""Validate Bearer token and return user data."""
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(models.User).filter(models.User.username == username).first()
if not user:
raise HTTPException(status_code=401, detail="Unknown user")
return user.model_dump(mode="json")
def get_current_admin(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer),
db: Session = Depends(get_db),
) -> dict:
"""Validate Bearer token and verify user has admin privileges."""
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(models.User).filter(models.User.username == username).first()
if not user:
raise HTTPException(status_code=401, detail="Unknown user")
if not user.is_admin:
raise HTTPException(status_code=403, detail="Admin access required")
return user.model_dump(mode="json")
+27
View File
@@ -0,0 +1,27 @@
"""
Database utilities for authentication.
"""
from sqlalchemy.orm import Session
from .models import Base
def utcnow():
"""Return current UTC timestamp for database columns."""
from datetime import datetime
return datetime.utcnow()
def get_db() -> Session:
"""
Dependency factory that yields a database session.
Should be imported and used with Depends(get_db) in endpoint functions.
"""
from db.session import SessionLocal
db = SessionLocal()
try:
yield db
finally:
db.close()
+22
View File
@@ -0,0 +1,22 @@
"""
Database models for authentication and core Newzy functionality.
"""
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .database import Base, utcnow
class User(Base):
"""User model for authentication."""
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
username: Mapped[str] = mapped_column(String(60), unique=True, index=True)
password_hash: Mapped[str] = mapped_column(String(128))
is_admin: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
+88
View File
@@ -0,0 +1,88 @@
"""
Pydantic schemas for authentication and admin endpoints.
"""
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class RegisterIn(BaseModel):
"""Request schema for user registration."""
username: str = Field(
..., min_length=3, max_length=60, pattern=r"^[a-zA-Z0-9_]{3,20}$",
description="Username (alphanumeric and underscores only, 3-20 chars)"
)
password: str = Field(..., min_length=8, max_length=128, description="Password")
class LoginIn(BaseModel):
"""Request schema for user login."""
username: str = Field(..., min_length=3, max_length=60, description="Username")
password: str = Field(..., min_length=8, max_length=128, description="Password")
class TokenOut(BaseModel):
"""Response schema for token generation (login/register)."""
token: str
username: str
is_admin: bool = False
class MeOut(BaseModel):
"""Response schema for current user info."""
username: str
is_admin: bool = False
# Article schemas
class ArticleBase(BaseModel):
"""Base article schema with common fields."""
title: str = Field(..., min_length=1, max_length=300)
url: str = Field("", max_length=500)
content: str = Field(..., description="Rich text content")
points: int = Field(0, ge=0, le=1000000)
class ArticleIn(ArticleBase):
"""Schema for creating/updating articles."""
pass
class ArticleOut(ArticleBase):
"""Schema for article output data."""
id: int
author_id: int
created_at: datetime
class Config:
from_attributes = True
class ArticleAdminIn(ArticleBase):
"""Schema for admin create/update operations."""
title: str = Field(..., min_length=1, max_length=300)
url: str = Field("", max_length=500)
content: str = Field(..., description="Rich text content")
points: int = Field(0, ge=0, le=1000000)
class ArticleAdminOut(ArticleBase):
"""Schema for admin article output data."""
id: int
author_id: int
created_at: datetime
class Config:
from_attributes = True
# Pagination response schema
class PaginatedResponse(BaseModel):
"""Standard pagination response structure."""
items: list[ArticleAdminOut]
total: int
page: int
page_size: int
total_pages: int
+282 -3
View File
@@ -2,11 +2,20 @@
Main FastAPI application for Newzy news application.
"""
import re
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, status
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
@@ -14,6 +23,29 @@ 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):
@@ -69,8 +101,255 @@ async def get_version():
}
# Placeholder routes for future implementation
# (Models are defined but API endpoints will be added in subsequent milestones)
# ==================== 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__":
+4
View File
@@ -5,6 +5,10 @@ sqlalchemy>=2.0.0
pydantic>=2.5.0
pydantic-settings>=2.1.0
python-multipart>=0.0.6
# JWT and authentication dependencies
python-jose[cryptography]>=3.3.0
# Testing dependencies
pytest>=7.4.0
pytest-asyncio>=0.23.0
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""
Seed script to create an admin user in the Newzy database.
Run this once after initial setup.
Usage:
python seed_admin.py
# or with custom username:
python seed_admin.py --username my_admin_user
"""
import os
import sys
from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import Session
# Add the project root to the path
sys.path.insert(0, os.path.dirname(__file__))
from db.session import engine, Base, get_db
from models.author import Author # Import to check if tables exist
from app.models import User
from app.auth import hash_password, SECRET_KEY
def main():
"""Create admin user in the database."""
# Check for command line args
username = "admin"
password = os.environ.get("ADMIN_PASSWORD", "admin123")
if len(sys.argv) > 1:
username = sys.argv[1]
print(f"Creating admin user: {username}")
print(f"Password: {password}")
print()
# Create engine and session
db_url = os.environ.get("DATABASE_URL", "sqlite:///data/db/newzy.db")
print(f"Connecting to database at: {db_url}")
try:
# Check if database exists
with Session(engine) as session:
tables = inspect(engine).get_table_names()
if not tables:
print("Error: No tables found in database. Please initialize the database first.")
return
if "users" not in tables:
print("Error: Users table not found. Please create the database schema first.")
print("Run: python -c 'from db.session import engine, Base; Base.metadata.create_all(engine)'")
return
# Check if user already exists
existing_user = session.query(User).filter(User.username == username).first()
if existing_user:
is_admin = getattr(existing_user, "is_admin", False)
print(f"User '{username}' already exists.")
if is_admin:
print("This user is already an admin. Nothing to do.")
sys.exit(0)
else:
print(f"Upgrading user to admin...")
existing_user.is_admin = True
session.commit()
print(f"User '{username}' is now an admin.")
sys.exit(0)
# Create new admin user
print("Creating new admin user...")
new_user = User(
username=username,
password_hash=hash_password(password),
is_admin=True
)
session.add(new_user)
session.commit()
print(f"Successfully created admin user '{username}'!")
print("You can now login with username:", username)
print("Password: ", password)
print("\nNote: In production, change the default password immediately.")
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
+184
View File
@@ -0,0 +1,184 @@
"""
Authentication tests for Newzy application.
"""
import pytest
from fastapi.testclient import TestClient
@pytest.fixture
def auth_client(test_db):
"""Test client with authentication setup."""
from db.session import SessionLocal
from app.models import User
db = SessionLocal()
# Create test user
test_user = User(
username="testuser",
password_hash="$a1b2c3d4e5f678901234567890123456789012345678901234567890abcdef$hash1234567890"
)
# Insert test user into database
db.add(test_user)
db.commit()
yield TestClient(app, raise_server_exceptions=True)
db.close()
@pytest.fixture
def valid_password():
"""Password for hashing tests."""
return "securepassword123"
@pytest.fixture
def hashed_password(valid_password):
"""Hashed version of test password."""
from app.auth import hash_password
return hash_password(valid_password)
def test_register_user(auth_client, valid_password):
"""Test user registration creates account."""
response = auth_client.post("/api/auth/register", json={
"username": "newuser123",
"password": valid_password
})
assert response.status_code == 201
data = response.json()
assert "token" in data
assert data["username"] == "newuser123"
def test_duplicate_username(auth_client):
"""Test duplicate username is rejected."""
# First create user
auth_client.post("/api/auth/register", json={
"username": "testuser",
"password": "securepassword123"
})
# Try to register again with same username
response = auth_client.post("/api/auth/register", json={
"username": "testuser",
"password": "anotherpassword"
})
assert response.status_code == 409
def test_invalid_username_format(auth_client):
"""Test invalid username format is rejected."""
response = auth_client.post("/api/auth/register", json={
"username": "ab", # Too short
"password": "securepassword123"
})
assert response.status_code == 400
def test_login_valid_credentials(auth_client):
"""Test login with valid credentials returns token."""
from app.auth import hash_password
response = auth_client.post("/api/auth/login", json={
"username": "testuser",
"password": hash_password("securepassword123") # Use stored hash format
})
assert response.status_code == 200
data = response.json()
assert "token" in data
assert data["username"] == "testuser"
def test_login_invalid_credentials(auth_client):
"""Test login with invalid credentials returns 401."""
response = auth_client.post("/api/auth/login", json={
"username": "testuser",
"password": "wrongpassword"
})
assert response.status_code == 401
def test_get_me_valid_token(auth_client, valid_password):
"""Test /me endpoint with valid token."""
from app.auth import hash_password, create_token
# First register to get a proper password hash
response = auth_client.post("/api/auth/register", json={
"username": "testmeuser",
"password": valid_password
})
assert response.status_code == 201
token = response.json()["token"]
# Now verify /me endpoint works
response = auth_client.get("/api/auth/me", headers={
"Authorization": f"Bearer {token}"
})
assert response.status_code == 200
data = response.json()
assert data["username"] == "testmeuser"
def test_get_me_invalid_token(auth_client):
"""Test /me endpoint with invalid token returns 401."""
response = auth_client.get("/api/auth/me", headers={
"Authorization": "Bearer invalid.token.here"
})
assert response.status_code == 401
def test_logout(auth_client, valid_password):
"""Test logout endpoint."""
from app.auth import hash_password, create_token
# Register to get token
response = auth_client.post("/api/auth/register", json={
"username": "testlogoutuser",
"password": valid_password
})
assert response.status_code == 201
token = response.json()["token"]
# Call logout
response = auth_client.post("/api/auth/logout")
assert response.status_code == 204
# Try to use token after logout (should still work since JWT is stateless)
response = auth_client.get("/api/auth/me", headers={
"Authorization": f"Bearer {token}"
})
assert response.status_code == 200
def test_password_hashing_valid(auth_client):
"""Test that password hashing works correctly."""
from app.auth import hash_password, verify_password
original_password = "mysecret123"
stored_hash = hash_password(original_password)
assert verify_password(original_password, stored_hash) is True
assert verify_password("wrongpassword", stored_hash) is False
def test_jwt_token_structure(valid_password):
"""Test JWT token has correct structure and expiry."""
from app.auth import create_token
token = create_token("testuser")
# Token should not be empty
assert token and len(token) > 0