DeutschLernen/docs/features/user-authentication.md
Lasse Rune Hansen 76e8af4987 Add complete solution: documentation, frontend, and project files
- Add comprehensive documentation in docs/ (architecture, features, roadmap)
- Add german-app-frontend with Vite, TypeScript, ESLint configuration
- Add AGENTS.md and .gitignore

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-05-31 18:20:53 +02:00

10 KiB

Feature: User Authentication & Authorization

Status: Planned
Priority: High
Complexity: Medium
Estimate: 4-6 hours
Assignee: -
Created: May 31, 2025
Target Completion: -
PR: -
Related Features: Infrastructure Setup, Lesson Management


📌 Overview

Purpose

Implement user authentication and authorization system using ASP.NET Core Identity with JWT token-based authentication.

User Story

As a user, I want to register, login, and access my personalized learning content so that I can track my progress and continue from where I left off.

Acceptance Criteria

  • Users can register with username, email, and password
  • Users can login with email and password
  • Users receive JWT token upon successful authentication
  • JWT token is required for protected API endpoints
  • Token expiration and refresh mechanism
  • Password hashing for security
  • Current user information available via /api/auth/me

📋 Requirements

Functional Requirements

ID Requirement Priority
FR-001 User registration endpoint High
FR-002 User login endpoint High
FR-003 JWT token generation and validation High
FR-004 Protected routes require authentication High
FR-005 Current user endpoint Medium
FR-006 Password reset functionality Low
FR-007 Email verification (optional for MVP) Low

Non-Functional Requirements

  • Security: Passwords hashed with bcrypt or similar
  • Security: JWT tokens expire after 24 hours
  • Security: Refresh tokens for seamless UX
  • Performance: Authentication < 500ms
  • Compatibility: Works with React frontend

🏗️ Technical Design

Components Involved

  • Backend: AuthController, AuthService, JWT configuration
  • Database: Users table (from initial schema)
  • Models: User, LoginDto, RegisterDto, AuthResponse
  • Middleware: JWT authentication middleware

Data Flow

User Registration:
1. Frontend POST /api/auth/register with {username, email, password}
2. Backend validates input
3. Backend hashes password
4. Backend creates user in database
5. Backend generates JWT token
6. Returns {userId, token} to frontend

User Login:
1. Frontend POST /api/auth/login with {email, password}
2. Backend validates credentials
3. Backend generates JWT token
4. Returns {userId, token} to frontend

Protected Endpoint:
1. Frontend includes token in Authorization header
2. Backend middleware validates token
3. Backend processes request if valid
4. Returns 401 if token invalid/expired

API Endpoints

Endpoint Method Description Auth Required
/api/auth/register POST Register new user No
/api/auth/login POST Login existing user No
/api/auth/me GET Get current user info Yes
/api/auth/logout POST Invalidate token Yes
/api/auth/refresh POST Refresh expired token Yes

Database Schema (from application-plan.md)

CREATE TABLE Users (
    Id SERIAL PRIMARY KEY,
    Username VARCHAR(50) UNIQUE NOT NULL,
    Email VARCHAR(100) UNIQUE NOT NULL,
    PasswordHash VARCHAR(255) NOT NULL,
    CurrentLevel VARCHAR(10) DEFAULT 'A1',
    Streak INT DEFAULT 0,
    TotalPoints INT DEFAULT 0,
    CreatedAt TIMESTAMP DEFAULT NOW()
);

🚀 Implementation Plan

Phase 1: Backend Authentication (3-4 hours)

  • Create User model and DTOs (RegisterDto, LoginDto, AuthResponse)
  • Configure ASP.NET Core Identity
  • Create AuthService with user registration logic
  • Create AuthService with user login logic
  • Configure JWT token generation
  • Create AuthController with endpoints
  • Add JWT authentication middleware
  • Configure CORS for frontend

Phase 2: Database Integration (1-2 hours)

  • Update User entity to match schema
  • Configure EF Core user repository
  • Implement password hashing
  • Create user seed data (admin user)
  • Test database operations

Phase 3: Token Management (1 hour)

  • Configure JWT settings in appsettings.json
  • Implement token validation middleware
  • Add token refresh mechanism
  • Set up token expiration (24 hours)
  • Configure refresh token rotation

Phase 4: Frontend Integration (Optional - if doing full stack)

  • Create auth service in React
  • Implement login/registration forms
  • Store token in localStorage/cookies
  • Add auth headers to API requests
  • Handle token expiration

Milestones

