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

18 KiB

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

  • All learning content endpoints require authentication (no public access)
  • User registration is mandatory before accessing any content
  • Admin role exists and is assigned to specific users only
  • Admin can access story generation UI/API
  • Admin can view list of all users
  • Admin can view individual user progress (lessons completed, stories unlocked)
  • Admin can generate reports on user activity
  • 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

  • Add [Authorize] to all learning content controllers
    • StoryController (GET endpoints)
    • LessonsController (GET endpoints)
    • QuizzesController (GET endpoints)
    • LevelsController (GET endpoints)
  • Add .RequireAuthorization() to all learning content minimal API endpoints
    • LessonsEndpoints.cs GET endpoints (/api/lessons, /api/lessons/{id}, /api/lessons/beginner, /api/lessons/advanced, /api/lessons/level/{level})
  • Remove [Authorize] from AuthController (register/login should be public)
  • Update CORS configuration to support credentials
  • 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

  • Define "Admin" role constant in backend
  • Modify JWT token generation to include roles
  • Update User entity to include role field
  • Add role to RegisterDto (or make first user admin)
  • Create migration for role field (if needed)
  • Add [Authorize(Roles = "Admin")] to admin endpoints
  • 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

  • Create AdminController
    • POST /api/admin/stories/generate
    • GET /api/admin/users
    • GET /api/admin/users/{id}/progress
    • GET /api/admin/reports/activity
    • GET /api/admin/reports/progress
    • GET /api/admin/reports/completion
  • Create AdminService
    • GenerateStoryForLevel()
    • GetAllUsers()
    • GetUserProgress()
    • GenerateActivityReport()
    • GenerateProgressReport()
    • GenerateCompletionReport()
  • Create UserReportService
    • Aggregate user data
    • Calculate statistics
    • Format reports
  • Create DTOs
    • AdminUserDto
    • UserProgressReportDto
    • ActivityReportDto
    • 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

  • Create admin layout component
  • Create protected admin routes
  • Create AdminDashboard page
    • Display user count
    • Display story count
    • Display activity statistics
    • Quick access buttons
  • Create AdminUsers page
    • User list table with pagination
    • Search/filter functionality
    • Click to view user details
  • Create AdminUserDetail page
    • User profile information
    • Lesson completion progress
    • Story segment unlock/completion status
    • Activity timeline
  • Create AdminReports page
    • Report type selector
    • Date range picker
    • Report generation button
    • Report display (tables/charts)
  • Create AdminStoryGenerator page
    • Level selector
    • Theme input
    • Segment count input
    • Generate button
    • Progress indicator
    • Success/failure messages
  • Add admin navigation
  • 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

  • All code follows Clean Architecture principles
  • All code compiles with 0 errors
  • All existing tests still pass
  • New code has corresponding unit tests (where applicable)
  • Code reviewed and approved
  • Documentation updated
  • Feature works in both development and Docker environments

Feature-Specific Criteria

  • All learning content endpoints return 401 for unauthenticated requests
  • Users must register/login before accessing any content
  • Admin can generate stories for all levels
  • Admin can view all users
  • Admin can view individual user progress
  • Admin can generate activity reports
  • Admin can generate progress reports
  • Admin can generate completion reports
  • Admin UI is intuitive and functional
  • 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

Architecture

Backend

Frontend

Database


📝 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.