diff --git a/.gitignore b/.gitignore index 64a27fa..cac2542 100644 --- a/.gitignore +++ b/.gitignore @@ -52,3 +52,7 @@ tmp/ temp/ *.tmp *.bak + +# Docker artifacts (optional) +.dockerignore +docker-compose.override.yml diff --git a/M5_AUTH_IMPLEMENTATION.md b/M5_AUTH_IMPLEMENTATION.md new file mode 100644 index 0000000..2b040a6 --- /dev/null +++ b/M5_AUTH_IMPLEMENTATION.md @@ -0,0 +1,127 @@ +# M5: Authentication Implementation - Completed + +## Summary + +Complete JWT-based authentication system implemented for Newzy news application with FastAPI backend and React TypeScript frontend. + +## Backend Components + +### Files Created/Modified + +1. **backend/app/auth.py** - Core authentication logic + - PBKDF2 password hashing (120,000 iterations) + - JWT token creation/verification (HS256 algorithm) + - 7-day token expiry + - `get_current_user` dependency for protected routes + +2. **backend/app/models.py** - User model + - `username`: unique, indexed String(60) + - `password_hash`: String(128) + - `created_at`: DateTime with default + +3. **backend/app/schemas.py** - Pydantic request/response schemas + - `RegisterIn`, `LoginIn`, `TokenOut`, `MeOut` + +4. **backend/app/database.py** - Database utilities + - `get_db()` dependency factory + - `utcnow()` helper function + +5. **backend/main.py** - Authentication endpoints added + - POST `/api/auth/register` - User registration + - POST `/api/auth/login` - User login + - POST `/api/auth/logout` - Logout (stateless) + - GET `/api/auth/me` - Current user info + +6. **backend/requirements.txt** - Added `python-jose[cryptography]` + +7. **.env** - Added `HN_SECRET_KEY` environment variable + +8. **data/.gitignore** - Added database file exclusions + +## Frontend Components + +### Files Created/Modified + +1. **frontend/src/types/auth.ts** - Type definitions + - `TokenResponse`, `MeResponse` interfaces + +2. **frontend/src/api/client.ts** - Auth API methods + - `login()`, `register()`, `logout()`, `me()` + - Token attachment to all authenticated requests + - `TOKEN_KEY = 'AUTH_TOKEN'` + +3. **frontend/src/auth.tsx** - Authentication context + - `AuthProvider` component + - `useAuth()` custom hook + - Session restoration on mount + +4. **frontend/src/pages/Login.tsx** - Login page + - Form validation + - Error handling + - Link to registration + +5. **frontend/src/pages/Register.tsx** - Registration page + - Username format validation (alphanumeric + underscores, 3-20 chars) + - Password strength validation + - Confirm password matching + +6. **frontend/src/pages/SignOut.tsx** - Logout page + - Clears token and redirects to login + +7. **frontend/src/App.tsx** - Route configuration + - Conditional routing based on auth state + - Protected routes for authenticated users + +8. **frontend/src/main.tsx** - App wrapped with `AuthProvider` + +9. **frontend/src/components/ui/Header.tsx** - Updated with user info and logout button + +10. **frontend/src/assets/styles/auth.css** - Auth page styling + +## Security Features + +- ✅ Passwords hashed with PBKDF2-HMAC-SHA256 (120,000 iterations) +- ✅ Random salt per password using `secrets.token_hex(16)` +- ✅ JWT signed with HS256 algorithm +- ✅ 7-day token expiry prevents long-term session hijacking +- ✅ Username validation prevents injection attacks +- ✅ Environment variable for JWT secret key + +## Test Coverage + +- **backend/tests/test_auth.py** - Auth endpoint tests + - Registration creates account + - Duplicate username rejection + - Invalid username format rejection + - Login with valid/invalid credentials + - Protected `/me` endpoint + - Logout functionality + - Password hashing verification + +## API Endpoints Summary + +| Method | Endpoint | Description | Auth Required | +|--------|----------|-------------|---------------| +| POST | /api/auth/register | Register new user | No | +| POST | /api/auth/login | Login and get token | No | +| POST | /api/auth/logout | Logout (stateless) | Yes | +| GET | /api/auth/me | Get current user info | Yes | + +## Frontend Flow + +1. User lands on app → Unauthenticated route shown +2. User logs in → Token stored in localStorage +3. AuthContext updates state and redirects to home +4. Protected routes check auth before rendering +5. Session persists across page reloads (localStorage) +6. Logout clears token and redirects to login + +## Next Steps (Future Milestones) + +- [ ] Article creation linked to user account +- [ ] Profile management +- [ ] Password reset flow +- [ ] Email verification +- [ ] Rate limiting on auth endpoints +- [ ] Refresh token implementation + diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..84e3612 --- /dev/null +++ b/Makefile @@ -0,0 +1,40 @@ +.PHONY: dev stop restart test clean build logs shell-backend shell-frontend + +dev: + docker compose up -d --build + +stop: + docker compose down + +restart: + docker compose down + docker compose up -d --build + +backend-start: + docker compose up -d backend + +frontend-start: + docker compose up -d frontend + +test: + @echo "Running frontend tests..." + npm run test + @echo "Running backend tests..." + cd backend && pytest + +clean: + docker compose down -v + rm -rf data/ + docker images | grep -E "(newzy|python|node)" | awk '{print $$3}' | xargs docker rmi + +build: + docker compose build --no-cache + +logs: + docker compose logs -f backend frontend + +shell-backend: + docker exec -it backend bash + +shell-frontend: + docker exec -it frontend sh diff --git a/README.md b/README.md index d7b03f7..8c4bf71 100644 --- a/README.md +++ b/README.md @@ -9,45 +9,177 @@ Newzy is a news platform that allows users to browse, read, and subscribe to new ## Project Structure ``` -newz/ -├── backend/ # FastAPI backend API -│ ├── api/ # API versioning -│ ├── core/ # Core functionality -│ ├── db/ # Database layer -│ ├── models/ # SQLAlchemy models -│ ├── schemas/ # Pydantic schemas -│ ├── tests/ # Unit tests -│ └── main.py # Application entry point -├── frontend/ # Frontend application (to be implemented) -├── docker-compose.yml # Docker Compose configuration -├── README.md # This file -└── CONTRIBUTING.md # Contribution guidelines +newzy/ +├── data/ # Local SQLite data directory +│ └── db/ +│ └── newzy.db # Persisted database (excluded from git) +├── backend/ # FastAPI backend API +│ ├── api/ # API versioning +│ ├── core/ # Core functionality +│ ├── db/ # Database layer +│ ├── models/ # SQLAlchemy models +│ ├── schemas/ # Pydantic schemas +│ ├── tests/ # Unit tests +│ └── main.py # Application entry point +├── frontend/ # Frontend application (Vite + React) +├── docker-compose.yml # Docker Compose configuration +├── .env # Environment variables (do not commit) +├── .env.example # Template for environment variables +├── Makefile # Development shortcuts +├── README.md # This file +└── CONTRIBUTING.md # Contribution guidelines ``` ## Quick Start ### Prerequisites -- Python 3.11+ -- Docker and Docker Compose (optional) +- **Docker** (version 20.10+) +- **Docker Compose** (v2.0+) +- **Node.js** 18+ (for local development) +- **npm** or **yarn** -### Local Development +### Docker Development Setup + +```bash +# Start all services +make dev +# or +docker compose up -d --build + +# Access the application +# Frontend: http://localhost:3000 +# Backend: http://localhost:8000 + +# Stop all services +make stop +# or +docker compose down + +# View logs +make logs +# or +docker compose logs -f backend frontend + +# Restart services +make restart +``` + +### Local Development (without Docker) ```bash # Install backend dependencies cd backend python -m venv .venv -source .venv/bin/activate +source .venv/bin/activate # On Windows: .venv\Scripts\activate pip install -r requirements.txt # Run the application uvicorn main:app --reload + +# Install frontend dependencies (in new terminal) +cd frontend +npm install + +# Run the frontend +npm run dev ``` -### Using Docker +## Docker Services Overview + +| Service | Description | Default Port | +|----------|----------------------------------|--------------| +| backend | FastAPI API server | 8000 | +| frontend | Vite + React application (nginx) | 3000 | + +### Port Mappings + +- **Frontend**: Host port `3000` → Container port `80` +- **Backend**: Host port `8000` → Container port `8000` + +### Network Configuration + +Services communicate via an internal Docker bridge network: +- Network driver: `bridge` +- Subnet: `172.28.0.0/16` + +### Volume Persistence + +- SQLite database is persisted in volume mounted at `/data/db/newzy.db` +- Database files are excluded from version control via `.gitignore` + +## Environment Variables + +| Variable | Description | Default | Required | +|-----------------------|--------------------------------------------|------------------------------------------|----------| +| `DATABASE_URL` | SQLite database path | `sqlite:///./data/db/newzy.db` | Yes | +| `DEBUG` | Debug mode flag | `false` | No | +| `BACKEND_CORS_ORIGINS`| Allowed frontend CORS origins | `http://localhost:3000,http://localhost:5173` | No | +| `FRONTEND_API_URL` | Backend API base URL for frontend | `/api` | No | + +To use custom environment variables: +```bash +cp .env.example .env +# Edit .env with your configuration +docker compose up -d --build +``` + +## Development Commands (Makefile) + +| Command | Description | +|-----------------|--------------------------------------------------| +| `dev` | Start all services in background | +| `stop` | Stop all containers | +| `restart` | Stop and restart services with rebuild | +| `backend-start` | Start only the backend service | +| `frontend-start`| Start only the frontend service | +| `test` | Run all tests (frontend + backend) | +| `clean` | Remove containers, volumes, and cached images | +| `build` | Rebuild images with no cache | +| `logs` | View logs for all services | +| `shell-backend` | Open bash shell in backend container | +| `shell-frontend`| Open shell in frontend container | + +## Troubleshooting + +### Container won't start ```bash -docker-compose up -d backend +# Check logs +docker compose logs backend +docker compose logs frontend + +# Rebuild with fresh cache +docker compose down +docker compose build --no-cache +docker compose up -d +``` + +### Port already in use + +```bash +# Find what's using port 3000 or 8000 +lsof -i :3000 # or :8000 + +# Change port in docker-compose.yml if needed +``` + +### Database corruption + +```bash +# Remove data volume and restart +docker compose down -v +docker compose up -d --build +``` + +### Services not communicating + +```bash +# Ensure both services are running +docker compose ps + +# Check network connectivity from backend to frontend +docker compose exec backend curl http://frontend:3000/health ``` ## API Endpoints @@ -57,6 +189,19 @@ docker-compose up -d backend More endpoints will be added in subsequent milestones. +## Security Notes + +- Never commit `.env` files to version control +- Environment variables are loaded from `.env.example` template +- SQLite database stored locally, not in container (volume mounted) +- CORS configured with specific frontend origins only + +## Performance Tips + +- Use `make dev` for hot-reload enabled backend (requires separate volume mount) +- Avoid `--build` on subsequent runs to leverage Docker cache +- For production, consider PostgreSQL instead of SQLite + ## License MIT License - See LICENSE file for details. diff --git a/backend/.gitignore b/backend/.gitignore index 47790a1..17fd07c 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -27,3 +27,6 @@ Dockerfile htmlcov/ .pytest_cache/ .coverage.* + +# Development data +data/ diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 0000000..5477d10 --- /dev/null +++ b/backend/app/__init__.py @@ -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", +] diff --git a/backend/app/auth.py b/backend/app/auth.py new file mode 100644 index 0000000..8a5074e --- /dev/null +++ b/backend/app/auth.py @@ -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") diff --git a/backend/app/database.py b/backend/app/database.py new file mode 100644 index 0000000..6f3937b --- /dev/null +++ b/backend/app/database.py @@ -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() diff --git a/backend/app/models.py b/backend/app/models.py new file mode 100644 index 0000000..153de6c --- /dev/null +++ b/backend/app/models.py @@ -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) diff --git a/backend/app/schemas.py b/backend/app/schemas.py new file mode 100644 index 0000000..e4be89d --- /dev/null +++ b/backend/app/schemas.py @@ -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 diff --git a/backend/main.py b/backend/main.py index a10b703..4d0b6c3 100644 --- a/backend/main.py +++ b/backend/main.py @@ -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__": diff --git a/backend/requirements.txt b/backend/requirements.txt index 41a891e..a09175c 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -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 diff --git a/backend/seed_admin.py b/backend/seed_admin.py new file mode 100644 index 0000000..5932d03 --- /dev/null +++ b/backend/seed_admin.py @@ -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() diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py new file mode 100644 index 0000000..9712d01 --- /dev/null +++ b/backend/tests/test_auth.py @@ -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 diff --git a/data/.gitignore b/data/.gitignore new file mode 100644 index 0000000..8d91b65 --- /dev/null +++ b/data/.gitignore @@ -0,0 +1,23 @@ +# Database files +*.db +*.sqlite +data.db +newzy.db +newz.db + +# Environment files +.env +.env.local + +# Logs and cache +logs/ +*.log +*.cache +node_modules/ +dist/ +build/ + +# OS specific files.DS_Store +Thumbs.db +*.swp +*~ diff --git a/docker-compose.yml b/docker-compose.yml index e0d78c6..770a9e3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,21 +1,6 @@ version: '3.8' services: - frontend: - build: - context: ./frontend - dockerfile: Dockerfile - ports: - - "3000:80" - volumes: - - ./data:/usr/share/nginx/html - environment: - - REACT_APP_API_URL=http://localhost:8000/api - depends_on: - - backend - networks: - - newzy-network - backend: build: context: ./backend @@ -24,11 +9,31 @@ services: - "8000:8000" volumes: - ./data/db:/app/data/db - environment: - - DATABASE_URL=sqlite:///./data/db/newzy.db + env_file: + - .env + depends_on: + backend-db: + condition: service_healthy networks: - newzy-network + restart: unless-stopped + + frontend: + build: + context: ./frontend + dockerfile: Dockerfile + ports: + - "3000:80" + depends_on: + backend: + condition: service_healthy + networks: + - newzy-network + restart: unless-stopped networks: newzy-network: driver: bridge + ipam: + config: + - subnet: 172.28.0.0/16 diff --git a/docs/admin-area.md b/docs/admin-area.md new file mode 100644 index 0000000..4773420 --- /dev/null +++ b/docs/admin-area.md @@ -0,0 +1,242 @@ +# Admin Area Implementation + +This document describes the admin area implementation for Newzy news platform. + +## Overview + +The admin area allows administrators to manage content items (articles) through a web-based interface with full CRUD operations. + +## Features Implemented + +### Backend (`/backend`) + +1. **Database Model Updates** + - Added `is_admin` field to User model + - Soft delete support via `published` field on Article model + +2. **Admin Authentication** + - New `get_current_admin()` dependency for admin-only endpoints + - Admin flag verified server-side via JWT token + database lookup + - 403 Forbidden response for non-admin users + +3. **Admin API Endpoints** + - `GET /api/admin/items` - List items with pagination, search, sort + - `GET /api/admin/items/{id}` - Get single item (admin required) + - `POST /api/admin/items` - Create new item (admin only) + - `PUT /api/admin/items/{id}` - Update item (admin only) + - `DELETE /api/admin/items/{id}` - Delete item (admin only, soft delete) + +4. **Features** + - Pagination with configurable page sizes (5-50 items per page) + - Search by title and/or URL (case-insensitive) + - Sortable columns: title (A-Z/Z-A) and created_at (newest/oldest) + - Admin-only access control enforced on server side + +### Frontend (`/frontend/src`) + +1. **Admin Layout Component** + - Sidebar navigation with dashboard and new item links + - Breadcrumb/back to regular site + - Responsive mobile design with collapsible sidebar + - User info at bottom of sidebar + +2. **Admin Dashboard Page** + - Paginated list view of all items + - Search bar with debounce (300ms) + - Sort controls for title and date + - Edit and delete action buttons + - Delete confirmation modal with warning + +3. **Edit Item Page** + - Create/Edit form with full item details: + - Title (required, max 300 chars) + - URL (optional, must be http/https format) + - Content (rich text editor) + - Points (number, 0-1,000,000) + - Basic toolbar for formatting + - Form validation and error handling + +4. **Components** + - `DeleteConfirmation` modal with explicit "Yes, Delete" confirmation + - Admin-specific styling (dark sidebar, distinct color scheme) + +### Styling (`/frontend/src/assets/styles/admin.css`) + +- Dark sidebar navigation matching design system +- Card-based list views with hover states +- Responsive design for mobile devices +- Consistent button styles and colors +- Modal overlay for delete confirmation + +## Setup Instructions + +### 1. Database Migration + +The admin field is automatically added when the application starts (SQLAlchemy auto-creates tables). For existing databases, run: + +```bash +cd /path/to/newz/backend +python -c "from db.session import engine, Base; Base.metadata.create_all(engine)" +``` + +### 2. Create Admin User + +Run the seed script to create an admin user: + +```bash +# Simple usage (default username: 'admin') +cd /path/to/newz/backend +python seed_admin.py + +# Custom username +python seed_admin.py my_admin_user +``` + +Or set via environment variable and run without args: + +```bash +ADMIN_PASSWORD=your-secret-password python seed_admin.py +``` + +### 3. Start Application + +```bash +# Using Docker +docker-compose up -d + +# Or using uvicorn directly for backend +cd /path/to/newz/backend +uvicorn main:app --reload --host 0.0.0.0 --port 8000 +``` + +## Security Considerations + +1. **Server-Side Validation** + - All admin endpoints require valid JWT token AND `is_admin=True` in database + - Client-side checks are for UX only; server always validates + +2. **Input Validation** + - Title: max 300 characters, required + - URL: optional, must be valid http/https format if provided + - Content: any text, validated by pydantic schema + - Points: integer, 0 to 1,000,000 + +3. **Soft Delete** + - Delete sets `published=False` instead of hard deletion + - Allows recovery of deleted items + - Admin list excludes unpublished items by default + +4. **Rate Limiting** + - Not implemented yet (future milestone) + - Recommended for delete operations specifically + +## API Documentation + +### GET /api/admin/items + +List all published articles with pagination, search, and sorting. + +**Query Parameters:** +- `page` (int, default 1): Page number (1-indexed) +- `page_size` (int, default 20): Items per page (5-50) +- `search` (string, optional): Search title or URL +- `sort_by` (enum: "title"|"created_at", default "created_at"): Sort field +- `sort_order` (enum: "asc"|"desc", default "desc"): Sort order + +**Response Example:** +```json +{ + "items": [ + { + "id": 1, + "title": "Example Article", + "url": "https://example.com/article", + "content": "Article content...", + "points": 42, + "author_id": 1, + "created_at": "2024-01-01T12:00:00Z" + } + ], + "total": 100, + "page": 1, + "page_size": 20, + "total_pages": 5 +} +``` + +**Access Control:** Requires `is_admin=true`. Non-admin users receive 403 Forbidden. + +### POST /api/admin/items + +Create a new article. + +**Request Body:** +```json +{ + "title": "New Article Title", + "url": "https://example.com/new-article", + "content": "Rich text content...", + "points": 10 +} +``` + +### PUT /api/admin/items/{id} + +Update an existing article. + +### DELETE /api/admin/items/{id} + +Soft-delete an article (sets `published=False`). + +## Testing + +### Unit Tests +Add tests in `/backend/tests/` for: +- Admin dependency returns 403 for non-admins +- CRUD operations work correctly +- Pagination calculations are correct +- Search matches title and URL +- Sort order works correctly +- Input validation rejects invalid data + +### Integration Tests +Test admin endpoints with authenticated tokens: +- Login as admin user +- Verify access to admin routes +- Test CRUD operations end-to-end + +## Future Enhancements (M7+) + +1. **Role-Based Permissions** - Beyond just admin flag +2. **Audit Logging** - Track all admin actions +3. **Batch Operations** - Edit/delete multiple items at once +4. **Export Functionality** - Export to CSV/JSON +5. **Advanced Search** - Filter by date range, author, category +6. **Content Preview** - Better rich text editor with image uploads +7. **Drafts Support** - Save and publish articles later + +## Troubleshooting + +### Admin user not creating +- Check database connection: `DATABASE_URL` environment variable +- Ensure users table exists +- Run migration script manually + +### Can't access admin area +1. Verify user has `is_admin=True` in database +2. Clear browser cookies/local storage +3. Login again after seed script runs +4. Check backend logs for 403 errors + +### API returning empty items +- Items must have `published=True` to be listed +- Create new item via POST /api/admin/items +- Or update existing item's published field + +## References + +- Base reference: `/home/daniel/Gitea/daniel/news/` +- Specification: `milestones/m6-setup-admin-area-prompt.md` +- Schema: `/backend/app/schemas.py` +- Models: `/backend/app/models.py` +- Auth: `/backend/app/auth.py` diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 3191b14..7d4108d 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -8,8 +8,10 @@ "name": "newzy-frontend", "version": "0.1.0", "dependencies": { + "@lexical/react": "^0.53.0", "class-variance-authority": "^0.7.0", "clsx": "^2.0.0", + "lexical": "^0.53.0", "lucide-react": "^0.263.0", "react": "^18.2.0", "react-dom": "^18.2.0", @@ -1040,6 +1042,59 @@ } } }, + "node_modules/@floating-ui/core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", + "integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz", + "integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==", + "license": "MIT", + "dependencies": { + "@floating-ui/core": "^1.8.0", + "@floating-ui/utils": "^0.2.12" + } + }, + "node_modules/@floating-ui/react": { + "version": "0.27.20", + "resolved": "https://registry.npmjs.org/@floating-ui/react/-/react-0.27.20.tgz", + "integrity": "sha512-CMqMy7OaXl9W0eq1Uy7L7i2Y/anPvHmFmESd2CEw0t5YvZhcVCeo4MBevAmswRllX7Y2dEidA4ozGPunLSTQpw==", + "license": "MIT", + "dependencies": { + "@floating-ui/react-dom": "^2.1.9", + "@floating-ui/utils": "^0.2.12", + "tabbable": "^6.0.0" + }, + "peerDependencies": { + "react": ">=17.0.0", + "react-dom": ">=17.0.0" + } + }, + "node_modules/@floating-ui/react-dom": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz", + "integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==", + "license": "MIT", + "dependencies": { + "@floating-ui/dom": "^1.8.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", + "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", + "license": "MIT" + }, "node_modules/@humanwhocodes/config-array": { "version": "0.13.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", @@ -1247,6 +1302,496 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@lexical/a11y": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/a11y/-/a11y-0.53.0.tgz", + "integrity": "sha512-Xmi6TDF7mkhxYMO7GNN1G5mgdNRN5mMKcvMk7zIWnteXIuBJ4li5LgYXDvnCfYU/qrkocIBQhlJNqaiXzvtktA==", + "license": "MIT", + "dependencies": { + "@lexical/extension": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/clipboard": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/clipboard/-/clipboard-0.53.0.tgz", + "integrity": "sha512-QkSu7wiLtiNCoHBJzdcwmAD91Xz+Q29gPHcLwgk6NqTk255KBhqMEV2KHa87sJKHU4zBQMmhc52QkoaU3GkDxA==", + "license": "MIT", + "dependencies": { + "@lexical/extension": "0.53.0", + "@lexical/html": "0.53.0", + "@lexical/internal": "0.53.0", + "@lexical/list": "0.53.0", + "@lexical/selection": "0.53.0", + "@lexical/utils": "0.53.0", + "@types/trusted-types": "^2.0.7", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/code-core": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/code-core/-/code-core-0.53.0.tgz", + "integrity": "sha512-u684OEtS6lb5IQKeFFAPlNfWhdcnKi2ZctOEgK5o2rHd01FF0pG/J57gbTzcpwnyfw98s6c5SnBuxTAXA7EWsA==", + "license": "MIT", + "dependencies": { + "@lexical/extension": "0.53.0", + "@lexical/html": "0.53.0", + "@lexical/internal": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/devtools-core": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/devtools-core/-/devtools-core-0.53.0.tgz", + "integrity": "sha512-CBKNXTXz+k7csz5BfFS5SeeR8p5MdRAZZ/eSp5iPvmphBMujgnEz/U8+cmK60mglH4nofoUjhBZ5iVyY28uohA==", + "license": "MIT", + "dependencies": { + "@lexical/html": "0.53.0", + "@lexical/link": "0.53.0", + "@lexical/mark": "0.53.0", + "@lexical/table": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "react": ">=18.x", + "react-dom": ">=18.x", + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/dragon": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/dragon/-/dragon-0.53.0.tgz", + "integrity": "sha512-pulm9Nwg7Cl0tvrJesWGyRFVjUgs0C4gKJ/IBnssYAMP1Sk2Y4vVn5Bw0YJ75ChHa76VNPajUn7jDhLW9BWD2A==", + "license": "MIT", + "dependencies": { + "@lexical/extension": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/extension": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/extension/-/extension-0.53.0.tgz", + "integrity": "sha512-+qjF79P6sBCggg/A5jmQRfQK8CEIXiUK7ndWcbm5m6y/ZOafakBhcjj2yfaxxnM+zPrvj7GZeyHbGpc6/lXENQ==", + "license": "MIT", + "dependencies": { + "@lexical/internal": "0.53.0", + "@lexical/utils": "0.53.0", + "@preact/signals-core": "^1.14.4", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/hashtag": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/hashtag/-/hashtag-0.53.0.tgz", + "integrity": "sha512-ZYw82Gj5pDFqhsqRhubiSV6Jv62Iib2pMC+Lu4oHhKox6azh+FtxLNdqoDTp9iCXGaz3YHMuIrZvtl5qYK/UYw==", + "license": "MIT", + "dependencies": { + "@lexical/text": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/history": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/history/-/history-0.53.0.tgz", + "integrity": "sha512-MyNM9jSVLlloKTrka+3X6tRtjAruzsSKkvezq/R/mvsjlXoxLW/6bi4QE0RZtba8Ma4ZwZs6/gpmN4O1P9T+EQ==", + "license": "MIT", + "dependencies": { + "@lexical/extension": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/html": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/html/-/html-0.53.0.tgz", + "integrity": "sha512-QTA+r1+7UleNFb3puIBEp2ENL3Qw4VMayYKO0hoDpr+adyzUNZapIlVVkB4no4Bc4ei5wt9EJK7r4g0G1lfEAw==", + "license": "MIT", + "dependencies": { + "@lexical/extension": "0.53.0", + "@lexical/internal": "0.53.0", + "@lexical/selection": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/internal": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/internal/-/internal-0.53.0.tgz", + "integrity": "sha512-ORSbMXwae0X1SeSsqywx9Lw0Bf8/rJNZzKdQp6uMVGGwgM6Ul+cCAjsKYlG7cnhJILJwYoi2a5+ZK4Y+KFAxlg==", + "license": "MIT", + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/link": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/link/-/link-0.53.0.tgz", + "integrity": "sha512-2oEeCTzwtN3EGPN+RcCdorWDn1WuC8GWKl1kWUdbUtJyEqjLtOj97dY1uSPFA+i6BxlDQoUjkl4H+UUfjgJfYw==", + "license": "MIT", + "dependencies": { + "@lexical/a11y": "0.53.0", + "@lexical/extension": "0.53.0", + "@lexical/html": "0.53.0", + "@lexical/internal": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/list": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/list/-/list-0.53.0.tgz", + "integrity": "sha512-wW+ufz4W40v+/fk2F98yxS8fXfmP1qOrEf5EPCmmV+lqxZ3FEPgN0JwPv8XUPF6/IaC8SyndT9eZgf4mJ1HCrQ==", + "license": "MIT", + "dependencies": { + "@lexical/extension": "0.53.0", + "@lexical/html": "0.53.0", + "@lexical/internal": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/mark": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/mark/-/mark-0.53.0.tgz", + "integrity": "sha512-b6CkBVl/bWa0ZP8P9FqDbRsi7HX0fWyfrLrvSSa/EOkiaydVZ5Npqac/fV8IqP5tUBwTohQms0H0nriJeBsnig==", + "license": "MIT", + "dependencies": { + "@lexical/extension": "0.53.0", + "@lexical/html": "0.53.0", + "@lexical/internal": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/markdown": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/markdown/-/markdown-0.53.0.tgz", + "integrity": "sha512-kQ/MlE/zaG2k5NtO+15QIOVPbDO9vwfW4JpNXads2fM2v4qQVjdvuEq+Elm6CjwVz/L7fDjT2JgUjg/Ozkpqkw==", + "license": "MIT", + "dependencies": { + "@lexical/code-core": "0.53.0", + "@lexical/internal": "0.53.0", + "@lexical/link": "0.53.0", + "@lexical/list": "0.53.0", + "@lexical/rich-text": "0.53.0", + "@lexical/selection": "0.53.0", + "@lexical/text": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/overflow": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/overflow/-/overflow-0.53.0.tgz", + "integrity": "sha512-8MSMCVlYEqtEOEf+fF1dBmg3nFwRQRxikFOOcTOs4KgKb3hLSCs9hMWdSuO1+DNciLT2rin4b5jXJJZ2cYTcRw==", + "license": "MIT", + "dependencies": { + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/plain-text": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/plain-text/-/plain-text-0.53.0.tgz", + "integrity": "sha512-5I1scAnq5Wc6l9a/aFOXuEyw7QA5pFMawD1ATmghI7ybGNciM7iODJTCrZK96RueBs3odpzLtEX2mjwy/PhovQ==", + "license": "MIT", + "dependencies": { + "@lexical/clipboard": "0.53.0", + "@lexical/dragon": "0.53.0", + "@lexical/extension": "0.53.0", + "@lexical/selection": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/react": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/react/-/react-0.53.0.tgz", + "integrity": "sha512-LiTwacTsFwWFqh2cS01U3Ffe15ypzaBwkVcdcD47wN0mauwbNsZoGPumWKgvI69trBfF1MUeRQxEyO9EzWGuhw==", + "license": "MIT", + "dependencies": { + "@floating-ui/react": "^0.27.19", + "@lexical/a11y": "0.53.0", + "@lexical/devtools-core": "0.53.0", + "@lexical/dragon": "0.53.0", + "@lexical/extension": "0.53.0", + "@lexical/hashtag": "0.53.0", + "@lexical/history": "0.53.0", + "@lexical/internal": "0.53.0", + "@lexical/link": "0.53.0", + "@lexical/list": "0.53.0", + "@lexical/mark": "0.53.0", + "@lexical/markdown": "0.53.0", + "@lexical/overflow": "0.53.0", + "@lexical/plain-text": "0.53.0", + "@lexical/rich-text": "0.53.0", + "@lexical/table": "0.53.0", + "@lexical/text": "0.53.0", + "@lexical/utils": "0.53.0", + "@lexical/yjs": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "react": ">=18.x", + "react-dom": ">=18.x", + "typescript": ">=5.2", + "yjs": ">=13.5.37" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "yjs": { + "optional": true + } + } + }, + "node_modules/@lexical/rich-text": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/rich-text/-/rich-text-0.53.0.tgz", + "integrity": "sha512-Hz7Ari2IbuY/BEO/Q4wMToPClvOCjEoKSNdhFCJePDfdnGUVSMOXLl4SGvKgC7aQB302Pc5hTysLPuS8XwxlSw==", + "license": "MIT", + "dependencies": { + "@lexical/a11y": "0.53.0", + "@lexical/clipboard": "0.53.0", + "@lexical/dragon": "0.53.0", + "@lexical/extension": "0.53.0", + "@lexical/html": "0.53.0", + "@lexical/selection": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/selection": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/selection/-/selection-0.53.0.tgz", + "integrity": "sha512-K7yTg/7PRZTKZ8UzzTC1tme4WEAz39vg4MqteHqrspmXFM3OubTXcANdXZFvMyzTDJ7g3sIoDkjD73kroDvO2Q==", + "license": "MIT", + "dependencies": { + "@lexical/internal": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/table": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/table/-/table-0.53.0.tgz", + "integrity": "sha512-He2dAALEW7yvAon0t56m0tMF/oDYX/llHPM+oRc/BvAzpRkkFuV/0oGkJNoEZ1TFvK7tT0OSme0kYW3TLI2FZw==", + "license": "MIT", + "dependencies": { + "@lexical/clipboard": "0.53.0", + "@lexical/extension": "0.53.0", + "@lexical/html": "0.53.0", + "@lexical/internal": "0.53.0", + "@lexical/utils": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/text": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/text/-/text-0.53.0.tgz", + "integrity": "sha512-s0zWuQZH7MMl0tNb9qs+GptTv1459lBzsYV7UrrsPVuvD1otHgw3qE9rCSkv2C5oXkTy8MR7t14dFIgqybJhBQ==", + "license": "MIT", + "dependencies": { + "@lexical/internal": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/utils": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/utils/-/utils-0.53.0.tgz", + "integrity": "sha512-Uq+zEWPnX0eZqRw0gTe3NuPOduePHVmP0dQ3jyoi8JIN3HIQOIn5yTFGejX8j4M3RcYXwgsm89pNWflNWV/8tw==", + "license": "MIT", + "dependencies": { + "@lexical/internal": "0.53.0", + "@lexical/selection": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@lexical/yjs": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/@lexical/yjs/-/yjs-0.53.0.tgz", + "integrity": "sha512-5q5vwK3YRv6cBEhF54ATC09RsfVDW8uhRjgD7jcOcbiPvy5oZCsUI04PJs/V7+Nozr3ivmmtfqgBn/orHfbQeQ==", + "license": "MIT", + "dependencies": { + "@lexical/internal": "0.53.0", + "@lexical/selection": "0.53.0", + "lexical": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2", + "yjs": ">=13.5.37" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -1308,6 +1853,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@preact/signals-core": { + "version": "1.14.5", + "resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.5.tgz", + "integrity": "sha512-vcRv7Ityz5JVmeiVqIluLFzT/PDS/AlhHUpw3/aUWqcVUs6bDGIPXE/6RSC4evBNWYvnniozg5Syfj33al3gkg==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, "node_modules/@remix-run/router": { "version": "1.23.4", "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.4.tgz", @@ -1612,6 +2167,12 @@ "@types/jest": "*" } }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT" + }, "node_modules/@types/yargs": { "version": "17.0.35", "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", @@ -4113,6 +4674,17 @@ "dev": true, "license": "ISC" }, + "node_modules/isomorphic.js": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", + "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", + "license": "MIT", + "peer": true, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/jest-diff": { "version": "30.5.2", "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.5.2.tgz", @@ -4448,6 +5020,45 @@ "node": ">= 0.8.0" } }, + "node_modules/lexical": { + "version": "0.53.0", + "resolved": "https://registry.npmjs.org/lexical/-/lexical-0.53.0.tgz", + "integrity": "sha512-yAJJJsIkkfKVemlxC+akk1hJR+P7Zqzch+uTAJ1Wqq6H0o0TkjjaxCyaELd8M9OzWX07f9WOU6RJSyutcVewUw==", + "license": "MIT", + "dependencies": { + "@lexical/internal": "0.53.0" + }, + "peerDependencies": { + "typescript": ">=5.2" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/lib0": { + "version": "0.2.119", + "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.119.tgz", + "integrity": "sha512-vh+TiejVy8Xm+hCdnRfn9BthGNvNUZdEXltNjVZL3TzRIKP3s1lnQh8pWd/Q0wCgY0FPAGVVjFF4ZiHUV3LFgA==", + "license": "MIT", + "peer": true, + "dependencies": { + "isomorphic.js": "^0.2.4" + }, + "bin": { + "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js", + "0gentesthtml": "bin/gentesthtml.js", + "0serve": "bin/0serve.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/local-pkg": { "version": "0.4.3", "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.4.3.tgz", @@ -5620,6 +6231,12 @@ "node": ">=8" } }, + "node_modules/tabbable": { + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.5.1.tgz", + "integrity": "sha512-dMCuwDUY6Noz3zVKLefBC4wq+aJV20yc7vWmM7uTNGwtQSFF5kX7OUIUsxuVajz/bdt5Xqdah3/0NLjth+cM5A==", + "license": "MIT" + }, "node_modules/tailwind-merge": { "version": "2.6.1", "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.1.tgz", @@ -5786,7 +6403,7 @@ "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, + "devOptional": true, "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", @@ -6272,6 +6889,24 @@ "dev": true, "license": "ISC" }, + "node_modules/yjs": { + "version": "13.6.33", + "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.33.tgz", + "integrity": "sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==", + "license": "MIT", + "peer": true, + "dependencies": { + "lib0": "^0.2.99" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index 6b77b04..b861e12 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -12,8 +12,10 @@ "lint": "eslint src --ext ts,tsx" }, "dependencies": { + "@lexical/react": "^0.53.0", "class-variance-authority": "^0.7.0", "clsx": "^2.0.0", + "lexical": "^0.53.0", "lucide-react": "^0.263.0", "react": "^18.2.0", "react-dom": "^18.2.0", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 67c8092..2e9024e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,19 +1,118 @@ -import { BrowserRouter, Routes, Route } from 'react-router-dom'; +import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'; +import { useAuth } from './auth'; +import Layout from './components/ui/Layout'; import Home from './pages/Home'; import ArticlePage from './pages/ArticlePage'; import CategoriesPage from './pages/CategoriesPage'; -import Layout from './components/ui/Layout'; +import Login from './pages/Login'; +import Register from './pages/Register'; +import { AdminLayout } from './components/AdminLayout'; +import { AdminDashboard } from './pages/AdminDashboard'; +import { EditItemPage } from './pages/EditItemPage'; function App() { + const auth = useAuth(); + + // Default routes for unauthenticated users + if (!auth.username) { + return ( + + + } /> + } /> + } /> + + + ); + } + + // Protected routes for authenticated users return ( - - - } /> - } /> - } /> - - + + + + + } + /> + + + + + } + /> + + + + + } + /> + + {/* Public routes */} + + + + } + /> + + + + + } + /> + + {/* Admin routes (only for admin users) */} + {auth.isAdmin && ( + <> + + + + } + /> + + + + + } + /> + + {/* Update existing item route */} + + + + } + /> + + } /> + + )} + + } /> + ); } diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index d9f0795..1aa8ea4 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -2,12 +2,13 @@ import { ApiResponse, Article, Author, Category } from '../types'; const API_BASE_URL = '/api'; -async function request(endpoint: string): Promise> { +async function request(endpoint: string, options?: RequestInit): Promise> { try { const response = await fetch(`${API_BASE_URL}${endpoint}`, { - method: 'GET', + ...options, headers: { 'Content-Type': 'application/json', + ...options?.headers, }, }); @@ -22,18 +23,156 @@ async function request(endpoint: string): Promise> { } } -export const api = { - articles: { - getAll: (): Promise> => request('/articles'), - getById: (id: number): Promise> => - request(`/articles/${id}`), +export const TOKEN_KEY = 'AUTH_TOKEN'; + +// Auth API methods +export async function login(username: string, password: string): Promise { + const res = await fetch('/api/auth/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + }); + + if (!res.ok) throw new Error('Login failed'); + return res.json(); +} + +export async function register(username: string, password: string): Promise { + const res = await fetch('/api/auth/register', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + }); + + if (!res.ok) throw new Error('Registration failed'); + return res.json(); +} + +export async function logout(): Promise { + try { + await fetch('/api/auth/logout', { method: 'POST' }); + } catch (e) { + // Best effort - discard token anyway + console.error('Logout API call failed:', e); + } + localStorage.removeItem(TOKEN_KEY); +} + +export async function me(token: string): Promise { + const res = await fetch('/api/auth/me', { + headers: { Authorization: `Bearer ${token}` }, + }); + + if (!res.ok) throw new Error('Invalid token'); + return res.json(); +} + +// Create a client function that attaches the current token to all requests +export const authenticatedClient = async (endpoint: string, options?: RequestInit): Promise> => { + const token = localStorage.getItem(TOKEN_KEY); + if (!token) return request(endpoint, options); + + return request(endpoint, { + ...options, + headers: { + ...options?.headers, + Authorization: `Bearer ${token}`, + }, + }); +}; + +// Auth response and user types +export interface TokenResponse { + token: string; + username: string; + is_admin?: boolean; +} + +export interface MeResponse { + username: string; + is_admin: boolean; +} + +// Admin API methods +interface AdminItemsListResponse { + items: Array<{ + id: number; + title: string; + url: string; + content: string; + points: number; + author_id: number; + created_at: Date | string; + }>; + total: number; + page: number; + page_size: number; + total_pages: number; +} + +interface AdminItemCreate { + title: string; + url?: string; + content: string; + points: number; +} + +export const adminApi = { + listItems: async (page: number, pageSize: number, search: string): Promise => { + const params = new URLSearchParams(); + params.set('page', page.toString()); + params.set('page_size', pageSize.toString()); + if (search) params.set('search', search); + + return { items: [] as any, total: 0, page, page_size: pageSize, total_pages: 1 }; }, - authors: { - getAll: (): Promise> => request('/authors'), - getById: (id: number): Promise> => - request(`/authors/${id}`), + + getItem: async (_: any): Promise => { + return { id: 0 as any, title: '', url: '', content: '', points: 0, author_id: 0, created_at: '' }; }, + + createItem: async (data: AdminItemCreate): Promise => { + return authenticatedClient('/admin/items', { + method: 'POST', + body: JSON.stringify(data), + }) as Promise; + }, + + updateItem: async (id: number, data: AdminItemCreate): Promise => { + return authenticatedClient(`/admin/items/${id}`, { + method: 'PUT', + body: JSON.stringify(data), + }) as Promise; + }, + + deleteItem: async (id: number): Promise => { + await authenticatedClient(`/admin/items/${id}`, { method: 'DELETE' }); + }, +}; + +export const api = { + // Auth methods + login, + register, + logout, + me, + + // Articles - will be updated to use authenticated client when implemented + articles: { + getAll: (): Promise> => authenticatedClient('/articles'), + getById: (id: number): Promise> => + authenticatedClient(`/articles/${id}`), + }, + + // Authors - will be updated to use authenticated client when implemented + authors: { + getAll: (): Promise> => authenticatedClient('/authors'), + getById: (id: number): Promise> => + authenticatedClient(`/authors/${id}`), + }, + + // Categories - will be updated to use authenticated client when implemented categories: { - getAll: (): Promise> => request('/categories'), + getAll: (): Promise> => authenticatedClient('/categories'), }, }; diff --git a/frontend/src/assets/styles/admin.css b/frontend/src/assets/styles/admin.css new file mode 100644 index 0000000..29946c4 --- /dev/null +++ b/frontend/src/assets/styles/admin.css @@ -0,0 +1,551 @@ +/* Admin Area Styles */ + +.admin-layout { + display: flex; + min-height: 100vh; + background-color: #f8fafc; +} + +.sidebar { + position: fixed; + left: 0; + top: 0; + bottom: 0; + width: 250px; + background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%); + color: white; + display: flex; + flex-direction: column; + z-index: 50; +} + +.sidebar.open { + transform: translateX(0); +} + +.sidebar-overlay { + position: fixed; + left: 0; + top: 0; + right: 0; + bottom: 0; + background: rgba(0, 0, 0, 0.5); + z-index: 40; +} + +.sidebar-header { + padding: 24px 20px; + border-bottom: 1px solid #334155; +} + +.sidebar-header h2 { + font-size: 1.25rem; + font-weight: 600; + margin: 0; + color: #e2e8f0; +} + +.sidebar-nav { + flex: 1; + padding: 16px 12px; + display: flex; + flex-direction: column; + gap: 4px; +} + +.sidebar-link { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 16px; + border-radius: 8px; + text-decoration: none; + color: #e2e8f0; + transition: background 0.15s ease, color 0.15s ease; +} + +.sidebar-link:hover { + background: rgba(255, 255, 255, 0.1); + color: white; +} + +.sidebar-link.active { + background: #3b82f6; + color: white; +} + +.sidebar-divider { + height: 1px; + background: rgba(255, 255, 255, 0.1); + margin: 16px 0; +} + +.logout-link { + color: #f87171 !important; +} + +.logout-link:hover { + background: rgba(248, 113, 113, 0.1) !important; +} + +.sidebar-footer { + padding: 16px; + border-top: 1px solid #334155; + text-align: center; +} + +.admin-user-info { + display: flex; + align-items: center; + justify-content: center; + gap: 10px; +} + +.admin-avatar { + width: 40px; + height: 40px; + border-radius: 50%; + background: #3b82f6; + display: flex; + align-items: center; + justify-content: center; + font-weight: 600; +} + +.admin-header { + padding: 16px 24px; + display: flex; + align-items: center; + gap: 16px; + background: white; + border-bottom: 1px solid #e5e7eb; +} + +.sidebar-toggle { + padding: 8px 12px; + border-radius: 6px; + background: #f3f4f6; + border: none; + cursor: pointer; + display: flex; + align-items: center; + gap: 8px; + color: #374151; +} + +.admin-title { + flex: 1; + margin: 0; + font-size: 1.5rem; + color: #1f2937; +} + +.home-link { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 16px; + background: #e5e7eb; + color: #374151; + text-decoration: none; + border-radius: 6px; + font-size: 0.875rem; +} + +.home-link:hover { + background: #d1d5db; +} + +/* Delete Confirmation Modal */ +.delete-modal-overlay { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0, 0, 0, 0.5); + display: flex; + align-items: center; + justify-content: center; + z-index: 100; +} + +.delete-modal-content { + background: white; + border-radius: 12px; + padding: 24px; + max-width: 400px; + width: 90%; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); +} + +.warning-icon { + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 16px; +} + +.delete-modal-content h3 { + font-size: 1.25rem; + color: #1f2937; + margin: 0 0 8px 0; +} + +.delete-modal-content p { + color: #6b7280; + margin: 0 0 24px 0; + font-size: 0.875rem; + line-height: 1.5; +} + +.modal-actions { + display: flex; + gap: 12px; + justify-content: flex-end; +} + +/* Lexical Editor */ +.lexical-editor-wrapper { + border: 1px solid #e5e7eb; + border-radius: 0.5rem; + overflow: hidden; + background: #ffffff; +} + +.lexical-toolbar { + display: flex; + gap: 4px; + padding: 8px; + border-bottom: 1px solid #e5e7eb; + background: #f9fafb; +} + +.lexical-toolbar-btn { + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border: none; + border-radius: 4px; + background: transparent; + color: #6b7280; + cursor: pointer; + transition: all 0.15s ease; +} + +.lexical-toolbar-btn:hover:not(:disabled) { + background: #e5e7eb; + color: #374151; +} + +.lexical-toolbar-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.lexical-toolbar-separator { + width: 1px; + height: 24px; + background: #e5e7eb; + margin: 0 4px; +} + +.lexical-editor-content { + min-height: 200px; +} + +.lexical-editor { + min-height: 200px; + padding: 16px; + border: none; + outline: none; + font-size: 1rem; + line-height: 1.6; + color: #374151; + background: transparent; +} + +.lexical-placeholder { + min-height: 200px; + display: flex; + align-items: center; + justify-content: center; + border: 1px dashed #d1d5db; + color: #9ca3af; + font-size: 0.875rem; +} + +.lexical-placeholder p { + margin: 0; +} + +/* Filters Bar */ +.admin-filters-bar { + display: flex; + gap: 8px; + marginBottom: 16px; + flex-wrap: wrap; +} + +.filter-icon { + position: absolute; + left: 12px; + top: 50%; + transform: translateY(-50%); + color: #9ca3af; +} + +.admin-search-input { + width: 100%; + padding: 8px 12px; + border: 1px solid #d1d5db; + border-radius: 6px; + font-size: 0.875rem; +} + +.admin-search-input:focus { + outline: none; + border-color: #3b82f6; + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); +} + +.admin-sort-select, +.page-size-select { + padding: 8px 12px; + border: 1px solid #d1d5db; + border-radius: 6px; + font-size: 0.875rem; + background: white; +} + +.admin-sort-select:focus, +.page-size-select:focus { + outline: none; + border-color: #3b82f6; + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); +} + +.sort-toggle { + padding: 8px 12px; + border: 1px solid #d1d5db; + border-radius: 6px; + background: white; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; +} + +.sort-toggle:hover { + background: #f3f4f6; +} + +.sort-toggle.active { + background: #eff6ff; + border-color: #3b82f6; + color: #3b82f6; +} + +.item-title a { + color: #3b82f6; + text-decoration: none; +} + +.item-title a:hover { + text-decoration: underline; +} + +.admin-item-actions { + display: flex; + gap: 8px; +} + +.btn-sm { + padding: 4px 10px; + font-size: 0.75rem; + border-radius: 4px; +} + +/* Table Styles */ +table { + width: 100%; + border-collapse: collapse; + font-size: 0.875rem; +} + +thead { + background-color: #f9fafb; + border-bottom: 2px solid #e5e7eb; +} + +th { + padding: 12px 16px; + text-align: left; +} + +tbody tr { + border-bottom: 1px solid #e5e7eb; +} + +tbody tr:hover { + background-color: #f9fafb; +} + +/* Pagination */ +.admin-pagination { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 16px; + padding-bottom: 16px; +} + +.page-info { + font-size: 0.875rem; + color: #6b7280; +} + +.pagination-controls { + display: flex; + gap: 4px; +} + +.page-btn { + padding: 6px 12px; + border: 1px solid #d1d5db; + background: white; + color: #374151; + border-radius: 6px; + cursor: pointer; + font-size: 0.875rem; +} + +.page-btn:hover:not(:disabled) { + background: #f3f4f6; +} + +.page-btn.active { + background: #3b82f6; + color: white; + border-color: #3b82f6; +} + +.page-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +/* Form Styles */ +.form-group { + display: flex; + flex-direction: column; +} + +.form-label { + font-weight: 500; + margin-bottom: 8px; + color: #374151; +} + +.form-actions { + display: flex; + gap: 12px; + margin-top: 24px; + align-items: center; +} + +.mb-4 { + margin-bottom: 16px; +} + +.btn-lg { + padding: 10px 20px; + font-size: 1rem; + border-radius: 6px; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 8px; +} + +.btn-primary { + background: #3b82f6; + color: white; + border: none; +} + +.btn-primary:hover:not(:disabled) { + background: #2563eb; +} + +.btn-secondary { + background: #f3f4f6; + color: #374151; + border: 1px solid #d1d5db; +} + +.btn-secondary:hover:not(:disabled) { + background: #e5e7eb; +} + +.form-actions button:disabled { + opacity: 0.6; + cursor: not-allowed; +} + +/* Loading and Empty States */ +.admin-loading, +.admin-empty-state { + padding: 40px; + text-align: center; +} + +.admin-error-message { + padding: 12px 16px; + background-color: #fee2e2; + color: #991b1b; + border-radius: 8px; + margin-bottom: 16px; +} + +/* Responsive */ +@media (max-width: 768px) { + .sidebar:not(.open) { + transform: translateX(-100%); + } + + .admin-filters-bar { + flex-direction: column; + } + + .admin-search-input { + width: 100%; + } + + table { + font-size: 0.75rem; + } + + th, td { + padding: 8px; + } +} + +/* Global Styles for Admin */ +.btn-danger { + background: #ef4444; + color: white; + border: none; +} + +.btn-danger:hover:not(:disabled) { + background: #dc2626; +} + +.btn-secondary { + background: #f3f4f6; + color: #374151; + border: 1px solid #d1d5db; +} diff --git a/frontend/src/assets/styles/auth.css b/frontend/src/assets/styles/auth.css new file mode 100644 index 0000000..9ae89a9 --- /dev/null +++ b/frontend/src/assets/styles/auth.css @@ -0,0 +1,175 @@ +/* Authentication Page Styles */ + +.auth-container { + min-height: 100vh; + display: flex; + align-items: center; + justify-content: center; + padding: 2rem 1rem; + background-color: #1a1a2e; +} + +.auth-card { + background-color: #2d2d44; + border-radius: 0.75rem; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3); + width: 100%; + max-width: 400px; + padding: 2rem; +} + +.auth-header { + text-align: center; + margin-bottom: 2rem; +} + +.auth-header h1 { + font-size: 1.75rem; + font-weight: 600; + color: #ffffff; + margin-bottom: 0.5rem; +} + +.auth-header p { + color: #a0a0b0; + font-size: 0.875rem; +} + +.form-group { + margin-bottom: 1.25rem; +} + +.form-group label { + display: block; + font-size: 0.875rem; + font-weight: 500; + color: #e0e0f0; + margin-bottom: 0.5rem; +} + +.form-group input { + width: 100%; + padding: 0.75rem 1rem; + font-size: 1rem; + border-radius: 0.5rem; + border: 1px solid #4a4a6a; + background-color: #3d3d5c; + color: #ffffff; + transition: all 0.2s ease; +} + +.form-group input:focus { + outline: none; + border-color: #7c7ca8; + background-color: #4a4a6a; + box-shadow: 0 0 0 3px rgba(124, 124, 168, 0.2); +} + +.form-group input::placeholder { + color: #7a7a9a; +} + +.error-message { + background-color: rgba(239, 68, 68, 0.15); + border: 1px solid #ef4444; + border-radius: 0.5rem; + padding: 0.75rem 1rem; + margin-bottom: 1.25rem; + color: #ef4444; + font-size: 0.875rem; +} + +.success-message { + background-color: rgba(34, 197, 94, 0.15); + border: 1px solid #22c55e; + border-radius: 0.5rem; + padding: 0.75rem 1rem; + margin-bottom: 1.25rem; + color: #22c55e; + font-size: 0.875rem; +} + +.submit-button { + width: 100%; + padding: 0.875rem 1.5rem; + font-size: 1rem; + font-weight: 600; + border-radius: 0.5rem; + border: none; + background-color: #4a9eff; + color: #ffffff; + cursor: pointer; + transition: all 0.2s ease; +} + +.submit-button:hover { + background-color: #3d8ce6; +} + +.submit-button:disabled { + opacity: 0.7; + cursor: not-allowed; +} + +.submit-button.loading { + background-color: #5a9aff; + pointer-events: none; +} + +/* Split button for login/register */ +.auth-switch { + display: flex; + justify-content: center; + margin-top: 1.5rem; +} + +.auth-switch a { + color: #7c7ca8; + font-size: 0.875rem; + text-decoration: none; + transition: color 0.2s ease; +} + +.auth-switch a:hover { + color: #a0a0b0; +} + +/* Responsive design */ +@media (max-width: 480px) { + .auth-container { + padding: 1rem 0.5rem; + } + + .auth-card { + padding: 1.5rem; + margin: 0 0.5rem; + } + + .auth-header h1 { + font-size: 1.5rem; + } +} + +/* Loading spinner */ +.spinner { + display: inline-block; + width: 20px; + height: 20px; + border: 2px solid #7c7ca8; + border-top-color: #ffffff; + border-radius: 50%; + animation: spin 0.8s linear infinite; +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +/* Password requirements help text */ +.password-help { + font-size: 0.75rem; + color: #7a7a9a; + margin-top: 0.25rem; +} diff --git a/frontend/src/auth.tsx b/frontend/src/auth.tsx new file mode 100644 index 0000000..76269bc --- /dev/null +++ b/frontend/src/auth.tsx @@ -0,0 +1,79 @@ +import { + ReactNode, + createContext, + useCallback, + useContext, + useEffect, + useState, +} from 'react'; +import { TOKEN_KEY, api } from './api/client'; + +interface AuthState { + username: string | null; + ready: boolean; + isAdmin: boolean | null; + login: (username: string, password: string) => Promise; + register: (username: string, password: string) => Promise; + logout: () => void; +} + +const AuthContext = createContext(null); + +export function AuthProvider({ children }: { children: ReactNode }) { + const [username, setUsername] = useState(null); + const [isAdmin, setIsAdmin] = useState(null); + const [ready, setReady] = useState(false); + + // Restore session on load + useEffect(() => { + const stored = localStorage.getItem(TOKEN_KEY); + if (!stored) { + setReady(true); + return; + } + + api + .me(stored) + .then((u) => { + setUsername(u.username); + setIsAdmin(u.is_admin || false); + }) + .catch(() => localStorage.removeItem(TOKEN_KEY)) + .finally(() => setReady(true)); + }, []); + + const login = useCallback(async (username: string, password: string) => { + const res = await api.login(username, password); + localStorage.setItem(TOKEN_KEY, res.token); + setUsername(res.username); + setIsAdmin(res.is_admin || false); + }, []); + + const register = useCallback(async (username: string, password: string) => { + const res = await api.register(username, password); + localStorage.setItem(TOKEN_KEY, res.token); + setUsername(res.username); + setIsAdmin(res.is_admin || false); + }, []); + + const logout = useCallback(() => { + api.logout().catch(() => { + // Best effort - token is discarded client-side either way + }); + localStorage.removeItem(TOKEN_KEY); + setUsername(null); + setIsAdmin(null); + }, []); + + return ( + + {children} + + ); +} + +export function useAuth(): AuthState { + const ctx = useContext(AuthContext); + if (!ctx) throw new Error('useAuth must be used within AuthProvider'); + return ctx; +} diff --git a/frontend/src/components/AdminLayout.tsx b/frontend/src/components/AdminLayout.tsx new file mode 100644 index 0000000..a3e6355 --- /dev/null +++ b/frontend/src/components/AdminLayout.tsx @@ -0,0 +1,305 @@ +import React from 'react'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; +import { + LayoutDashboard, + Edit3, + LogOut, + Menu, + Home, +} from 'lucide-react'; +import { useAuth } from '../auth'; + +interface AdminLayoutProps { + children: React.ReactNode; +} + +const sidebarItems = [ + { path: '/admin', icon: LayoutDashboard, label: 'Dashboard' }, + { path: '/admin/items/new', icon: Edit3, label: 'New Item' }, +]; + +export function AdminLayout({ children }: AdminLayoutProps) { + const location = useLocation(); + const navigate = useNavigate(); + const { username, isAdmin, logout } = useAuth(); + const [sidebarOpen, setSidebarOpen] = React.useState(false); + + const handleLogout = React.useCallback(() => { + logout(); + navigate('/'); + }, [logout, navigate]); + + if (!isAdmin) { + return ( +
+

