DeutschLernen/docs/features/admin-module.md
Lasse Rune Hansen c1e3c37843 feat(backend/auth): Enforce authentication on LessonsEndpoints minimal API GET endpoints
- Added .RequireAuthorization() to all GET endpoints in LessonsEndpoints.cs
  - /api/lessons
  - /api/lessons/{id}
  - /api/lessons/beginner
  - /api/lessons/advanced
  - /api/lessons/level/{level}
- Updated admin-module.md feature documentation
  - Marked all acceptance criteria as complete
  - Updated functional requirements status to Complete
  - Updated Definition of Done criteria
  - Added note about Phase 4 completion

This ensures all learning content endpoints now require JWT authentication,
completing the Phase 4 Admin Module authentication enforcement requirement.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-06-14 17:03:30 +02:00

443 lines
No EOL
18 KiB
Markdown

# Feature: Admin Module & User Management
> **Status**: ✅ Completed
> **Priority**: High
> **Complexity**: High
> **Estimate**: 12-16 hours
> **Assignee**: -
> **Created**: June 14, 2025
> **Completed**: June 14, 2026
> **PR**: -
> **Related Features**: User Authentication, Story Integration, Lesson Management, Progress Tracking
---
## 📌 Overview
### Purpose
Implement a comprehensive admin module that allows the application owner (Lasse) to manage users, generate story content, and access progress reports. This is **mission-critical** for the application as it enforces the requirement that **all visitors must sign up before accessing any learning content**.
### User Stories
- **As an admin**, I want to generate stories for levels so that users have content to learn from
- **As an admin**, I want to view user lists and their progress so that I can monitor application usage
- **As an admin**, I want to view progress reports so that I can understand how users are engaging with the platform
- **As a visitor**, I must sign up and login before I can access any learning content (stories, lessons, quizzes)
### Acceptance Criteria
- [x] All learning content endpoints require authentication (no public access)
- [x] User registration is mandatory before accessing any content
- [x] Admin role exists and is assigned to specific users only
- [x] Admin can access story generation UI/API
- [x] Admin can view list of all users
- [x] Admin can view individual user progress (lessons completed, stories unlocked)
- [x] Admin can generate reports on user activity
- [x] Admin endpoints are protected and only accessible to admin users
---
## 📋 Requirements
### Functional Requirements
| ID | Requirement | Priority | Status |
|----|-------------|----------|--------|
| FR-001 | Mandatory user registration before accessing content | High | ✅ Complete |
| FR-002 | JWT authentication required for ALL learning endpoints | High | ✅ Complete |
| FR-003 | Admin role system with single admin user (Lasse) | High | ✅ Complete |
| FR-004 | Admin UI for story generation | High | ✅ Complete |
| FR-005 | Admin API endpoint for story generation | High | ✅ Complete |
| FR-006 | Admin UI for viewing all users | High | ✅ Complete |
| FR-007 | Admin API endpoint for listing users | High | ✅ Complete |
| FR-008 | Admin UI for viewing user progress | High | ✅ Complete |
| FR-009 | Admin API endpoint for user progress | High | ✅ Complete |
| FR-010 | Admin UI for generating user progress reports | Medium | ✅ Complete |
| FR-011 | Admin API endpoint for progress reports | Medium | ✅ Complete |
| FR-012 | Admin dashboard with overview statistics | Medium | ✅ Complete |
### Non-Functional Requirements
- Security: Admin endpoints must be protected with role-based authorization
- Security: Admin role can only be assigned through direct database manipulation (not via API)
- Performance: User list loading < 500ms for up to 10,000 users
- Performance: Progress reports generation < 2 seconds
- Data Retention: User progress data retained indefinitely
- Audit: Admin actions should be logged (future enhancement)
---
## 🏗️ Technical Design
### Components Involved
#### Backend (GermanApp)
- **Controllers**: AdminController (new), UserController (new), ReportController (new)
- **Services**: AdminService (new), UserReportService (new)
- **Entities**: User (existing), StorySegment (existing), StoryProgress (existing), UserProgress (existing)
- **Repositories**: IUserRepository (existing), IStoryProgressRepository (existing), IUserProgressRepository (existing)
- **DTOs**: UserDto, UserListDto, UserProgressDto, ProgressReportDto, StoryGenerationRequestDto (existing)
- **Middleware**: Role-based authorization (existing JWT infrastructure)
#### Frontend (german-app-frontend)
- **Pages**: AdminDashboard (new), AdminUsers (new), AdminReports (new), AdminStoryGenerator (new)
- **Components**: UserList (new), UserCard (new), ProgressChart (new), StoryGenerationForm (new)
- **Services**: adminApi (new), authService (existing)
- **Types**: User, UserProgress, ProgressReport (new)
- **Routing**: Protected admin routes with role check
#### Infrastructure
- **Database**: No new tables needed (uses existing Users, StoryProgress, UserProgress, StorySegments)
- **Configuration**: Admin role configuration in JWT claims
### Data Flow
#### User Authentication Flow (Mandatory)
```
1. Visitor arrives at / (home page)
2. Frontend checks localStorage for JWT token
3. If no token → redirect to /login
4. User enters credentials → POST /api/auth/login
5. Backend validates → returns JWT token
6. Frontend stores token → redirects to /learn or /story/1
7. All subsequent requests include Authorization: Bearer <token>
8. Backend middleware validates token → allows access to protected endpoints
```
#### Story Generation Flow (Admin Only)
```
1. Admin navigates to /admin/stories
2. Frontend verifies user has admin role (from JWT claims)
3. Admin selects level (1-5) and enters theme
4. Frontend POST /api/admin/stories/generate with {levelId, theme, segmentCount}
5. Backend verifies admin role
6. Backend extracts vocabulary from level's lessons
7. Backend calls Mistral AI with CEFR-specific prompt
8. Backend splits story into segments
9. Backend saves segments to database
10. Backend returns success with generated segments
11. Frontend shows success message
```
#### User Management Flow (Admin Only)
```
1. Admin navigates to /admin/users
2. Frontend verifies admin role
3. Frontend GET /api/admin/users
4. Backend verifies admin role
5. Backend fetches all users from database
6. Backend returns user list with basic info
7. Frontend displays user table with filters
8. Admin clicks on user → GET /api/admin/users/{id}/progress
9. Backend returns detailed progress for that user
10. Frontend displays user progress dashboard
```
#### Report Generation Flow (Admin Only)
```
1. Admin navigates to /admin/reports
2. Frontend verifies admin role
3. Admin selects report type (user activity, progress, etc.)
4. Frontend GET /api/admin/reports/{type}?startDate=...&endDate=...
5. Backend verifies admin role
6. Backend aggregates data based on report type
7. Backend returns report data
8. Frontend renders report with charts/tables
```
### API Endpoints
#### Admin Endpoints (Require Admin Role)
| Endpoint | Method | Description | Auth Required | Admin Only |
|----------|--------|-------------|----------------|------------|
| `/api/admin/stories/generate` | POST | Generate story for a level | Yes | Yes |
| `/api/admin/stories/levels/{levelId}/regenerate` | POST | Regenerate story for level | Yes | Yes |
| `/api/admin/users` | GET | List all users | Yes | Yes |
| `/api/admin/users/{id}` | GET | Get specific user details | Yes | Yes |
| `/api/admin/users/{id}/progress` | GET | Get user's progress | Yes | Yes |
| `/api/admin/reports/activity` | GET | User activity report | Yes | Yes |
| `/api/admin/reports/progress` | GET | Learning progress report | Yes | Yes |
| `/api/admin/reports/completion` | GET | Lesson/story completion report | Yes | Yes |
| `/api/admin/dashboard` | GET | Admin dashboard statistics | Yes | Yes |
#### Modified Endpoints (Now Require Authentication)
| Endpoint | Method | Description | Auth Required | Change |
|----------|--------|-------------|----------------|--------|
| `/api/story/*` | GET/POST | All story endpoints | Yes | Added [Authorize] |
| `/api/lessons/*` | GET | All lesson endpoints | Yes | Added [Authorize] |
| `/api/quizzes/*` | GET | All quiz endpoints | Yes | Added [Authorize] |
| `/api/levels/*` | GET | All level endpoints | Yes | Added [Authorize] |
### Database Schema
No new tables required. Uses existing:
- `Users` - User accounts
- `StorySegments` - Story content
- `StoryProgress` - Which story segments user has unlocked/completed
- `UserProgress` - Lesson completion tracking
- `Levels` - Learning levels (A1, A2, etc.)
- `Lessons` - Learning lessons
---
## 🚀 Implementation Plan
### Phase 1: Authentication Enforcement (1-2 hours)
**Priority: Critical** - Must be done before any other work
- [x] Add `[Authorize]` to all learning content controllers
- [x] StoryController (GET endpoints)
- [x] LessonsController (GET endpoints)
- [x] QuizzesController (GET endpoints)
- [x] LevelsController (GET endpoints)
- [x] Add `.RequireAuthorization()` to all learning content minimal API endpoints
- [x] LessonsEndpoints.cs GET endpoints (/api/lessons, /api/lessons/{id}, /api/lessons/beginner, /api/lessons/advanced, /api/lessons/level/{level})
- [x] Remove `[Authorize]` from AuthController (register/login should be public)
- [x] Update CORS configuration to support credentials
- [x] Test authentication flow with Postman/curl
**Deliverables:**
- All learning endpoints require JWT token
- Unauthenticated requests return 401
---
### Phase 2: Admin Role System (2-3 hours)
**Priority: High** - Required for admin functionality
- [x] Define "Admin" role constant in backend
- [x] Modify JWT token generation to include roles
- [x] Update User entity to include role field
- [x] Add role to RegisterDto (or make first user admin)
- [x] Create migration for role field (if needed)
- [x] Add `[Authorize(Roles = "Admin")]` to admin endpoints
- [x] Update frontend auth to decode and store roles
**Deliverables:**
- Role-based authorization working
- Admin users can access admin endpoints
- Regular users cannot access admin endpoints
---
### Phase 3: Admin Backend Services (4-5 hours)
**Priority: High** - Backend infrastructure for admin features
- [x] Create AdminController
- [x] POST /api/admin/stories/generate
- [x] GET /api/admin/users
- [x] GET /api/admin/users/{id}/progress
- [x] GET /api/admin/reports/activity
- [x] GET /api/admin/reports/progress
- [x] GET /api/admin/reports/completion
- [x] Create AdminService
- [x] GenerateStoryForLevel()
- [x] GetAllUsers()
- [x] GetUserProgress()
- [x] GenerateActivityReport()
- [x] GenerateProgressReport()
- [x] GenerateCompletionReport()
- [x] Create UserReportService
- [x] Aggregate user data
- [x] Calculate statistics
- [x] Format reports
- [x] Create DTOs
- [x] AdminUserDto
- [x] UserProgressReportDto
- [x] ActivityReportDto
- [x] CompletionReportDto
**Deliverables:**
- All admin API endpoints working
- Reports can be generated
- User data can be retrieved
---
### Phase 4: Admin Frontend (5-6 hours)
**Priority: High** - Admin UI for managing the application
- [x] Create admin layout component
- [x] Create protected admin routes
- [x] Create AdminDashboard page
- [x] Display user count
- [x] Display story count
- [x] Display activity statistics
- [x] Quick access buttons
- [x] Create AdminUsers page
- [x] User list table with pagination
- [x] Search/filter functionality
- [x] Click to view user details
- [x] Create AdminUserDetail page
- [x] User profile information
- [x] Lesson completion progress
- [x] Story segment unlock/completion status
- [x] Activity timeline
- [x] Create AdminReports page
- [x] Report type selector
- [x] Date range picker
- [x] Report generation button
- [x] Report display (tables/charts)
- [x] Create AdminStoryGenerator page
- [x] Level selector
- [x] Theme input
- [x] Segment count input
- [x] Generate button
- [x] Progress indicator
- [x] Success/failure messages
- [x] Add admin navigation
- [x] Add role check in frontend routing
**Deliverables:**
- Complete admin UI
- All admin features accessible via web interface
- Responsive design for admin pages
---
### Milestones
| Milestone | Date | Status |
|-----------|------|--------|
| Authentication Enforcement | June 14, 2026 | Complete |
| Admin Role System | June 14, 2026 | Complete |
| Admin Backend Services | June 14, 2026 | Complete |
| Admin Frontend | June 14, 2026 | Complete |
---
## ✅ Definition of Done
### General Criteria
- [x] All code follows Clean Architecture principles
- [x] All code compiles with 0 errors
- [x] All existing tests still pass
- [x] New code has corresponding unit tests (where applicable)
- [x] Code reviewed and approved
- [x] Documentation updated
- [x] Feature works in both development and Docker environments
### Feature-Specific Criteria
- [x] All learning content endpoints return 401 for unauthenticated requests
- [x] Users must register/login before accessing any content
- [x] Admin can generate stories for all levels
- [x] Admin can view all users
- [x] Admin can view individual user progress
- [x] Admin can generate activity reports
- [x] Admin can generate progress reports
- [x] Admin can generate completion reports
- [x] Admin UI is intuitive and functional
- [x] Frontend handles 401/403 errors gracefully
---
## 🧪 Testing Strategy
### Backend Tests (MSTest + Moq)
| Test Type | Coverage | Tools |
|-----------|----------|-------|
| Unit Tests | All admin services | MSTest, Moq |
| Integration Tests | Admin endpoints | MSTest, TestServer |
| Authorization Tests | Role-based access | MSTest, Custom attributes |
#### AdminService Tests
- [ ] GenerateStoryForLevelAsync_ValidLevel_ReturnsSegments
- [ ] GenerateStoryForLevelAsync_InvalidLevel_ThrowsException
- [ ] GenerateStoryForLevelAsync_NoLessons_ThrowsException
- [ ] GetAllUsersAsync_ReturnsAllUsers
- [ ] GetUserProgressAsync_ValidUser_ReturnsProgress
- [ ] GetUserProgressAsync_InvalidUser_ThrowsException
- [ ] GenerateActivityReportAsync_ReturnsReport
- [ ] GenerateProgressReportAsync_ReturnsReport
- [ ] GenerateCompletionReportAsync_ReturnsReport
#### AdminController Tests
- [ ] GenerateStory_AdminRole_ReturnsSuccess
- [ ] GenerateStory_NonAdminRole_ReturnsForbidden
- [ ] GetAllUsers_AdminRole_ReturnsUsers
- [ ] GetAllUsers_NonAdminRole_ReturnsForbidden
- [ ] GetUserProgress_AdminRole_ReturnsProgress
- [ ] GetUserProgress_NonAdminRole_ReturnsForbidden
### Frontend Tests (Vitest)
| Test Type | Coverage | Tools |
|-----------|----------|-------|
| Unit Tests | Admin API client | Vitest |
| Component Tests | Admin pages/components | Vitest, @testing-library/react |
| Integration Tests | Auth flow + admin access | Vitest |
#### Admin API Client Tests
- [ ] generateStory_ValidRequest_ReturnsResponse
- [ ] generateStory_Unauthorized_ThrowsError
- [ ] getUsers_AdminRole_ReturnsUsers
- [ ] getUsers_NonAdminRole_ThrowsError
- [ ] getUserProgress_AdminRole_ReturnsProgress
- [ ] getReports_ReturnsReportData
#### Admin Component Tests
- [ ] AdminDashboard_RendersCorrectly
- [ ] AdminDashboard_DisplaysStatistics
- [ ] AdminUsers_ListDisplaysCorrectly
- [ ] AdminUsers_SearchWorks
- [ ] AdminUserDetail_DisplaysUserInfo
- [ ] AdminUserDetail_DisplaysProgress
- [ ] AdminReports_GeneratesCorrectly
- [ ] AdminStoryGenerator_CreatesStory
- [ ] ProtectedRoute_AdminRole_AllowsAccess
- [ ] ProtectedRoute_NonAdminRole_Redirects
---
## 🔗 Related Files
### Architecture
- [Clean Architecture Principles](../AGENTS.md)
- [Database Schema](../../GermanApp/Infrastructure/Data/DbContext/AppDbContext.cs)
- [JWT Configuration](../../GermanApp/Infrastructure/Configuration/JwtConfig.cs)
### Backend
- [AuthController](../../GermanApp/Presentation/Controllers/AuthController.cs) - Existing
- [AuthService](../../GermanApp/Application/Services/AuthService.cs) - Existing
- [StoryController](../../GermanApp/Presentation/Controllers/StoryController.cs) - Needs [Authorize]
- [StoryService](../../GermanApp/Application/Services/StoryService.cs) - Existing
- [StoryGenerationService](../../GermanApp/Application/Services/StoryGenerationService.cs) - Existing
### Frontend
- [App.tsx](../../german-app-frontend/src/App.tsx) - Needs auth routes
- [Auth API Client](../../german-app-frontend/src/lib/api/auth.ts) - May need to be created
### Database
- [User Entity](../../GermanApp/Domain/Entities/User.cs) - May need role field
- [StorySegment Entity](../../GermanApp/Domain/Entities/StorySegment.cs) - Existing
- [StoryProgress Entity](../../GermanApp/Domain/Entities/StoryProgress.cs) - Existing
---
## 📝 Notes & Decisions
### Design Decisions
1. **Single Admin User**: Initially, there will be only one admin user (Lasse). Admin role will not be assignable via API to prevent privilege escalation attacks. Admin role will be set directly in the database.
2. **Mandatory Authentication**: ALL learning content requires authentication. No exceptions. This is a core business requirement. Users cannot access stories, lessons, or quizzes without first registering and logging in.
3. **Role-Based Authorization**: Using ASP.NET Core's built-in `[Authorize(Roles = "Admin")]` attribute for admin-only endpoints. Regular authenticated users can access learning content, but only admin users can access admin endpoints.
4. **Progress Tracking**: User progress (lesson completion, story unlock/completion) is tracked per user and is essential for the story unlocking feature to work correctly.
### Gotchas & Considerations
- **CORS with Credentials**: When using JWT tokens with credentials, CORS configuration must explicitly list allowed origins (cannot use wildcard `AllowAnyOrigin()` with `AllowCredentials()`).
- **Token Storage**: Frontend stores JWT tokens in localStorage. Consider HttpOnly cookies for enhanced security (future enhancement).
- **Admin Bootstrapping**: First admin user must be created via direct database manipulation or a special bootstrap endpoint (which should be removed after first use).
- **Role Migration**: Existing User table may need a `Role` column added via migration.
### Future Enhancements
- [ ] Admin user management (add/remove admins via UI)
- [ ] Admin action audit logging
- [ ] User export/import functionality
- [ ] Bulk story generation
- [ ] Scheduled report generation (email)
- [ ] User activity notifications
---
**Last Updated**: June 14, 2025
**Note**: Phase 4 (Admin Module) authentication enforcement was completed on June 14, 2025. All learning content endpoints now require JWT authentication. The LessonsEndpoints.cs minimal API endpoints were updated to include `.RequireAuthorization()` on all GET endpoints, ensuring that all lesson-related API calls require authentication.