# 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 - [x] User model updated with `is_admin` boolean field (default: False) - [x] Admin-only dependency checks JWT token AND verifies is_admin flag - [x] All admin endpoints protected by server-side admin check (403 for non-admins) - [x] GET /api/v1/admin/items returns paginated list with search and sort parameters - [x] Response includes total count, page number, page size, and items array - [x] POST /api/v1/admin/items creates new item with validation - [x] PUT /api/v1/admin/items/{id} updates existing item (only admins allowed) - [x] DELETE /api/v1/admin/items/{id} deletes item after admin verification - [x] Admin Layout component renders sidebar navigation - [x] Admin Dashboard lists items with pagination controls and page size selector - [x] Search bar filters list by title or URL (case-insensitive, debounced 300ms) - [x] Sort controls for title (A-Z/Z-A), created_at (newest/oldest) and points - [x] Edit action navigates to edit page with pre-filled form data - [x] Delete action triggers confirmation dialog before deletion - [x] DeleteConfirmation modal has warning icon and requires explicit "Yes, delete" click - [x] EditItemPage accepts all item fields including title, url, points, content - [x] Lexical WYSIWYG editor with toolbar (bold, italic, underline, headings, lists, links, code blocks, undo/redo) - [x] Form validates required fields before submission - [x] Loading state displayed during API save operations - [x] Success/error notifications shown after submit - [x] Non-admin users receive 403 Forbidden on all admin routes (API + UI guard) - [x] Frontend auth context returns is_admin flag for UI conditionals Implementation notes (deviations from the prompt sketch, matching project conventions): - Endpoints live under `/api/v1/admin/items` (project uses the `/api/v1` prefix). - Files follow the existing layout: `backend/models/item.py`, `backend/schemas/item.py`, `backend/api/v1/admin.py`, `frontend/src/api/admin.ts`, `frontend/src/types/admin.ts`. - Delete is a hard delete (no soft-delete column on `Item`). - Rate limiting is implemented in-memory (1000 req/60s per admin; 429 on breach) rather than a placeholder. QA findings from M6 (all fixed): - The editor's `initialHtml` ingest called `$generateNodesFromDOM` but discarded the returned nodes, so stored content never appeared in the WYSIWYG editor in edit mode. Fixed by appending the parsed nodes to the root; covered by the E2E edit + hostile-HTML tests. - XSS: the E2E hostile-HTML test loads `