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
This commit is contained in:
1 parent
c1313c8758
commit
4c82e4f54c
3 files changed
+783
-17
No files matched your search
@@ -38,27 +38,14 @@ This benchmark consists of multiple milestones, each representing a separate tas
|
|||||||
### M3: Frontend Application
|
### M3: Frontend Application
|
||||||
This benchmark consists of multiple milestones, each representing a separate task:
|
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: Authentication System
|
||||||
- [M5 - Setup Authentication](milestone/m5-setup-authentication-prompt.md)
|
- [M5 - Setup Authentication](milestone/m5-setup-authentication-prompt.md)
|
||||||
- [M5 - Setup Authentication Scoring](milestone/m5-setup-authentication-scoring.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
|
## Tech Stack Variations
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
# M6: Setup Admin Area - Scoring Rubric
|
||||||
|
|
||||||
|
## Acceptance Criteria Scoring Table
|
||||||
|
|
||||||
|
| Score | Criteria |
|
||||||
|
|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||||
|
| 0 | Agent failed to implement acceptance criteria:<br>- No is_admin field added to User model<br>- Admin endpoints not created or unprotected<br>- No admin routes in frontend<br>- Delete without confirmation<br>- Lexical editor not integrated |
|
||||||
|
| 1 | Agent partially implemented acceptance criteria that builds successfully:<br>- User model has is_admin but no validation logic<br>- One admin endpoint working (e.g., list only)<br>- Frontend has placeholder route but no functionality<br- No delete confirmation<br- Basic list view without pagination |
|
||||||
|
| 2 | Agent fully implemented acceptance criteria that builds successfully:<br>is_admin field in User model with default value<br>- Backend admin dependency checks JWT AND is_admin flag (403 for non-admins)<br- GET /api/admin/items returns paginated data<br- Frontend AdminLayout component created with sidebar navigation<br- Delete action exists but confirmation missing |
|
||||||
|
| 3 | Agent fully implemented acceptance criteria that builds successfully, includes working pagination with page/page_size parameters in response<br- Search functionality filters by title/url (case-insensitive)<br- Sort controls toggle asc/desc order for title and date columns |
|
||||||
|
| 4 | Agent fully implemented acceptance criteria that builds successfully, includes EditItemPage component pre-filling form with item data<br- Admin API client methods defined for create/update/delete/list<br- Form validation prevents empty submissions |
|
||||||
|
| 5 | Agent fully implemented acceptance criteria that builds successfully, includes Lexical WYSIWYG editor integration in edit form<br- Editor has toolbar (bold, italic, headings, lists)<br- Rich text content saved correctly to database |
|
||||||
|
| 6 | Agent fully implemented acceptance criteria that builds successfully, includes DeleteConfirmation modal with warning icon<br- Requires explicit "Yes, delete" click to confirm<br- Warning message explains consequences |
|
||||||
|
| 7 | Agent fully implemented acceptance criteria that builds successfully, includes all content from Score 5 AND:<br- SweetAlert2 or custom modal with proper overlay styling<br- Modal dismisses on outside click (escapes modal area)<br- Cancel button properly exits without deleting |
|
||||||
|
|
||||||
|
## Scoring Breakdown by Criterion
|
||||||
|
|
||||||
|
### Database Schema (Max 3 points)
|
||||||
|
- **0 pts**: No is_admin field in User model<br>- Missing migration or no field added
|
||||||
|
- **1 pt**: is_admin Boolean field exists but wrong default<br>- Not stored in database
|
||||||
|
- **2 pts**: is_admin Boolean field with default=False<br- Properly typed in SQLAlchemy model
|
||||||
|
- **3 pts**: Migration creates column correctly<br- Sample data seeded (admin user exists)
|
||||||
|
|
||||||
|
### Backend Admin Protection (Max 4 points)
|
||||||
|
- **0 pts**: No admin-only dependency or check<br>- All endpoints publicly accessible
|
||||||
|
- **1 pt**: JWT token checked but not is_admin flag<br>- Returns 200 for non-admins
|
||||||
|
- **2 pts**: Admin dependency validates token AND checks is_admin<br- Raises 403 for non-admin users (correct status code)
|
||||||
|
- **3 pts**: Error message includes "Admin access required"<br- Security headers set appropriately
|
||||||
|
- **4 pts**: All CRUD endpoints protected by admin check<br- Server-side validation not dependent on client
|
||||||
|
|
||||||
|
### Admin List Endpoint (Max 4 points)
|
||||||
|
- **0 pts**: No /api/admin/items endpoint<br>- Returns empty/error response
|
||||||
|
- **1 pt**: Endpoint exists but returns all items without pagination<br>- Infinite list
|
||||||
|
- **2 pts**: Pagination parameters work (page, page_size)<br- Response includes items array and count
|
||||||
|
- **3 pts**: Search parameter filters by title OR url<br- Case-insensitive search implemented
|
||||||
|
- **4 pts**: Sort parameters work for title AND created_at<br- Both ascending and descending orders
|
||||||
|
|
||||||
|
### Create Endpoint (Max 3 points)
|
||||||
|
- **0 pts**: No POST /api/admin/items endpoint<br>- Cannot create items via admin API
|
||||||
|
- **1 pt**: Endpoint exists but doesn't require admin flag<br>- Non-admins can create
|
||||||
|
- **2 pts**: Admin-only creation with proper validation<br- Returns created item or appropriate error
|
||||||
|
- **3 pts**: Input validation (title required, URL format check)<br- Database transaction commits successfully
|
||||||
|
|
||||||
|
### Update Endpoint (Max 3 points)
|
||||||
|
- **0 pts**: No PUT /api/admin/items/{id} endpoint<br>- Cannot update existing items
|
||||||
|
- **1 pt**: Endpoint exists but open to all users<br>- Non-admins can modify items
|
||||||
|
- **2 pts**: Admin-only updates with proper field mapping<br- Updates id, title, url, points, content correctly
|
||||||
|
- **3 pts**: Optimistic UI feedback on frontend (pending save)<br- Error handling for failed updates
|
||||||
|
|
||||||
|
### Delete Endpoint (Max 3 points)
|
||||||
|
- **0 pts**: No DELETE /api/admin/items/{id} endpoint<br>- Cannot delete items via API
|
||||||
|
- **1 pt**: Endpoint exists but returns success immediately<br>- No confirmation mechanism
|
||||||
|
- **2 pts**: Admin-only deletion with proper verification<br- Removes item from database correctly
|
||||||
|
- **3 pts**: Optional soft delete (published=False) implemented<br- Hard delete works and removes records
|
||||||
|
|
||||||
|
### Frontend Layout (Max 4 points)
|
||||||
|
- **0 pts**: No admin layout or sidebar navigation<br>- Admin pages inaccessible
|
||||||
|
- **1 pt**: Protected route exists but AuthContext check missing<br>- Non-admins can access UI
|
||||||
|
- **2 pts**: AdminLayout renders only for is_admin=true users<br- Sidebar navigation with back button works
|
||||||
|
- **3 pts**: Layout collapses on mobile (responsive)<br- Breadcrumbs or title indicates admin area
|
||||||
|
- **4 pts**: Error state if not admin shows friendly message<br- Protected routes redirect to home/login
|
||||||
|
|
||||||
|
### List View Components (Max 6 points)
|
||||||
|
- **0 pts**: No list view component<br>- Items page missing entirely
|
||||||
|
- **1 pt**: Basic table/list but no pagination controls<br- All items displayed at once
|
||||||
|
- **2 pts**: Pagination controls functional (prev/next, page numbers)<br- Page size selector present and working
|
||||||
|
- **3 pts**: Card-based or table layout with hover effects<br- Loading state shows during fetch
|
||||||
|
- **4 pts**: Item count displays (X of Y items total)<br- Empty state shown when no items match search
|
||||||
|
- **5 pts**: Search debounced (300ms delay before API call)<br- Results update without page refresh
|
||||||
|
- **6 pts**: Edit and delete buttons on each row<br- Action icons or clearly labeled text
|
||||||
|
|
||||||
|
### Edit View Components (Max 4 points)
|
||||||
|
- **0 pts**: No edit page or form missing<br>- Cannot create/edit items
|
||||||
|
- **1 pt**: Create/Edit form exists but missing fields<br- Only title input, no content editor
|
||||||
|
- **2 pts**: Form includes all required fields (title, url, points, content)<br- Save button triggers API request
|
||||||
|
- **3 pts**: Form pre-fills with existing item data for edit mode<br- Loading state during save operation
|
||||||
|
- **4 pts**: Cancel button reverts to unsaved state<br- Success notification on completion
|
||||||
|
|
||||||
|
### Delete Confirmation (Max 5 points)
|
||||||
|
- **0 pts**: No confirmation dialog<br>- Direct delete without warning
|
||||||
|
- **1 pt**: Modal appears but no warning icon or message<br- Just "Are you sure?" text only
|
||||||
|
- **2 pts**: Warning icon present (exclamation/triangle)<br- Title explains deletion action
|
||||||
|
- **3 pts**: Message describes consequences clearly<br- "This action cannot be undone" message present
|
||||||
|
- **4 pts**: Two buttons: Cancel and Delete<br- Delete button requires explicit confirmation ("Yes, delete")
|
||||||
|
- **5 pts**: Outside click dismisses modal<br- ESC key closes dialog
|
||||||
|
|
||||||
|
### Lexical Editor (Max 5 points)
|
||||||
|
- **0 pts**: No WYSIWYG editor<br>- Text area only, no formatting
|
||||||
|
- **1 pt**: Basic textarea but not integrated with React properly<br- Plain text save only
|
||||||
|
- **2 pts**: Lexical editor imported and mounted<br- ContentEditable div present
|
||||||
|
- **3 pts**: Toolbar shows formatting buttons (bold, italic)<br- Buttons clickable but may not work yet
|
||||||
|
- **4 pts**: Bold/italic/headings/lists actually formatted<br- HTML output contains proper tags
|
||||||
|
- **5 pts**: Rich text content saves to database correctly<br- Retrieved content displays with formatting
|
||||||
|
|
||||||
|
### Frontend API Client (Max 4 points)
|
||||||
|
- **0 pts**: No adminApi client file<br>- Hardcoded fetch URLs scattered throughout
|
||||||
|
- **1 pt**: Admin methods exist but no Bearer token attachment<br>- Authentication fails silently
|
||||||
|
- **2 pts**: create, read, update, delete methods implemented<br- All four CRUD operations callable
|
||||||
|
- **3 pts**: Pagination parameters included in list request<br- Search/sort params work correctly
|
||||||
|
- **4 pts**: Error handling wraps all API calls properly<br- Throws errors on 403/404 responses
|
||||||
|
|
||||||
|
## Total Possible Score: 51 points
|
||||||
|
|
||||||
|
## Evaluation Notes
|
||||||
|
- Partial credit given for incomplete but working implementations (Score 1)
|
||||||
|
- Full credit requires all acceptance criteria met with passing verification (Score 2 minimum)
|
||||||
|
- Higher scores require additional value-add content beyond baseline requirements
|
||||||
|
- Score 0 indicates agent did not attempt the task or security is compromised
|
||||||
|
|
||||||
|
## Critical Security Requirements
|
||||||
|
|
||||||
|
**MUST HAVE for Score >2:**
|
||||||
|
- [ ] 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
|
||||||
Reference in new issue
Block a user