From 4c82e4f54c2b26ff769f85b4d8211b2ea7ce3c3d Mon Sep 17 00:00:00 2001 From: Daniel Samson Date: Thu, 29 Oct 2026 16:23:52 +0000 Subject: [PATCH] feat: add M6 setup admin area milestone Backend (FastAPI): - is_admin field added to User model with default False - Admin-only dependency validates JWT AND is_admin flag - Protected CRUD endpoints for items management - Pagination, search by title/url, sort by title/date Frontend (React + TypeScript): - AdminLayout with sidebar navigation protected by auth check - AdminDashboard with pagination controls and page size selector - EditItemPage with Lexical WYSIWYG editor toolbar - DeleteConfirmation modal requires explicit confirmation - Warning icon and consequences message before delete Security: - Server-side 403 Forbidden for non-admin users - JWT token validation required on all admin routes --- README.md | 21 +- milestone/m6-setup-admin-area-prompt.md | 590 +++++++++++++++++++++++ milestone/m6-setup-admin-area-scoring.md | 189 ++++++++ 3 files changed, 783 insertions(+), 17 deletions(-) create mode 100644 milestone/m6-setup-admin-area-prompt.md create mode 100644 milestone/m6-setup-admin-area-scoring.md diff --git a/README.md b/README.md index 4d082b8..71f6f88 100644 --- a/README.md +++ b/README.md @@ -38,27 +38,14 @@ This benchmark consists of multiple milestones, each representing a separate tas ### M3: Frontend Application This benchmark consists of multiple milestones, each representing a separate task: -### M1: Git Repository Setup -- [M1 - Setup Git Project](milestone/m1-setup-git-project-prompt.md) -- [M1 - Setup Git Project Scoring](milestone/m1-setup-git-project-scoring.md) - -### M2: Backend Infrastructure -- [M2 - Setup Backend](milestone/m2-setup-backend-prompt.md) -- [M2 - Setup Backend Scoring](milestone/m2-setup-backend-scoring.md) - -### M3: Frontend Application -- [M3 - Setup Frontend](milestone/m3-setup-frontend-prompt.md) -- [M3 - Setup Frontend Scoring](milestone/m3-setup-frontend-scoring.md) - -### M4: Developer Environment -- [M4 - Setup Developer Environment](milestone/m4-setup-developer-environment-prompt.md) -- [M4 - Setup Developer Environment Scoring](milestone/m4-setup-developer-environment-scoring.md) - ### M5: Authentication System - [M5 - Setup Authentication](milestone/m5-setup-authentication-prompt.md) - [M5 - Setup Authentication Scoring](milestone/m5-setup-authentication-scoring.md) -After each milestone the agents context MUST be cleared. This tests the models reasoning capabilities and how it performs with incomplete information. +### M6: Admin Area +- [M6 - Setup Admin Area](milestone/m6-setup-admin-area-prompt.md) +- [M6 - Setup Admin Area Scoring](milestone/m6-setup-admin-area-scoring.md) + ## Tech Stack Variations diff --git a/milestone/m6-setup-admin-area-prompt.md b/milestone/m6-setup-admin-area-prompt.md new file mode 100644 index 0000000..882e16b --- /dev/null +++ b/milestone/m6-setup-admin-area-prompt.md @@ -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 { + 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; + }, + + async getItem(id: number): Promise { + return api.get(`/api/admin/items/${id}`) as Promise; + }, + + async createItem(data: any): Promise { + return api.post("/api/admin/items", data) as Promise; + }, + + async updateItem(id: number, data: any): Promise { + return api.put(`/api/admin/items/${id}`, data) as Promise; + }, + + async deleteItem(id: number): Promise { + return api.delete(`/api/admin/items/${id}`) as Promise; + }, +}; +``` + +### 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(null); + + return ( +
+ + + {/* Additional plugins here */} + + + + handleSave(e.currentTarget.textContent)} + /> +
+ ); +} + +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; + onCancel: () => void; +} + +export function DeleteConfirmation({ itemId, itemName, onConfirm, onCancel }: DeleteConfirmationProps) { + const { username } = useAuth(); + + return ( +
+
+ +

Are you sure you want to delete "{itemName}"?

+

This action cannot be undone.

+
+ + +
+
+
+ ); +} +``` + +## 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 diff --git a/milestone/m6-setup-admin-area-scoring.md b/milestone/m6-setup-admin-area-scoring.md new file mode 100644 index 0000000..bb12832 --- /dev/null +++ b/milestone/m6-setup-admin-area-scoring.md @@ -0,0 +1,189 @@ +# M6: Setup Admin Area - Scoring Rubric + +## Acceptance Criteria Scoring Table + +| Score | Criteria | +|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| 0 | Agent failed to implement acceptance criteria:
- No is_admin field added to User model
- Admin endpoints not created or unprotected
- No admin routes in frontend
- Delete without confirmation
- Lexical editor not integrated | +| 1 | Agent partially implemented acceptance criteria that builds successfully:
- User model has is_admin but no validation logic
- One admin endpoint working (e.g., list only)
- Frontend has placeholder route but no functionalityis_admin field in User model with default value
- Backend admin dependency checks JWT AND is_admin flag (403 for non-admins)- Missing migration or no field added +- **1 pt**: is_admin Boolean field exists but wrong default
- Not stored in database +- **2 pts**: is_admin Boolean field with default=False- All endpoints publicly accessible +- **1 pt**: JWT token checked but not is_admin flag
- Returns 200 for non-admins +- **2 pts**: Admin dependency validates token AND checks is_admin- Returns empty/error response +- **1 pt**: Endpoint exists but returns all items without pagination
- Infinite list +- **2 pts**: Pagination parameters work (page, page_size)- Cannot create items via admin API +- **1 pt**: Endpoint exists but doesn't require admin flag
- Non-admins can create +- **2 pts**: Admin-only creation with proper validation- Cannot update existing items +- **1 pt**: Endpoint exists but open to all users
- Non-admins can modify items +- **2 pts**: Admin-only updates with proper field mapping- Cannot delete items via API +- **1 pt**: Endpoint exists but returns success immediately
- No confirmation mechanism +- **2 pts**: Admin-only deletion with proper verification- Admin pages inaccessible +- **1 pt**: Protected route exists but AuthContext check missing
- Non-admins can access UI +- **2 pts**: AdminLayout renders only for is_admin=true users- Items page missing entirely +- **1 pt**: Basic table/list but no pagination controls- Cannot create/edit items +- **1 pt**: Create/Edit form exists but missing fields- Direct delete without warning +- **1 pt**: Modal appears but no warning icon or message- Text area only, no formatting +- **1 pt**: Basic textarea but not integrated with React properly- Hardcoded fetch URLs scattered throughout +- **1 pt**: Admin methods exist but no Bearer token attachment
- Authentication fails silently +- **2 pts**: create, read, update, delete methods implemented2:** +- [ ] is_admin field exists in database +- [ ] Backend validates BOTH JWT token AND is_admin flag +- [ ] Non-admin users receive 403 Forbidden status +- [ ] Error message indicates admin access required + +**MUST HAVE for Score >4:** +- [ ] All CRUD endpoints protected server-side +- [ ] Search filters by title OR url (not just client-side) +- [ ] Sort parameters actually change database query order + +**MUST HAVE for Score >6:** +- [ ] Delete requires explicit confirmation dialog +- [ ] Warning message explains consequences +- [ ] Cancel button available and functional + +## Bonus Points Consideration + +**+1 point** for: +- Soft delete implementation (sets published=False instead of removing record) +- Audit logging placeholder (logs admin action to database table or file) + +**+2 points** for: +- Loading skeleton while fetching items list +- Empty state UI when no search results found +- Pagination metadata in response (total_pages, current_page) + +**+3 points** for: +- Responsive design on mobile devices +- Keyboard shortcuts (Ctrl+S to save, ESC to cancel) +- Keyboard navigation (Tab between form fields, Enter to save) + +## Test Scenarios to Verify Score 5+ + +1. **Non-Admin Access**: + - User with is_admin=False calls /api/admin/items → 403 Forbidden + - Frontend detects 403 and shows access denied message + - JWT token valid but insufficient permissions + +2. **Admin Authentication**: + - Admin user with valid token calls /api/admin/items → 200 OK + - Response includes pagination metadata (page, page_size, total_pages) + - Items array contains all expected properties + +3. **Pagination**: + - Request page=2, page_size=10 returns second page of items + - Total count accurate across pages + - Page size selector changes items per page + +4. **Search**: + - Search "test" finds items with "test" in title OR url + - Case-insensitive search (works for "Test", "TEST", "test") + - Empty search returns all items + +5. **Sorting**: + - Sort by title asc shows A-Z order + - Sort by created_at desc shows newest first + - Toggle switches between orders successfully + +6. **Delete Confirmation**: + - Click delete → confirmation modal appears + - Warning icon visible (red or yellow triangle) + - Message includes "cannot be undone" warning + - Cancel button dismisses without deleting + - Outside click dismisses modal + - Only explicit "Yes, Delete" triggers API request + +7. **Lexical Editor**: + - Type text with bold formatting applied + - Save button stores content as rich HTML + - Retrieved content displays formatting correctly + - Undo/redo functionality works (if implemented) + +8. **Form Validation**: + - Empty title field blocks save operation + - Invalid URL format triggers error message + - Loading state shows while submitting + - Success notification appears on completion