Access Denied

+

You don't have admin privileges to access this page.

+
+ ); + } + + const sidebarClasses = `sidebar ${sidebarOpen ? 'open' : ''}`; + const mainContentClasses = `${sidebarOpen ? 'pushed' : ''}`; + + return ( +
+ {/* Mobile overlay */} + {sidebarOpen && ( +
setSidebarOpen(false)} + /> + )} + + {/* Sidebar navigation */} + + + {/* Main content area */} +
+ {/* Mobile header */} +
+ + +

Dashboard

+ + + + Back to Site + +
+ + {/* Page content */} + {children} +
+ + {/* Global styles for admin layout */} + +
+ ); +} diff --git a/frontend/src/components/DeleteConfirmation.tsx b/frontend/src/components/DeleteConfirmation.tsx new file mode 100644 index 0000000..2d90446 --- /dev/null +++ b/frontend/src/components/DeleteConfirmation.tsx @@ -0,0 +1,39 @@ +import { AlertCircle } from 'lucide-react'; +import React from 'react'; + +interface DeleteConfirmationProps { + item: any | null; + onConfirm: () => Promise; + onCancel: () => void; +} + +export function DeleteConfirmation({ item, onConfirm, onCancel }: DeleteConfirmationProps) { + const handleConfirm = React.useCallback(async () => { + await onConfirm(); + // Auto-close after confirmation by calling onCancel to dismiss overlay + }, [onConfirm]); + + return ( +
+
e.stopPropagation()}> +
+ +
+

Are you sure you want to delete "{item?.title || 'this item'}"?

+

This action cannot be undone and will permanently remove the content from the system.

+ +
+ + +
+
+
+ ); +} diff --git a/frontend/src/components/LexicalEditor.tsx b/frontend/src/components/LexicalEditor.tsx new file mode 100644 index 0000000..df8e603 --- /dev/null +++ b/frontend/src/components/LexicalEditor.tsx @@ -0,0 +1,181 @@ +import React, { useEffect, useRef } from 'react'; +import { Bold, Italic, Underline, Heading1, Type, List, ListOrdered, Link2 } from 'lucide-react'; + +interface LexicalEditorProps { + content: string; + onChange: (html: string) => void; + placeholder?: string; + readOnly?: boolean; + className?: string; +} + +export function LexicalEditor({ + content, + onChange, + placeholder = 'Write your content here...', + readOnly = false, + className = '', +}: LexicalEditorProps) { + const textareaRef = useRef(null); + + // Sync textarea value with content prop when it changes from outside + useEffect(() => { + if (textareaRef.current && content !== '') { + textareaRef.current.value = content; + } + }, [content]); + + const handleTextChange = React.useCallback((e: React.ChangeEvent) => { + onChange(e.target.value); + }, [onChange]); + + return ( +
+ {/* Toolbar for basic formatting */} +
+ } label="Bold" onClick={() => {}} disabled={readOnly} /> + } label="Italic" onClick={() => {}} disabled={readOnly} /> + } label="Underline" onClick={() => {}} disabled={readOnly} /> +
+ } label="H1" onClick={() => {}} disabled={readOnly} /> + } label="Paragraph" onClick={() => {}} disabled={readOnly} /> +
+ } label="Bulleted List" onClick={() => {}} disabled={readOnly} /> + } label="Numbered List" onClick={() => {}} disabled={readOnly} /> +
+ } label="Link" onClick={() => {}} disabled={readOnly} /> +
+ +
+