final commit
This commit is contained in:
1 parent
0ffbba3bed
commit
7b242b8685
39 files changed
+5524
-65
No files matched your search
@@ -0,0 +1,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