final commit
This commit is contained in:
1 parent
0ffbba3bed
commit
7b242b8685
39 files changed
+5524
-65
No files matched your search
@@ -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",
|
||||
]
|
||||
@@ -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")
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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
|
||||
Reference in new issue
Block a user