Complex Feature

Practical Exercise 3

Hands-On

Add user authentication to an existing Todo API

The Challenge

Add authentication to an existing codebase

Current State

  • Working Todo API from Practical 2
  • No user accounts
  • All todos are public
  • No access control

Target State

  • User registration & login
  • JWT-based authentication
  • Todos belong to users
  • Protected endpoints
Duration: 60-90 minutes | Focus: Modifying existing code with AIDD

Task 1: Update vision.md

Your Task

Extend the vision document to include authentication requirements.

Update vision.md for the Todo API to include user authentication. New requirements: - User registration with email/password - JWT-based session management - Todos associated with authenticated users - Protected endpoints requiring valid tokens Update: Goals, Non-Goals, Architecture Decisions, Technical Constraints

Key Additions

  • New goal: User authentication
  • Non-goal: OAuth/social login (keep simple)
  • Architecture: JWT tokens, password hashing
  • Constraint: No third-party auth services

Task 2: Discover - New User Journeys

Your Task

Map user journeys for authentication features.

Read updated vision.md. Map user journeys for authentication: 1. New user registration journey 2. Returning user login journey 3. Authenticated user accessing their todos 4. Token expiration and refresh Include: personas, goals, steps, success criteria, edge cases

Registration

Signup → Validate → Hash → Store → Token

Login

Credentials → Verify → Generate JWT → Return

Protected Access

Request + Token → Validate → Allow/Deny

Edge Cases

Duplicate email, weak password, expired token

Task 3: Plan - Authentication Epics

Your Task

Create task epics for the authentication feature.

Suggested Epic Order

EpicSizeDependencies
1. User Model & MigrationSExisting DB
2. Password Hashing UtilitySNone
3. User Registration EndpointM1, 2
4. JWT Token GenerationMNone
5. Login EndpointM1, 2, 4
6. Auth MiddlewareM4
7. Associate Todos with UsersM1, 6
8. Protect Todo EndpointsM6, 7

Task 4: Review - Security Audit

Your Task

Have AI review the authentication plan for security issues.

Review the authentication epics for security concerns: 1. Password handling - Is hashing algorithm secure (bcrypt)? 2. Token security - JWT signing, expiration, storage 3. Input validation - SQL injection, XSS prevention 4. Rate limiting - Protection against brute force 5. Error messages - No information leakage

Security Risks

- Weak password allowed
- No rate limiting
- Token in URL params
- Plain text logging

Mitigations

- Min 8 chars + complexity
- Login attempt limits
- Bearer token in header
- Sanitize log output

Task 5: Execute - User Registration TDD

Your Task

Implement user registration with TDD, one criterion at a time.

Implement "User Registration" using TDD. Acceptance Criteria (implement one at a time): 1. POST /auth/register accepts email and password 2. Email must be valid format 3. Password must be at least 8 characters 4. Password is hashed before storage 5. Returns 201 with user ID (no password) 6. Returns 409 if email already exists Show failing test first, then implement.
Remember: Each criterion = one Red-Green-Refactor cycle. Don't batch!

Task 6: Execute - Auth Middleware

Your Task

Create authentication middleware with TDD.

Implement "Auth Middleware" using TDD. Acceptance Criteria: 1. Extracts JWT from Authorization header (Bearer token) 2. Returns 401 if no token provided 3. Returns 401 if token is invalid/expired 4. Attaches user ID to request context if valid 5. Passes to next handler Test each criterion separately.

Testing Tip

Create a helper function to generate valid test tokens. Mock the JWT verification for unit tests.

Task 7: Execute - Protect Todo Endpoints

Your Task

Update existing Todo endpoints to require authentication.

Protect Todo endpoints with authentication: Changes needed: 1. Apply auth middleware to all /todos routes 2. Filter todos by authenticated user ID 3. Prevent users from accessing others' todos 4. Update existing tests to include auth headers Maintain backward compatibility where possible.

Before

GET /todos
# Returns ALL todos

After

GET /todos
Authorization: Bearer <jwt>
# Returns user's todos only

Task 8: Test - Full Integration

Your Task

Create end-to-end tests for the complete auth flow.

Generate integration tests for complete auth flow: Scenarios: 1. Register new user -> Login -> Create todo -> Verify ownership 2. Try to access another user's todo -> Should fail 3. Access without token -> Should return 401 4. Login with wrong password -> Should return 401 5. Token expiration handling

Integration Test Checklist

  • Full user registration flow
  • Login and token generation
  • Protected endpoint access
  • User isolation (can't see others' todos)
  • Error scenarios covered

Completion Checklist

Auth Endpoints

  • POST /auth/register
  • POST /auth/login
  • Password hashing (bcrypt)
  • JWT token generation

Protected Todos

  • Auth middleware applied
  • Todos linked to users
  • User isolation enforced
  • Proper 401/403 responses

Security

  • Passwords never stored plain
  • Tokens expire appropriately
  • Input validation complete
  • No information leakage

Testing

  • Unit tests for each component
  • Integration tests for flows
  • Edge cases covered
  • All tests passing

Reflection Questions

Modifying Existing Code

How did AIDD help when adding features to an existing codebase?

Security Considerations

What security issues did the review phase catch? Would you have found them otherwise?

Test Updates

How did existing tests guide the refactoring? Did any break unexpectedly?

AI Limitations

Where did AI struggle with security-sensitive code? How did you verify correctness?

Submit: Updated repository with auth feature, updated vision.md, and all tests passing.

Practical Complete!

Complex Feature Implementation

You've mastered adding features with AIDD!

Slide Overview