Milestone Date Status
Backend Auth Complete -
Database Integration -
Token Management -
Frontend Integration -

Tasks

Backend

  • Create Models/User.cs with properties
  • Create DTOs/Auth/RegisterDto.cs
  • Create DTOs/Auth/LoginDto.cs
  • Create DTOs/Auth/AuthResponse.cs
  • Create Services/AuthService.cs
  • Create Controllers/AuthController.cs
  • Configure JWT in Program.cs
  • Add [Authorize] attribute to protected endpoints
  • Create AuthMiddleware.cs
  • Configure CORS policy
  • Write unit tests for AuthService
  • Write integration tests for AuthController

Database

  • Update User entity mapping
  • Create UserRepository
  • Implement password hashing
  • Create migration for Users table
  • Seed admin user

Token Management

  • Configure JWT settings
  • Implement token generation
  • Implement token validation
  • Implement token refresh
  • Set token expiration

Frontend (Optional)

  • Create authService.ts
  • Create LoginPage component
  • Create RegisterPage component
  • Create AuthContext for user state
  • Implement protected route wrapper
  • Add logout functionality

🔗 Dependencies

Feature Dependencies

Technical Dependencies

  • ASP.NET Core Identity
  • JWT Bearer Authentication package
  • BouncyCastle or similar for password hashing

Blockers

  • Infrastructure Setup must be complete first

Definition of Done

General Criteria (All Features)

  • All acceptance criteria met and verified
  • All tasks in this document completed
  • Code follows Clean Architecture principles
  • Code reviewed and approved by at least 1 team member
  • All tests passing (unit, integration)
  • Documentation updated (README, AGENTS.md if applicable)
  • Feature works in development environment
  • Feature deployed to staging environment
  • Performance meets defined targets
  • Security review completed
  • No critical bugs or blockers

Authentication-Specific Criteria

  • Users can successfully register with valid credentials
  • Users can successfully login with valid credentials
  • Invalid credentials are rejected with appropriate error messages
  • JWT tokens are generated and validated correctly
  • Token expiration works as configured
  • Token refresh mechanism works
  • Protected endpoints reject requests without valid tokens
  • Passwords are hashed and never stored in plain text
  • Rate limiting on auth endpoints configured

🧪 Testing Strategy

Testing Approach

Test Type Coverage Tools Responsibility
Unit Tests 80%+ code coverage MsTest, Moq Backend Dev
Integration Tests All service interactions MsTest, TestContainers Backend Dev
API Tests All endpoints MsTest, HttpClient Backend Dev
Frontend Unit Tests Component logic Vitest Frontend Dev
Frontend Integration Service integration Vitest Frontend Dev
E2E Tests Critical user journeys Playwright QA/Dev
Manual Testing Exploratory, edge cases BrowserStack QA

Authentication-Specific Tests

Backend Tests

  • Register with valid data → success
  • Register with duplicate email → error
  • Register with duplicate username → error
  • Register with invalid password → error
  • Login with valid credentials → success
  • Login with invalid email → error
  • Login with invalid password → error
  • Login with valid token → success
  • Login with expired token → error
  • Login with invalid token → error
  • Access protected endpoint without token → 401
  • Access protected endpoint with valid token → success
  • Access protected endpoint with invalid token → 401
  • Token refresh → new valid token
  • Rate limiting on login attempts → 429 after N attempts

Frontend Tests

  • Registration form validation
  • Registration form submission
  • Login form validation
  • Login form submission
  • Token storage in localStorage/cookies
  • Token inclusion in API requests
  • Protected route redirection
  • Logout functionality
  • Session expiration handling

📝 Notes & Decisions

Decisions Made

Date Decision Rationale
May 31, 2025 Use JWT over cookies Stateless, works well with SPAs, scalable
May 31, 2025 ASP.NET Core Identity Built-in, well-tested, integrates with EF Core
May 31, 2025 24-hour token expiration Balance between security and UX

Technical Notes

  • Store only password hash, never plain text
  • Use HttpOnly cookies for refresh tokens if possible
  • Sanitize username/email inputs to prevent injection
  • Rate limit login attempts to prevent brute force

Gotchas

  • ⚠️ JWT secret must be long and random (>32 characters)
  • ⚠️ Token must be stored securely on frontend (HttpOnly cookie or secure localStorage)
  • ⚠️ CORS must be configured to accept credentials if using cookies
  • ⚠️ Password hashing should use work factor appropriate for your hardware

📊 Progress History

Date Status Change Notes
May 31, 2025 Created Initial plan based on application-plan.md


Feature created from application-plan.md