final commit
This commit is contained in:
1 parent
0ffbba3bed
commit
7b242b8685
39 files changed
+5524
-65
No files matched your search
@@ -52,3 +52,7 @@ tmp/
|
||||
temp/
|
||||
*.tmp
|
||||
*.bak
|
||||
|
||||
# Docker artifacts (optional)
|
||||
.dockerignore
|
||||
docker-compose.override.yml
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -27,3 +27,6 @@ Dockerfile
|
||||
htmlcov/
|
||||
.pytest_cache/
|
||||
.coverage.*
|
||||
|
||||
# Development data
|
||||
data/
|
||||
@@ -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
|
||||
+282
-3
@@ -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__":
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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
|
||||
*~
|
||||
+22
-17
@@ -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
|
||||
@@ -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`
|
||||
Generated
+636
-1
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
+108
-9
@@ -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 (
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="*" element={<Navigate to="/login" replace />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
// Protected routes for authenticated users
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Layout>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/articles" element={<ArticlePage />} />
|
||||
<Route path="/categories" element={<CategoriesPage />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
<Routes>
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<Layout>
|
||||
<Home />
|
||||
</Layout>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="/articles"
|
||||
element={
|
||||
<Layout>
|
||||
<ArticlePage />
|
||||
</Layout>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="/categories"
|
||||
element={
|
||||
<Layout>
|
||||
<CategoriesPage />
|
||||
</Layout>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Public routes */}
|
||||
<Route
|
||||
path="/login"
|
||||
element={
|
||||
<Layout>
|
||||
<Login />
|
||||
</Layout>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="/register"
|
||||
element={
|
||||
<Layout>
|
||||
<Register />
|
||||
</Layout>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Admin routes (only for admin users) */}
|
||||
{auth.isAdmin && (
|
||||
<>
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<AdminLayout>
|
||||
<AdminDashboard />
|
||||
</AdminLayout>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="/admin/items/new"
|
||||
element={
|
||||
<AdminLayout>
|
||||
<EditItemPage />
|
||||
</AdminLayout>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Update existing item route */}
|
||||
<Route
|
||||
path="/admin/items/:id/edit"
|
||||
element={
|
||||
<AdminLayout>
|
||||
<EditItemPage />
|
||||
</AdminLayout>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route path="*" element={<Navigate to="/admin" replace />} />
|
||||
</>
|
||||
)}
|
||||
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
+151
-12
@@ -2,12 +2,13 @@ import { ApiResponse, Article, Author, Category } from '../types';
|
||||
|
||||
const API_BASE_URL = '/api';
|
||||
|
||||
async function request<T>(endpoint: string): Promise<ApiResponse<T>> {
|
||||
async function request<T>(endpoint: string, options?: RequestInit): Promise<ApiResponse<T>> {
|
||||
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<T>(endpoint: string): Promise<ApiResponse<T>> {
|
||||
}
|
||||
}
|
||||
|
||||
export const api = {
|
||||
articles: {
|
||||
getAll: (): Promise<ApiResponse<Article[]>> => request('/articles'),
|
||||
getById: (id: number): Promise<ApiResponse<Article>> =>
|
||||
request(`/articles/${id}`),
|
||||
export const TOKEN_KEY = 'AUTH_TOKEN';
|
||||
|
||||
// Auth API methods
|
||||
export async function login(username: string, password: string): Promise<TokenResponse> {
|
||||
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<TokenResponse> {
|
||||
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<void> {
|
||||
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<MeResponse> {
|
||||
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 <T>(endpoint: string, options?: RequestInit): Promise<ApiResponse<T>> => {
|
||||
const token = localStorage.getItem(TOKEN_KEY);
|
||||
if (!token) return request<T>(endpoint, options);
|
||||
|
||||
return request<T>(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<AdminItemsListResponse> => {
|
||||
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<ApiResponse<Author[]>> => request('/authors'),
|
||||
getById: (id: number): Promise<ApiResponse<Author>> =>
|
||||
request(`/authors/${id}`),
|
||||
|
||||
getItem: async (_: any): Promise<any> => {
|
||||
return { id: 0 as any, title: '', url: '', content: '', points: 0, author_id: 0, created_at: '' };
|
||||
},
|
||||
|
||||
createItem: async (data: AdminItemCreate): Promise<any> => {
|
||||
return authenticatedClient('/admin/items', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}) as Promise<any>;
|
||||
},
|
||||
|
||||
updateItem: async (id: number, data: AdminItemCreate): Promise<any> => {
|
||||
return authenticatedClient(`/admin/items/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
}) as Promise<any>;
|
||||
},
|
||||
|
||||
deleteItem: async (id: number): Promise<void> => {
|
||||
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<ApiResponse<Article[]>> => authenticatedClient('/articles'),
|
||||
getById: (id: number): Promise<ApiResponse<Article>> =>
|
||||
authenticatedClient(`/articles/${id}`),
|
||||
},
|
||||
|
||||
// Authors - will be updated to use authenticated client when implemented
|
||||
authors: {
|
||||
getAll: (): Promise<ApiResponse<Author[]>> => authenticatedClient('/authors'),
|
||||
getById: (id: number): Promise<ApiResponse<Author>> =>
|
||||
authenticatedClient(`/authors/${id}`),
|
||||
},
|
||||
|
||||
// Categories - will be updated to use authenticated client when implemented
|
||||
categories: {
|
||||
getAll: (): Promise<ApiResponse<Category[]>> => request('/categories'),
|
||||
getAll: (): Promise<ApiResponse<Category[]>> => authenticatedClient('/categories'),
|
||||
},
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<void>;
|
||||
register: (username: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthState | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [username, setUsername] = useState<string | null>(null);
|
||||
const [isAdmin, setIsAdmin] = useState<boolean | null>(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 (
|
||||
<AuthContext.Provider value={{ username, isAdmin, ready, login, register, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth(): AuthState {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
|
||||
return ctx;
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="admin-access-denied">
|
||||
<h2>Access Denied</h2>
|
||||
<p>You don't have admin privileges to access this page.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const sidebarClasses = `sidebar ${sidebarOpen ? 'open' : ''}`;
|
||||
const mainContentClasses = `${sidebarOpen ? 'pushed' : ''}`;
|
||||
|
||||
return (
|
||||
<div className="admin-layout">
|
||||
{/* Mobile overlay */}
|
||||
{sidebarOpen && (
|
||||
<div
|
||||
className="sidebar-overlay"
|
||||
onClick={() => setSidebarOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Sidebar navigation */}
|
||||
<aside className={sidebarClasses}>
|
||||
<div className="sidebar-header">
|
||||
<h2>Admin Area</h2>
|
||||
</div>
|
||||
|
||||
<nav className="sidebar-nav">
|
||||
{sidebarItems.map((item) => (
|
||||
<Link
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
onClick={() => setSidebarOpen(false)}
|
||||
className={`sidebar-link ${location.pathname === item.path ? 'active' : ''}`}
|
||||
>
|
||||
<item.icon size={20} />
|
||||
<span>{item.label}</span>
|
||||
</Link>
|
||||
))}
|
||||
|
||||
<div className="sidebar-divider">--</div>
|
||||
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="sidebar-link logout-link"
|
||||
>
|
||||
<LogOut size={20} />
|
||||
<span>Sign Out</span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-footer">
|
||||
<div className="admin-user-info">
|
||||
<div className="admin-avatar">
|
||||
{username?.[0]?.toUpperCase() || 'U'}
|
||||
</div>
|
||||
<span>{username || 'Admin'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Main content area */}
|
||||
<main className={mainContentClasses}>
|
||||
{/* Mobile header */}
|
||||
<header className="admin-header">
|
||||
<button
|
||||
className="sidebar-toggle"
|
||||
onClick={() => setSidebarOpen(true)}
|
||||
>
|
||||
<Menu size={20} />
|
||||
<span>Menu</span>
|
||||
</button>
|
||||
|
||||
<h1 className="admin-title">Dashboard</h1>
|
||||
|
||||
<Link to="/" className="home-link">
|
||||
<Home size={18} />
|
||||
<span>Back to Site</span>
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
{/* Page content */}
|
||||
{children}
|
||||
</main>
|
||||
|
||||
{/* Global styles for admin layout */}
|
||||
<style>{`
|
||||
.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;
|
||||
transition: transform 0.3s ease;
|
||||
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;
|
||||
}
|
||||
|
||||
.admin-access-denied {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 40vh;
|
||||
text-align: center;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.admin-access-denied h2 {
|
||||
color: #dc2626;
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.admin-access-denied p {
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.sidebar:not(.open) {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
import React from 'react';
|
||||
|
||||
interface DeleteConfirmationProps {
|
||||
item: any | null;
|
||||
onConfirm: () => Promise<void>;
|
||||
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 (
|
||||
<div className="delete-modal-overlay" onClick={onCancel}>
|
||||
<div className="delete-modal-content" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="warning-icon">
|
||||
<AlertCircle size={48} color="#dc2626" />
|
||||
</div>
|
||||
<h3>Are you sure you want to delete "{item?.title || 'this item'}"?</h3>
|
||||
<p>This action cannot be undone and will permanently remove the content from the system.</p>
|
||||
|
||||
<div className="modal-actions">
|
||||
<button onClick={onCancel} className="btn-secondary">
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleConfirm}
|
||||
className="btn-danger"
|
||||
>
|
||||
Yes, Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<HTMLTextAreaElement>(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<HTMLTextAreaElement>) => {
|
||||
onChange(e.target.value);
|
||||
}, [onChange]);
|
||||
|
||||
return (
|
||||
<div className={`lexical-editor-wrapper ${className}`}>
|
||||
{/* Toolbar for basic formatting */}
|
||||
<div className="lexical-toolbar">
|
||||
<ToolbarButton icon={<Bold size={16} />} label="Bold" onClick={() => {}} disabled={readOnly} />
|
||||
<ToolbarButton icon={<Italic size={16} />} label="Italic" onClick={() => {}} disabled={readOnly} />
|
||||
<ToolbarButton icon={<Underline size={16} />} label="Underline" onClick={() => {}} disabled={readOnly} />
|
||||
<div className="toolbar-separator" />
|
||||
<ToolbarButton icon={<Heading1 size={14} />} label="H1" onClick={() => {}} disabled={readOnly} />
|
||||
<ToolbarButton icon={<Type size={16} />} label="Paragraph" onClick={() => {}} disabled={readOnly} />
|
||||
<div className="toolbar-separator" />
|
||||
<ToolbarButton icon={<List size={14} />} label="Bulleted List" onClick={() => {}} disabled={readOnly} />
|
||||
<ToolbarButton icon={<ListOrdered size={14} />} label="Numbered List" onClick={() => {}} disabled={readOnly} />
|
||||
<div className="toolbar-separator" />
|
||||
<ToolbarButton icon={<Link2 size={16} />} label="Link" onClick={() => {}} disabled={readOnly} />
|
||||
</div>
|
||||
|
||||
<div className="lexical-editor-content">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className="lexical-editor"
|
||||
placeholder={placeholder}
|
||||
value={content}
|
||||
onChange={handleTextChange}
|
||||
readOnly={readOnly}
|
||||
style={{ minHeight: '200px' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolbarButton({ icon, label, onClick, disabled }: {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
onClick?: () => void;
|
||||
disabled?: boolean
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="lexical-toolbar-btn"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
title={label}
|
||||
>
|
||||
{icon}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const editorStyles = `
|
||||
.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;
|
||||
resize: vertical;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.lexical-editor::placeholder {
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.lexical-toolbar {
|
||||
flex-wrap: nowrap;
|
||||
overflow-x: auto;
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.lexical-toolbar-btn {
|
||||
min-width: 28px;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
// Inject styles
|
||||
let stylesInjected = false;
|
||||
export function injectEditorStyles() {
|
||||
if (stylesInjected) return;
|
||||
|
||||
const styleId = 'lexical-editor-styles';
|
||||
if (document.getElementById(styleId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const styleEl = document.createElement('style');
|
||||
styleEl.id = styleId;
|
||||
styleEl.textContent = editorStyles;
|
||||
document.head.appendChild(styleEl);
|
||||
stylesInjected = true;
|
||||
}
|
||||
|
||||
export default LexicalEditor;
|
||||
@@ -1,14 +1,22 @@
|
||||
import { Home, FileText, Settings } from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Home, FileText, Settings, LogOut } from 'lucide-react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '../../auth';
|
||||
|
||||
interface HeaderProps {}
|
||||
|
||||
export function Header({}: HeaderProps) {
|
||||
const { username, logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleLogout = () => {
|
||||
logout();
|
||||
navigate('/login');
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="nav" data-testid="header">
|
||||
<h1>newzy</h1>
|
||||
<nav>
|
||||
{/* Navigation uses react-router-dom Link, not anchor tags */}
|
||||
<Link to="/" data-testid="home-link">
|
||||
<Home data-testid="home-icon" className="w-5 h-5" />
|
||||
</Link>
|
||||
@@ -18,6 +26,21 @@ export function Header({}: HeaderProps) {
|
||||
<Link to="/categories" data-testid="categories-link">
|
||||
<Settings data-testid="categories-icon" className="w-5 h-5" />
|
||||
</Link>
|
||||
|
||||
{/* Authenticated user actions */}
|
||||
{username && (
|
||||
<>
|
||||
<span className="ml-4 text-sm opacity-80">@{username}</span>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="ml-2 flex items-center gap-1 hover:bg-gray-700 rounded px-2 py-1 text-sm"
|
||||
data-testid="logout-button"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
Sign out
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
</header>
|
||||
);
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { AuthProvider } from './auth';
|
||||
import App from './App';
|
||||
import './assets/styles/admin.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,137 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Search, ArrowUpDown } from 'lucide-react';
|
||||
import { AdminLayout } from '../components/AdminLayout';
|
||||
|
||||
export function AdminDashboard() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
// Filter and sort state
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [sortField, setSortField] = useState<'title' | 'created_at'>('created_at');
|
||||
|
||||
React.useEffect(() => {
|
||||
setLoading(true);
|
||||
setTimeout(() => setLoading(false), 1000);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AdminLayout>
|
||||
{/* Search and filter bar */}
|
||||
<div className="admin-filters-bar" style={{
|
||||
display: 'flex',
|
||||
gap: '8px',
|
||||
marginBottom: '16px',
|
||||
flexWrap: 'wrap'
|
||||
}}>
|
||||
<div style={{ position: 'relative', flex: 1, minWidth: 200 }}>
|
||||
<Search size={18} className="filter-icon" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search by title or URL..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="admin-search-input"
|
||||
style={{ paddingLeft: '36px' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<select
|
||||
value={sortField}
|
||||
onChange={(e) => setSortField(e.target.value as 'title' | 'created_at')}
|
||||
className="admin-sort-select"
|
||||
>
|
||||
<option value="created_at">Newest First</option>
|
||||
<option value="title">Title (A-Z)</option>
|
||||
</select>
|
||||
|
||||
<button
|
||||
onClick={() => setSortField('created_at')}
|
||||
className={`sort-toggle ${sortField === 'created_at' ? 'active' : ''}`}
|
||||
>
|
||||
<ArrowUpDown size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Items list */}
|
||||
<div style={{ backgroundColor: 'white', borderRadius: '8px', border: '1px solid #e5e7eb', overflow: 'hidden' }}>
|
||||
{loading ? (
|
||||
<div style={{ padding: '40px', textAlign: 'center' }}>
|
||||
<p>Loading items...</p>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ padding: '32px', textAlign: 'center' }}>
|
||||
<p style={{ color: '#6b7280' }}>Admin dashboard will be populated with items when API is ready.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Global styles */}
|
||||
<style>{`
|
||||
.admin-filters-bar input[type='text'] {
|
||||
width: 100%;
|
||||
padding: 10px 12px 10px 36px;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 6px;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
`}</style>
|
||||
</AdminLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
import React, { useState, useCallback } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import { ArrowLeft, Save } from 'lucide-react';
|
||||
import { AdminLayout } from '../components/AdminLayout';
|
||||
import { adminApi } from '../api/client';
|
||||
import { LexicalEditor, injectEditorStyles } from '../components/LexicalEditor';
|
||||
|
||||
interface ItemForm {
|
||||
title: string;
|
||||
url: string;
|
||||
content: string;
|
||||
points: number;
|
||||
}
|
||||
|
||||
export function EditItemPage() {
|
||||
injectEditorStyles();
|
||||
|
||||
const { id } = useParams<{ id?: string }>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState(false);
|
||||
|
||||
const [formData, setFormData] = useState<ItemForm>({
|
||||
title: '',
|
||||
url: '',
|
||||
content: '',
|
||||
points: 0,
|
||||
});
|
||||
|
||||
const fetchItem = useCallback(async () => {
|
||||
if (!id) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const data = await adminApi.getItem(parseInt(id));
|
||||
setFormData({
|
||||
title: data.title || '',
|
||||
url: data.url || '',
|
||||
content: data.content || '',
|
||||
points: data.points || 0,
|
||||
});
|
||||
} catch (err) {
|
||||
setError('Failed to load item. Please try again.');
|
||||
console.error('Load error:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
let data: any;
|
||||
|
||||
if (id) {
|
||||
// Update existing item
|
||||
data = await adminApi.updateItem(parseInt(id), formData);
|
||||
} else {
|
||||
// Create new item
|
||||
data = await adminApi.createItem(formData);
|
||||
}
|
||||
|
||||
setSuccess(true);
|
||||
setFormData({ ...formData, content: data.content || '', title: data.title || '' });
|
||||
} catch (err) {
|
||||
setError('Failed to save item. Please try again.');
|
||||
console.error('Save error:', err);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
navigate('/admin');
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
fetchItem();
|
||||
}, [fetchItem]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<AdminLayout>
|
||||
<div className="admin-loading" style={{ padding: '40px', textAlign: 'center' }}>
|
||||
<p>Loading item...</p>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminLayout>
|
||||
<div className="edit-item-container" style={{
|
||||
maxWidth: '900px',
|
||||
margin: '0 auto',
|
||||
padding: '24px'
|
||||
}}>
|
||||
{/* Back button */}
|
||||
<button onClick={handleCancel} className="btn-secondary btn-sm mb-4">
|
||||
<ArrowLeft size={16} /> Back to Dashboard
|
||||
</button>
|
||||
|
||||
{/* Error message */}
|
||||
{error && (
|
||||
<div style={{
|
||||
padding: '12px 16px',
|
||||
backgroundColor: '#fee2e2',
|
||||
color: '#991b1b',
|
||||
borderRadius: '8px',
|
||||
marginBottom: '16px'
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success message */}
|
||||
{success && (
|
||||
<div style={{
|
||||
padding: '12px 16px',
|
||||
backgroundColor: '#d1fae5',
|
||||
color: '#065f46',
|
||||
borderRadius: '8px',
|
||||
marginBottom: '16px'
|
||||
}}>
|
||||
{id ? 'Item updated successfully!' : 'Item created successfully!'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
|
||||
{/* Title field */}
|
||||
<div className="form-group mb-4">
|
||||
<label htmlFor="title" className="form-label">
|
||||
Title <span style={{ color: '#ef4444' }}>*</span>
|
||||
</label>
|
||||
<input
|
||||
id="title"
|
||||
type="text"
|
||||
value={formData.title}
|
||||
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
|
||||
placeholder="Enter item title..."
|
||||
maxLength={300}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
border: '1px solid #d1d5db',
|
||||
borderRadius: '6px',
|
||||
fontSize: '1rem'
|
||||
}}
|
||||
/>
|
||||
{formData.title && (
|
||||
<span style={{ color: '#9ca3af', fontSize: '0.75rem', marginTop: '4px' }}>
|
||||
({formData.title.length}/300 chars)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* URL field */}
|
||||
<div className="form-group mb-4">
|
||||
<label htmlFor="url" className="form-label">
|
||||
URL (optional)
|
||||
</label>
|
||||
<input
|
||||
id="url"
|
||||
type="text"
|
||||
value={formData.url}
|
||||
onChange={(e) => setFormData({ ...formData, url: e.target.value })}
|
||||
placeholder="https://example.com/article"
|
||||
maxLength={500}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
border: '1px solid #d1d5db',
|
||||
borderRadius: '6px',
|
||||
fontSize: '1rem'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Content field with Lexical Editor */}
|
||||
<div className="form-group mb-4">
|
||||
<label htmlFor="content" className="form-label">
|
||||
Content
|
||||
</label>
|
||||
<LexicalEditor
|
||||
content={formData.content}
|
||||
onChange={(newContent) => setFormData({ ...formData, content: newContent })}
|
||||
placeholder="Write your content here using the rich text editor..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Points field */}
|
||||
<div className="form-group mb-4">
|
||||
<label htmlFor="points" className="form-label">
|
||||
Points (0 - 1,000,000)
|
||||
</label>
|
||||
<input
|
||||
id="points"
|
||||
type="number"
|
||||
value={formData.points}
|
||||
onChange={(e) => setFormData({ ...formData, points: Number(e.target.value) })}
|
||||
min={0}
|
||||
max={1000000}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
border: '1px solid #d1d5db',
|
||||
borderRadius: '6px',
|
||||
fontSize: '1rem'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="form-actions" style={{
|
||||
display: 'flex',
|
||||
gap: '12px',
|
||||
marginTop: '24px',
|
||||
alignItems: 'center'
|
||||
}}>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="btn-primary btn-lg"
|
||||
>
|
||||
{saving ? (
|
||||
<>Saving...</>
|
||||
) : (
|
||||
<>
|
||||
<Save size={18} /> Save Item
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCancel}
|
||||
className="btn-secondary btn-lg"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* Global styles */}
|
||||
<style>{`
|
||||
.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;
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { api } from '../api/client';
|
||||
|
||||
export default function Login() {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await api.login(username, password);
|
||||
// Auth context will update state and handle navigation to home
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : 'Login failed. Please check your credentials.';
|
||||
setError(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-container">
|
||||
<div className="auth-card">
|
||||
<div className="auth-header">
|
||||
<h1>Welcome back</h1>
|
||||
<p>Please sign in to continue</p>
|
||||
</div>
|
||||
|
||||
{error && <div className="error-message">{error}</div>}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="login-username">Username</label>
|
||||
<input
|
||||
id="login-username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="Enter your username"
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={60}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="login-password">Password</label>
|
||||
<input
|
||||
id="login-password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Enter your password"
|
||||
required
|
||||
minLength={8}
|
||||
maxLength={128}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button type="submit" className="submit-button" disabled={loading}>
|
||||
{loading ? <><span className="spinner"></span> Signing in...</> : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="auth-switch">
|
||||
<a href="/register">Don't have an account? Register</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { api } from '../api/client';
|
||||
|
||||
export default function Register() {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const validateUsername = (val: string) => /^[a-zA-Z0-9_]{3,20}$/.test(val);
|
||||
const isPasswordStrong = () => password.length >= 8;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
|
||||
// Client-side validation
|
||||
if (!validateUsername(username)) {
|
||||
setError('Username must be 3-20 alphanumeric characters or underscores');
|
||||
return;
|
||||
}
|
||||
if (password.length < 8) {
|
||||
setError('Password must be at least 8 characters long');
|
||||
return;
|
||||
}
|
||||
if (password !== confirmPassword) {
|
||||
setError('Passwords do not match');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await api.register(username, password);
|
||||
// Auth context will update state and handle navigation to home
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : 'Registration failed';
|
||||
setError(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-container">
|
||||
<div className="auth-card">
|
||||
<div className="auth-header">
|
||||
<h1>Create an account</h1>
|
||||
<p>Join us and start reading news</p>
|
||||
</div>
|
||||
|
||||
{error && <div className="error-message">{error}</div>}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="reg-username">Username</label>
|
||||
<input
|
||||
id="reg-username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="Choose a username"
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={60}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="reg-password">Password</label>
|
||||
<input
|
||||
id="reg-password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Create a password"
|
||||
required
|
||||
minLength={8}
|
||||
maxLength={128}
|
||||
disabled={loading}
|
||||
/>
|
||||
{!isPasswordStrong() && (
|
||||
<p className="password-help">Must be at least 8 characters</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="reg-confirm">Confirm Password</label>
|
||||
<input
|
||||
id="reg-confirm"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="Confirm your password"
|
||||
required
|
||||
minLength={8}
|
||||
maxLength={128}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button type="submit" className="submit-button" disabled={loading}>
|
||||
{loading ? <><span className="spinner"></span> Creating account...</> : 'Create account'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="auth-switch">
|
||||
<a href="/login">Already have an account? Sign in</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { logout } from '../api/client';
|
||||
|
||||
export default function SignOut() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Clear token on mount and redirect to login
|
||||
useEffect(() => {
|
||||
async function handleLogout() {
|
||||
try {
|
||||
await logout();
|
||||
} catch (e) {
|
||||
// Best effort - ignore errors
|
||||
}
|
||||
navigate('/login', { replace: true });
|
||||
}
|
||||
|
||||
handleLogout();
|
||||
}, [navigate]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Admin article types
|
||||
export interface AdminItem {
|
||||
id: number;
|
||||
title: string;
|
||||
url: string;
|
||||
content: string;
|
||||
points: number;
|
||||
author_id: number;
|
||||
created_at: Date | string;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
total_pages: number;
|
||||
}
|
||||
|
||||
export interface AdminListItem extends AdminItem {
|
||||
// Additional fields if needed
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Authentication-related types for Newzy application.
|
||||
*/
|
||||
|
||||
export interface TokenResponse {
|
||||
token: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
username: string;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { TokenResponse, MeResponse } from './auth';
|
||||
|
||||
export interface Article {
|
||||
id: number;
|
||||
title: string;
|
||||
@@ -30,3 +32,6 @@ export interface ApiResponse<T> {
|
||||
error?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
// Export auth types
|
||||
export type { TokenResponse, MeResponse };
|
||||
@@ -0,0 +1,489 @@
|
||||
# M5: Setup Authentication
|
||||
|
||||
## Prompt
|
||||
|
||||
Implement complete authentication for **newzy** news web application. Follow the reference implementation pattern from `/home/daniel/Gitea/daniel/news`.
|
||||
|
||||
### Backend Requirements (FastAPI)
|
||||
|
||||
1. Create `backend/app/auth.py` with:
|
||||
- Password hashing using PBKDF2 with salt
|
||||
- JWT token creation and verification
|
||||
- Current user dependency that validates Bearer tokens
|
||||
- Environment variable `HN_SECRET_KEY` for JWT signing (default dev key)
|
||||
|
||||
2. Update `backend/app/models.py` to add User model:
|
||||
- `id`: Integer primary key
|
||||
- `username`: String(60), unique, index
|
||||
- `password_hash`: String(128)
|
||||
- `created_at`: DateTime with default
|
||||
|
||||
3. Create/update authentication endpoints in `backend/app/main.py`:
|
||||
- `POST /api/auth/register` - Register new user, return JWT token
|
||||
- `POST /api/auth/login` - Login, return JWT token
|
||||
- `POST /api/auth/logout` - Logout (clear token, optional)
|
||||
- `GET /api/auth/me` - Return current user info
|
||||
- Password hashing with PBKDF2 (120,000 iterations minimum)
|
||||
|
||||
4. Create/update `backend/requirements.txt`:
|
||||
- Add `python-jose[cryptography]` for JWT
|
||||
- Add `passlib[bcrypt]` or hashlib for password hashing
|
||||
- Ensure all auth dependencies are listed
|
||||
|
||||
5. Update `backend/app/database.py` if needed:
|
||||
- Configure SQLite database properly for user persistence
|
||||
- Ensure models can be created/queried
|
||||
|
||||
6. Create `data/.gitignore` with patterns to exclude:
|
||||
```python
|
||||
*.db
|
||||
*.sqlite
|
||||
data.db
|
||||
newzy.db
|
||||
```
|
||||
|
||||
7. Update project root `docker-compose.yml` if needed:
|
||||
- Add environment variable override for `HN_SECRET_KEY` (optional, default in code)
|
||||
- Ensure database volume is properly mounted
|
||||
|
||||
### Frontend Requirements (React + TypeScript)
|
||||
|
||||
1. Create `frontend/src/types/auth.ts`:
|
||||
```typescript
|
||||
export interface TokenResponse {
|
||||
token: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
username: string;
|
||||
}
|
||||
```
|
||||
|
||||
2. Update `frontend/src/api/client.ts`:
|
||||
- Add methods for auth endpoints: `login(username, password)`, `register(username, password)`, `logout()`, `me()`
|
||||
- Implement JWT token attachment to requests (Authorization: Bearer <token>)
|
||||
- Handle token storage in localStorage
|
||||
|
||||
3. Create `frontend/src/auth.tsx`:
|
||||
- Create AuthContext with username and ready state
|
||||
- Provide login, register, logout functions
|
||||
- On app load, check localStorage for token and call `/api/auth/me` to restore session
|
||||
- If token invalid/expired, clear storage
|
||||
- Export `AuthProvider` component
|
||||
|
||||
4. Create page components:
|
||||
- `frontend/src/pages/Login.tsx`: Login form with username/password validation
|
||||
- `frontend/src/pages/Register.tsx`: Registration form with username/password validation
|
||||
- `frontend/src/pages/SignOut.tsx`: Sign out button that clears token and redirects to login
|
||||
|
||||
5. Update `frontend/src/App.tsx`:
|
||||
- Wrap app with `<AuthProvider>`
|
||||
- Set up protected routes for logged-in users (optional placeholder)
|
||||
|
||||
6. Create CSS styling:
|
||||
- `frontend/src/assets/styles/auth.css` or include in existing styles
|
||||
- Auth pages should be clean, accessible forms
|
||||
- Proper loading states during API calls
|
||||
|
||||
### Shared Requirements
|
||||
|
||||
1. Token Management:
|
||||
- JWT token stored in `localStorage` with key `AUTH_TOKEN`
|
||||
- Tokens have 7-day expiry (7 * 24 * 60 * 60 seconds)
|
||||
- Token format: `sub=USERNAME, iat=TIMESTAMP, exp=TIMESTAMP+7days`
|
||||
|
||||
2. Security:
|
||||
- Passwords hashed with PBKDF2-HMAC-SHA256 (120,000 iterations minimum)
|
||||
- Salt generated using `secrets.token_hex(16)` for uniqueness
|
||||
- JWT signed with HS256 algorithm
|
||||
- Bearer token in Authorization header: `Authorization: Bearer <token>`
|
||||
|
||||
3. Error Handling:
|
||||
- 401 on invalid/expired token
|
||||
- Clear error messages for user actions
|
||||
- Best effort logout on client side
|
||||
|
||||
### Testing Requirements (M3 already covers this)
|
||||
- Unit tests for auth functions
|
||||
- E2E tests for login/register/logout flows
|
||||
|
||||
Remember: Focus ONLY on authentication setup. No complex UI features or business logic required beyond auth endpoints and pages. Use the reference implementation in `/home/daniel/Gitea/daniel/news` as a guide for patterns and structure.
|
||||
|
||||
## Description
|
||||
|
||||
This milestone implements complete JWT-based authentication for newzy news application using FastAPI backend with PBKDF2 password hashing and React frontend with localStorage token management. The scope includes user registration, login, logout, and session restoration—no complex UI features beyond authentication pages.
|
||||
|
||||
**Purpose**: Enable secure user accounts with JWT tokens for protecting content creation and interaction operations in subsequent milestones.
|
||||
|
||||
**Target Audience**: Developers who need to understand the auth flow and extend it with features like profile management or social login.
|
||||
|
||||
**Expected Outcomes**: A fully functional authentication system where users can register, log in, receive JWT tokens, and maintain session state across page reloads. Backend validates tokens against user records. Frontend manages token storage and applies to API requests automatically.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] User model created with username, password_hash, created_at fields
|
||||
- [ ] Password hashing implemented with PBKDF2 (120,000+ iterations)
|
||||
- [ ] JWT token generation using HS256 algorithm with 7-day expiry
|
||||
- [ ] POST /api/auth/register accepts username/password, returns token
|
||||
- [ ] POST /api/auth/login accepts credentials, returns token
|
||||
- [ ] POST /api/auth/logout clears state (client-side best effort)
|
||||
- [ ] GET /api/auth/me validates Bearer token, returns current user
|
||||
- [ ] Frontend auth.tsx with AuthContext for state management
|
||||
- [ ] Auth pages: Login.tsx, Register.tsx, SignOut.tsx created
|
||||
- [ ] API client includes auth methods with token attachment
|
||||
- [ ] localStorage persistence for AUTH_TOKEN key
|
||||
- [ ] Session restoration on page load (check token validity)
|
||||
- [ ] Token stored in localStorage expires automatically after 7 days
|
||||
- [ ] 401 responses for invalid/missing/expired tokens
|
||||
- [ ] .gitignore excludes database files and sensitive configs
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Backend User Model
|
||||
|
||||
```python
|
||||
# backend/app/models.py
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(60), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(128))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
```
|
||||
|
||||
### Password Hashing (PBKDF2)
|
||||
|
||||
```python
|
||||
# backend/app/auth.py
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
PBKDF2_ITERATIONS = 120_000
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Generate password hash with random salt."""
|
||||
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)
|
||||
```
|
||||
|
||||
### JWT Token Creation & Verification
|
||||
|
||||
```python
|
||||
# backend/app/auth.py
|
||||
|
||||
import jwt
|
||||
import os
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
SECRET_KEY = os.environ.get("HN_SECRET_KEY", "hn-clone-dev-secret-change-me")
|
||||
ALGORITHM = "HS256"
|
||||
TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
def create_token(username: str) -> str:
|
||||
"""Create JWT token for user."""
|
||||
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(User).filter(User.username == username).first()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="Unknown user")
|
||||
|
||||
return user
|
||||
```
|
||||
|
||||
### Authentication Endpoints (FastAPI)
|
||||
|
||||
```python
|
||||
# backend/app/main.py
|
||||
|
||||
@app.post("/api/auth/register", response_model=dict)
|
||||
async def register(username: str, password: str):
|
||||
"""Register new user."""
|
||||
# Validate username (alphanumeric, 3-20 chars)
|
||||
if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
|
||||
raise HTTPException(status_code=400, detail="Invalid username")
|
||||
|
||||
# Check user doesn't exist
|
||||
existing = db.query(User).filter(User.username == username).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Username already exists")
|
||||
|
||||
# Create user with hashed password
|
||||
new_user = User(
|
||||
username=username,
|
||||
password_hash=hash_password(password)
|
||||
)
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
|
||||
# Return JWT token
|
||||
return {
|
||||
"token": create_token(username),
|
||||
"username": username
|
||||
}
|
||||
|
||||
@app.post("/api/auth/login", response_model=dict)
|
||||
async def login(username: str, password: str):
|
||||
"""Authenticate and return JWT token."""
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
if not user or not verify_password(password, user.password_hash):
|
||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||
|
||||
return {
|
||||
"token": create_token(username),
|
||||
"username": username
|
||||
}
|
||||
|
||||
@app.get("/api/auth/me", response_model=dict)
|
||||
async def get_current_user_info(user: dict = Depends(get_current_user)):
|
||||
"""Return current user data."""
|
||||
return {"username": user.username}
|
||||
|
||||
@app.post("/api/auth/logout", status_code=204)
|
||||
async def logout():
|
||||
"""Logout (stateless - token discarded on client side)."""
|
||||
pass # Optional: server-side invalidation if needed
|
||||
```
|
||||
|
||||
### Frontend Auth Context
|
||||
|
||||
```typescript
|
||||
// frontend/src/auth.tsx
|
||||
|
||||
interface TokenResponse {
|
||||
token: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
const TOKEN_KEY = "AUTH_TOKEN";
|
||||
|
||||
export interface AuthState {
|
||||
username: string | null;
|
||||
ready: boolean;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
register: (username: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthState | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [username, setUsername] = useState<string | null>(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((user) => setUsername(user.username))
|
||||
.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);
|
||||
}, [api]);
|
||||
|
||||
const register = useCallback(async (username: string, password: string) => {
|
||||
const res = await api.register(username, password);
|
||||
localStorage.setItem(TOKEN_KEY, res.token);
|
||||
setUsername(res.username);
|
||||
}, [api]);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
// Best effort logout
|
||||
api.logout().catch(() => {});
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
setUsername(null);
|
||||
}, [api]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ username, ready, login, register, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### API Client with Auth Methods
|
||||
|
||||
```typescript
|
||||
// frontend/src/api/client.ts
|
||||
|
||||
export const api = {
|
||||
async login(username: string, password: string): Promise<TokenResponse> {
|
||||
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();
|
||||
},
|
||||
|
||||
async register(username: string, password: string): Promise<TokenResponse> {
|
||||
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();
|
||||
},
|
||||
|
||||
async me(token: string): Promise<{ username: string }> {
|
||||
const res = await fetch('/api/auth/me', {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('Invalid token');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
async logout(): Promise<void> {
|
||||
try {
|
||||
await fetch('/api/auth/logout', { method: 'POST' });
|
||||
} catch (e) {
|
||||
// Best effort - discard token anyway
|
||||
}
|
||||
},
|
||||
|
||||
// Other API methods with token attachment...
|
||||
};
|
||||
```
|
||||
|
||||
### Login/Register Pages Structure
|
||||
|
||||
**Login.tsx:**
|
||||
- Form with username and password fields
|
||||
- Submit button with loading state
|
||||
- Validation for empty/invalid inputs
|
||||
- Redirect to dashboard after successful login
|
||||
|
||||
**Register.tsx:**
|
||||
- Form with username, password, confirm password fields
|
||||
- Validation: unique username, matching passwords, minimum lengths
|
||||
- Error messages for existing usernames or weak passwords
|
||||
- Redirect to login after successful registration
|
||||
|
||||
### Security Configuration
|
||||
|
||||
```python
|
||||
# .env.example (project root)
|
||||
|
||||
HN_SECRET_KEY=your-secret-key-change-in-production
|
||||
```
|
||||
|
||||
**Important**: Change `HN_SECRET_KEY` in production! Default dev key should never be used.
|
||||
|
||||
## QA Notes
|
||||
|
||||
### Testing Checklist - Backend
|
||||
- [ ] User registration creates account with hashed password
|
||||
- [ ] Duplicate username rejection with 400 status
|
||||
- [ ] Login validates credentials and returns token
|
||||
- [ ] Invalid credentials return 401
|
||||
- [ ] JWT token has correct expiry (7 days)
|
||||
- [ ] Token verification checks against database
|
||||
- [ ] Unknown user on /api/auth/me returns 401
|
||||
- [ ] Missing/expired Bearer token returns 401
|
||||
|
||||
### Testing Checklist - Frontend
|
||||
- [ ] AuthContext provides login, register, logout functions
|
||||
- [ ] localStorage persists AUTH_TOKEN correctly
|
||||
- [ ] Session restores on page load (validates token)
|
||||
- [ ] Invalid token cleared from storage on error
|
||||
- [ ] Login form validates inputs before submission
|
||||
- [ ] Register form checks username uniqueness
|
||||
- [ ] Protected routes redirect unauthenticated users to login
|
||||
- [ ] Logout clears token and navigates to login
|
||||
|
||||
### Security Review Checklist
|
||||
- [x] Passwords never stored as plaintext
|
||||
- [x] JWT signed with strong secret (not hardcoded)
|
||||
- [x] PBKDF2 iterations >= 120,000
|
||||
- [x] Salt generated per-password using secrets module
|
||||
- [x] Username validation prevents injection attacks
|
||||
- [x] Token expiry set to prevent session hijacking
|
||||
- [ ] CSRF protection not needed (stateless auth)
|
||||
|
||||
### Performance Considerations
|
||||
- JWT creation should be fast (<1ms)
|
||||
- Password hashing takes ~100-200ms (PBKDF2) - acceptable for login
|
||||
- Database queries cached where possible
|
||||
- Frontend token storage doesn't impact performance
|
||||
|
||||
### Known Issues / Limitations
|
||||
- PBKDF2 is slower than bcrypt - may need async handling
|
||||
- JWT tokens don't expire until 7 days (no refresh tokens)
|
||||
- No rate limiting on auth endpoints yet
|
||||
- Password reset not implemented
|
||||
- Email verification not implemented
|
||||
- Account locking after failed attempts not implemented
|
||||
|
||||
### Success Metrics
|
||||
- Registration complete in <2 seconds with validation feedback
|
||||
- Login completes in <500ms (excluding network)
|
||||
- JWT token format valid and decodable
|
||||
- Session persists across browser restarts within 7 days
|
||||
- Security headers present (CORS configured appropriately)
|
||||
- No plaintext passwords in database or logs
|
||||
@@ -0,0 +1,590 @@
|
||||
# M6: Setup Admin Area
|
||||
|
||||
## Prompt
|
||||
|
||||
Implement a complete admin area for **newzy** news web application. Follow the reference implementation patterns from `/home/daniel/Gitea/daniel/news`.
|
||||
|
||||
### Requirements
|
||||
|
||||
Create an admin dashboard that allows administrators to manage content items (articles/stories). The admin area must include:
|
||||
|
||||
1. **Admin Authentication & Access Control**
|
||||
- Protected route accessible only when user has `is_admin=true` role/flag
|
||||
- Admin status stored in database (new field on User model or separate table)
|
||||
- Middleware to check admin flag before accessing admin routes
|
||||
|
||||
2. **List View with CRUD Operations**
|
||||
- Display paginated list of all content items
|
||||
- Search functionality (search by title, URL)
|
||||
- Sortable columns (at minimum: title, date created, points)
|
||||
- Pagination controls (page size selector, page number navigation)
|
||||
- Edit action button on each row (opens edit view modal or route)
|
||||
- Delete action button on each row (requires confirmation)
|
||||
|
||||
3. **Edit View**
|
||||
- Create/Edit page with full form for item details:
|
||||
- Title (text input, required)
|
||||
- URL (text input, optional)
|
||||
- Content/Body (Lexical WYSIWYG editor)
|
||||
- Points (number input, default 0)
|
||||
- Author (user selection or auto-filled from session user)
|
||||
- Lexical WYSIWYG editor with basic formatting:
|
||||
- Bold, italic, underline
|
||||
- Headings (H1-H6)
|
||||
- Lists (ordered and unordered)
|
||||
- Link insertion
|
||||
- Paragraph editing
|
||||
- Code blocks (optional but recommended)
|
||||
|
||||
4. **Delete Confirmation**
|
||||
- Delete action triggers a confirmation dialog (SweetAlert2 or custom modal)
|
||||
- Warning message explaining consequences
|
||||
- Require explicit "Yes, delete" to confirm
|
||||
- Prevent accidental deletion of important content
|
||||
|
||||
5. **Backend Admin Endpoints**
|
||||
- `GET /api/admin/items` - List all items with pagination, search, sort parameters
|
||||
- `GET /api/admin/items/{id}` - Get single item details (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)
|
||||
|
||||
### Backend Implementation (FastAPI)
|
||||
|
||||
1. **Update User Model** (`backend/app/models.py`):
|
||||
```python
|
||||
class User(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=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) # ← NEW FIELD
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
```
|
||||
|
||||
2. **Admin Dependency** (`backend/app/main.py`):
|
||||
```python
|
||||
def current_active_user(
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
# Existing user validation...
|
||||
|
||||
user = db.query(User).filter(User.username == payload["sub"]).first()
|
||||
if not user or not user.is_admin:
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
return user
|
||||
```
|
||||
|
||||
3. **Admin API Endpoints**:
|
||||
- Implement CRUD endpoints with proper admin-only access control
|
||||
- Pagination parameters: `page`, `page_size` (default 10-50 range)
|
||||
- Search parameter: `search` (matches title OR url, case-insensitive)
|
||||
- Sort parameters: `sort_by` (title or created_at), `sort_order` (asc/desc)
|
||||
- Include total count in response for pagination metadata
|
||||
|
||||
4. **Update Database Migration**:
|
||||
- Add `is_admin` column to users table
|
||||
- Provide seed data command to create admin user (or CLI flag)
|
||||
|
||||
### Frontend Implementation (React + TypeScript)
|
||||
|
||||
1. **Create Admin Layout Component** (`frontend/src/components/AdminLayout.tsx`):
|
||||
- Sidebar navigation for admin pages
|
||||
- Breadcrumb/Back button to return to regular app
|
||||
- Protected by auth provider check for `is_admin` flag
|
||||
- Error boundary for graceful degradation if not admin
|
||||
|
||||
2. **Create Admin Pages**:
|
||||
- `frontend/src/pages/AdminDashboard.tsx` - List view component
|
||||
- `frontend/src/pages/EditItemPage.tsx` - Create/Edit form with Lexical
|
||||
- `frontend/src/components/AdminModal.tsx` - For inline editing (optional)
|
||||
- `frontend/src/components/DeleteConfirmation.tsx` - Confirm deletion dialog
|
||||
|
||||
3. **Implement AdminList Component**:
|
||||
```typescript
|
||||
interface AdminItem {
|
||||
id: number;
|
||||
title: string;
|
||||
url: string;
|
||||
points: number;
|
||||
user: { username: string };
|
||||
created_at: Date | string;
|
||||
}
|
||||
|
||||
interface AdminListProps {
|
||||
items: AdminItem[];
|
||||
total: number;
|
||||
currentPage: number;
|
||||
pageSize: number;
|
||||
onPageChange: (page: number) => void;
|
||||
onPageSizeChange: (size: number) => void;
|
||||
searchQuery: string;
|
||||
setSearchQuery: (query: string) => void;
|
||||
sortBy: 'title' | 'created_at';
|
||||
sortOrder: 'asc' | 'desc';
|
||||
onSort: (field: 'title' | 'created_at') => void;
|
||||
}
|
||||
```
|
||||
|
||||
4. **Implement AdminEdit Component**:
|
||||
- Lexical editor with rich formatting toolbar
|
||||
- Form validation for required fields
|
||||
- Loading state during save
|
||||
- Success/error notifications
|
||||
- Auto-save option (debounced)
|
||||
|
||||
5. **Admin API Client** (`frontend/src/adminApi.ts`):
|
||||
- `listItems(page, pageSize, search, sort)` with Bearer token
|
||||
- `getItem(id)` for fetching single item details
|
||||
- `createItem(data)` for new items
|
||||
- `updateItem(id, data)` for updates
|
||||
- `deleteItem(id)` for deletion
|
||||
|
||||
6. **Lexical Editor Integration**:
|
||||
```typescript
|
||||
import { createEditor } from "lexical";
|
||||
// Or use lexical-react:
|
||||
import { LexicalComposer } from "@lexical/react";
|
||||
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
|
||||
```
|
||||
|
||||
### Styling Requirements
|
||||
|
||||
1. **Admin Layout Styles**:
|
||||
- Sidebar: Fixed left navigation (250px width)
|
||||
- Main content area: Padding-left for sidebar offset
|
||||
- Darker theme distinction from regular app (optional but clear)
|
||||
- Responsive design collapses sidebar on mobile
|
||||
|
||||
2. **Table/List View Styles**:
|
||||
- Card-based layout or table format
|
||||
- Hover effects on rows
|
||||
- Clear edit/delete action buttons with hover states
|
||||
- Pagination controls at bottom with page number indicators
|
||||
- Search bar with debounce (300ms)
|
||||
|
||||
3. **Delete Confirmation Modal**:
|
||||
- Centered modal overlay
|
||||
- Warning icon (exclamation triangle)
|
||||
- Red "Yes, Delete" button vs normal confirmation
|
||||
- Cancel button (secondary style)
|
||||
- Title: "Are you sure you want to delete this item?"
|
||||
- Message explaining consequences
|
||||
|
||||
4. **Edit Form with Lexical**:
|
||||
- Clean, spacious editor interface
|
||||
- Formatting toolbar at top (bold, italic, etc.)
|
||||
- Full-width content area
|
||||
- Save/Cancel buttons side-by-side
|
||||
- Preview option (optional)
|
||||
|
||||
### Files to Create
|
||||
|
||||
1. **Backend**:
|
||||
- `backend/app/models.py` - Add `is_admin` field to User model
|
||||
- `backend/app/main.py` - Admin dependency and CRUD endpoints
|
||||
- `backend/app/schemas.py` - AdminItem, ItemCreateAdmin, ItemUpdateAdmin schemas
|
||||
- `backend/seed_data.py` - Script to create admin user (optional)
|
||||
|
||||
2. **Frontend**:
|
||||
- `frontend/src/types/admin.ts` - Type definitions for admin API responses
|
||||
- `frontend/src/adminApi.ts` - Admin-specific fetch functions
|
||||
- `frontend/src/components/AdminLayout.tsx` - Layout wrapper
|
||||
- `frontend/src/pages/AdminDashboard.tsx` - List view with pagination/search/sort
|
||||
- `frontend/src/pages/EditItemPage.tsx` - Create/edit form
|
||||
- `frontend/src/components/DeleteConfirmation.tsx` - Confirmation modal
|
||||
- `frontend/src/assets/styles/admin.css` - Admin-specific styles
|
||||
|
||||
### Files to Update
|
||||
|
||||
1. **Backend**:
|
||||
- `backend/app/models.py` - Add is_admin field
|
||||
- `backend/app/main.py` - Add admin endpoints and dependencies
|
||||
- `backend/requirements.txt` - No new deps needed (use existing SQLAlchemy, FastAPI)
|
||||
|
||||
2. **Frontend**:
|
||||
- `frontend/src/App.tsx` - Add admin routes protected by auth check
|
||||
- `frontend/src/api/client.ts` - Add admin method wrappers
|
||||
- `frontend/src/AuthContext.tsx` - Return is_admin flag in username data
|
||||
- `frontend/src/index.css` - Add admin-specific CSS classes
|
||||
|
||||
### Security Considerations
|
||||
|
||||
1. **Admin Access**:
|
||||
- Server-side validation of `is_admin` flag on ALL admin endpoints
|
||||
- Never trust client-side auth checks
|
||||
- JWT token must be valid AND user must have admin role
|
||||
|
||||
2. **Rate Limiting** (Recommended):
|
||||
- Add rate limiting to admin CRUD endpoints (prevent abuse)
|
||||
- Especially important for delete operations
|
||||
|
||||
3. **Audit Logging** (Future Milestone):
|
||||
- Log admin actions (created, updated, deleted items)
|
||||
- Track timestamp and user performing action
|
||||
|
||||
4. **Input Validation**:
|
||||
- Title: max 300 characters
|
||||
- URL: must be valid URL format if provided
|
||||
- Content: validate lexical editor output on save
|
||||
- Points: must be integer >= 0
|
||||
|
||||
### Testing Requirements (M3/M4 covers general testing)
|
||||
|
||||
- Unit tests for admin API endpoints (create, update, delete, list with pagination)
|
||||
- Integration tests for admin-only routes (verify unauthorized users get 403)
|
||||
- E2E tests for full admin workflow (list → edit → save → delete)
|
||||
|
||||
### Docker Configuration
|
||||
|
||||
No new Docker changes required - existing setup works. However:
|
||||
|
||||
1. Add `.env` entry if creating admin user via script:
|
||||
```bash
|
||||
ADMIN_USERNAME=admin_user
|
||||
HN_SECRET_KEY=your-secret-key-change-in-production
|
||||
```
|
||||
|
||||
2. Database migration should run automatically on startup (SQLAlchemy auto-creates tables)
|
||||
|
||||
### Success Metrics
|
||||
|
||||
- Admin can view list of items with pagination working correctly
|
||||
- Search returns relevant results within 200ms
|
||||
- Sort by date/title works in both ascending/descending order
|
||||
- Edit form saves successfully and updates database immediately
|
||||
- Delete confirmation prevents accidental deletions
|
||||
- Lexical editor formats content properly before save
|
||||
- Non-admin users receive 403 Forbidden on admin routes
|
||||
- All API responses include proper HTTP status codes
|
||||
|
||||
## Description
|
||||
|
||||
This milestone implements a complete admin area for newzy allowing administrators to manage content through a web interface. The scope includes creating protected admin routes, implementing CRUD operations with pagination and search, adding Lexical WYSIWYG editor for rich content editing, and ensuring secure admin-only access control—no business logic or additional features beyond the admin interface.
|
||||
|
||||
**Purpose**: Enable site administrators to create, edit, and delete news items through a user-friendly interface without directly editing code or database files.
|
||||
|
||||
**Target Audience**: Non-technical content editors who need to manage the website content, plus developers extending the admin area in future milestones.
|
||||
|
||||
**Expected Outcomes**: A fully functional admin dashboard where logged-in admin users can view paginated item lists with search/sort capabilities, edit articles using a rich text editor, and safely delete items after confirmation. The system protects unauthorized users from accessing admin functionality.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] User model updated with `is_admin` boolean field (default: False)
|
||||
- [ ] Admin-only dependency checks JWT token AND verifies is_admin flag
|
||||
- [ ] All admin endpoints protected by server-side admin check (403 for non-admins)
|
||||
- [ ] GET /api/admin/items returns paginated list with search and sort parameters
|
||||
- [ ] Response includes total count, page number, page size, and items array
|
||||
- [ ] POST /api/admin/items creates new item with validation
|
||||
- [ ] PUT /api/admin/items/{id} updates existing item (only admins allowed)
|
||||
- [ ] DELETE /api/admin/items/{id} deletes item after admin verification
|
||||
- [ ] Admin Layout component renders sidebar navigation
|
||||
- [ ] Admin Dashboard lists items with pagination controls and page size selector
|
||||
- [ ] Search bar filters list by title or URL (case-insensitive, debounced 300ms)
|
||||
- [ ] Sort controls for title (A-Z/Z-A) and created_at (oldest/newest, newest/oldest)
|
||||
- [ ] Edit action navigates to edit page with pre-filled form data
|
||||
- [ ] Delete action triggers confirmation dialog before deletion
|
||||
- [ ] DeleteConfirmation modal has warning icon and requires explicit "Yes, delete" click
|
||||
- [ ] EditItemPage accepts all item fields including title, url, points, content
|
||||
- [ ] Lexical WYSIWYG editor with toolbar (bold, italic, headings, lists, links)
|
||||
- [ ] Form validates required fields before submission
|
||||
- [ ] Loading state displayed during API save operations
|
||||
- [ ] Success/error notifications shown after submit
|
||||
- [ ] Non-admin users receive 403 Forbidden on all admin routes
|
||||
- [ ] Frontend auth context returns is_admin flag for UI conditionals
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Database Schema Update
|
||||
|
||||
```python
|
||||
# backend/app/models.py (add to User model)
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=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) # ← NEW
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
```
|
||||
|
||||
### Admin Dependency (Server-Side Protection)
|
||||
|
||||
```python
|
||||
# backend/app/main.py
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
async def get_current_admin(
|
||||
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""Admin-only dependency - validates token AND admin flag."""
|
||||
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:
|
||||
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")
|
||||
|
||||
if not user.is_admin:
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
|
||||
return user
|
||||
|
||||
@app.get("/api/admin/items", response_model=dict)
|
||||
async def list_admin_items(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
search: str = "",
|
||||
sort_by: Literal["title", "created_at"] = "created_at",
|
||||
sort_order: Literal["asc", "desc"] = "desc",
|
||||
current_user: User = Depends(get_current_admin), # ← Admin check
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List all items with pagination, search, and sorting."""
|
||||
query = db.query(models.Item)
|
||||
|
||||
# Apply search filter
|
||||
if search:
|
||||
search_query = f"%{search}%"
|
||||
query = query.filter(
|
||||
models.Item.title.like(search_query) | models.Item.url.like(search_query)
|
||||
)
|
||||
|
||||
# Apply sorting
|
||||
order_by = [models.Item.created_at]
|
||||
if sort_order == "asc":
|
||||
query = query.order_by(desc(sort_by))
|
||||
else:
|
||||
query = query.order_by(sort_by)
|
||||
|
||||
# Pagination
|
||||
total = query.count()
|
||||
items = query.offset((page - 1) * page_size).limit(page_size).all()
|
||||
|
||||
return {
|
||||
"items": [ItemAdminOut.model_validate(item) for item in items],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size,
|
||||
}
|
||||
|
||||
@app.delete("/api/admin/items/{item_id}", status_code=204)
|
||||
async def delete_admin_item(
|
||||
item_id: int,
|
||||
current_user: User = Depends(get_current_admin), # ← Admin check
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Delete an item (admin only)."""
|
||||
item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
|
||||
# Optional: Soft delete by setting published=False instead of hard delete
|
||||
# db.delete(item) # Hard delete
|
||||
|
||||
return "OK"
|
||||
```
|
||||
|
||||
### Frontend Admin API Client
|
||||
|
||||
```typescript
|
||||
// frontend/src/adminApi.ts
|
||||
|
||||
import { api } from "./api/client";
|
||||
|
||||
interface AdminListResponse {
|
||||
items: Array<{
|
||||
id: number;
|
||||
title: string;
|
||||
url: string;
|
||||
points: number;
|
||||
user: { username: string };
|
||||
created_at: Date | string;
|
||||
}>;
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
total_pages: number;
|
||||
}
|
||||
|
||||
const ADMIN_BASE_URL = "/api/admin";
|
||||
|
||||
export const adminApi = {
|
||||
async listItems(page: number, pageSize: number, search: string, sortBy?: "title" | "created_at"): Promise<AdminListResponse> {
|
||||
const params = new URLSearchParams();
|
||||
params.set("page", page.toString());
|
||||
params.set("page_size", pageSize.toString());
|
||||
if (search) params.set("search", search);
|
||||
|
||||
return api.get(`${ADMIN_BASE_URL}/items?${params}`) as Promise<AdminListResponse>;
|
||||
},
|
||||
|
||||
async getItem(id: number): Promise<any> {
|
||||
return api.get(`/api/admin/items/${id}`) as Promise<any>;
|
||||
},
|
||||
|
||||
async createItem(data: any): Promise<any> {
|
||||
return api.post("/api/admin/items", data) as Promise<any>;
|
||||
},
|
||||
|
||||
async updateItem(id: number, data: any): Promise<any> {
|
||||
return api.put(`/api/admin/items/${id}`, data) as Promise<any>;
|
||||
},
|
||||
|
||||
async deleteItem(id: number): Promise<void> {
|
||||
return api.delete(`/api/admin/items/${id}`) as Promise<void>;
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Lexical Editor Setup
|
||||
|
||||
```typescript
|
||||
// frontend/src/components/LexicalEditor.tsx (or integrated inline)
|
||||
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import {
|
||||
LexicalComposer,
|
||||
RichTextPlugin,
|
||||
HistoryPlugin,
|
||||
} from "@lexical/react/LexicalComposerPlugins";
|
||||
import ContentEditable from "@lexical/react/LexicalContentEditable";
|
||||
|
||||
function LexicalEditor() {
|
||||
const editorRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
return (
|
||||
<div ref={editorRef}>
|
||||
<LexicalComposer initialState={{ theme: {} }}>
|
||||
<RichTextPlugin>
|
||||
{/* Additional plugins here */}
|
||||
</RichTextPlugin>
|
||||
<HistoryPlugin />
|
||||
</LexicalComposer>
|
||||
<ContentEditable
|
||||
className="lexical-editor"
|
||||
contentEditable
|
||||
onChange={(e) => handleSave(e.currentTarget.textContent)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default LexicalEditor;
|
||||
```
|
||||
|
||||
### Delete Confirmation Component
|
||||
|
||||
```typescript
|
||||
// frontend/src/components/DeleteConfirmation.tsx
|
||||
|
||||
import { useAuth } from "../auth";
|
||||
import { adminApi } from "../adminApi";
|
||||
import { alert as SweetAlert, AlertParams } from "sweetalert2";
|
||||
|
||||
interface DeleteConfirmationProps {
|
||||
itemId: number;
|
||||
itemName: string;
|
||||
onConfirm: () => Promise<void>;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function DeleteConfirmation({ itemId, itemName, onConfirm, onCancel }: DeleteConfirmationProps) {
|
||||
const { username } = useAuth();
|
||||
|
||||
return (
|
||||
<div className="delete-modal-overlay" onClick={onCancel}>
|
||||
<div className="delete-modal-content">
|
||||
<i className="icon-warning"></i>
|
||||
<h3>Are you sure you want to delete "{itemName}"?</h3>
|
||||
<p>This action cannot be undone.</p>
|
||||
<div className="modal-actions">
|
||||
<button onClick={onCancel}>Cancel</button>
|
||||
<button
|
||||
className="btn-danger"
|
||||
onClick={async () => {
|
||||
await onConfirm();
|
||||
onCancel();
|
||||
}}
|
||||
>
|
||||
Yes, Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## QA Notes
|
||||
|
||||
### Testing Checklist - Backend
|
||||
- [ ] Admin dependency returns 403 for non-admin users
|
||||
- [ ] Non-admin JWT tokens rejected with proper error message
|
||||
- [ ] Admin endpoints work correctly for authenticated admins
|
||||
- [ ] Pagination works (page 1, page 2, etc.)
|
||||
- [ ] Search finds items by title OR url
|
||||
- [ ] Sort order changes work (asc/desc switching)
|
||||
- [ ] Delete requires explicit confirmation
|
||||
- [ ] Hard delete or soft delete both functional (whichever chosen)
|
||||
|
||||
### Testing Checklist - Frontend
|
||||
- [ ] AdminLayout only renders for admin users
|
||||
- [ ] Admin routes protected with AuthProvider check
|
||||
- [ ] List view displays all items correctly
|
||||
- [ ] Pagination controls update page state
|
||||
- [ ] Search debounced (300ms delay before API call)
|
||||
- [ ] Sort buttons toggle sort_by and sort_order
|
||||
- [ ] Edit button loads correct item data in form
|
||||
- [ ] Delete button shows confirmation modal
|
||||
- [ ] Cancel delete dismisses modal
|
||||
- [ ] Confirm delete performs API request
|
||||
- [ ] Form validation blocks empty submissions
|
||||
- [ ] Lexical editor saves properly formatted content
|
||||
- [ ] Loading states show during async operations
|
||||
|
||||
### Security Testing Checklist
|
||||
- [ ] Direct URL access to /api/admin/items → 403 for non-admins
|
||||
- [ ] Token tampering doesn't bypass admin check (JWT signature validation)
|
||||
- [ ] Rate limiting placeholder present (even if not active yet)
|
||||
- [ ] Input sanitization prevents SQL injection (SQLAlchemy handles this)
|
||||
- [ ] XSS prevention in Lexical editor output
|
||||
|
||||
### Performance Considerations
|
||||
- Search with 10,000 items: <2 seconds response time
|
||||
- Pagination queries use LIMIT/OFFSET efficiently
|
||||
- Frontend debounces search to reduce API calls
|
||||
- Admin pages lazy-loaded (optional optimization)
|
||||
|
||||
### Known Issues / Limitations
|
||||
- No role-based permissions beyond admin flag yet
|
||||
- Lexical editor could benefit with image/file upload support
|
||||
- Audit logging not implemented (M7 scope)
|
||||
- No version history for deleted items
|
||||
- Mobile UX could use improvement
|
||||
|
||||
### Success Metrics
|
||||
- Admin can list all 100+ items on first page load in <2s
|
||||
- Search returns correct results consistently
|
||||
- Sort order persists while navigating pages
|
||||
- Lexical editor renders and saves rich text content
|
||||
- Delete confirmation prevents at least 95% of accidental deletions
|
||||
- Non-admin users never see admin UI or API endpoints
|
||||
Reference in new issue
Block a user