Files
thrilltrack-explorer/migration/PHASE_02_AUTHENTICATION.md

9.5 KiB

PHASE 2: Authentication

Status: Not Started
Estimated Time: 18-22 hours
Priority: CRITICAL
Depends On: Phase 1 (Foundation)
Blocks: Phases 3-13 (Almost everything requires auth)


🎯 Phase Goal

Replace ALL supabase.auth.* calls with Django authentication service, including JWT token management, OAuth, MFA, and session handling.


📋 Prerequisites

  • Phase 1 complete (API client, types, base service)
  • Django auth endpoints tested and working
  • JWT token format documented
  • OAuth providers configured in Django

🗂️ Files to Create/Modify

src/services/auth/
├── authService.ts         (NEW)
├── oauthService.ts        (NEW)
├── mfaService.ts          (NEW)
├── types.ts               (NEW)
└── index.ts               (NEW)

src/hooks/
├── useAuth.tsx            (MODIFY - major rewrite)

src/components/auth/
├── AuthModal.tsx          (MODIFY)
├── LoginForm.tsx          (MODIFY)
├── RegisterForm.tsx       (MODIFY)
├── PasswordResetForm.tsx  (MODIFY)
├── TOTPSetup.tsx          (MODIFY)
├── MFAChallenge.tsx       (MODIFY)
└── MFARemovalDialog.tsx   (MODIFY)

Task 2.1: Auth Service Core (6 hours)

Checklist

  • Create src/services/auth/authService.ts
  • Implement login
    • login(email: string, password: string): Promise<AuthResponse>
    • Store JWT token in localStorage
    • Store refresh token
    • Return user object
  • Implement register
    • register(data: RegisterData): Promise<AuthResponse>
    • Handle email verification requirement
    • Store tokens on success
  • Implement logout
    • logout(): Promise<void>
    • Clear tokens from localStorage
    • Invalidate on server
  • Implement token refresh
    • refreshToken(): Promise<AuthResponse>
    • Auto-refresh on 401 errors
    • Handle refresh token expiry
  • Implement getCurrentUser
    • getCurrentUser(): Promise<User>
    • Use JWT token
    • Cache user data
  • Implement password reset flow
    • requestPasswordReset(email: string): Promise<void>
    • confirmPasswordReset(token: string, password: string): Promise<void>
  • Implement email verification
    • verifyEmail(token: string): Promise<void>
    • resendVerification(): Promise<void>
  • Implement email change
    • requestEmailChange(newEmail: string): Promise<void>
    • confirmEmailChange(token: string): Promise<void>
  • Implement password change
    • changePassword(current: string, newPassword: string): Promise<void>

Django Endpoints to Use

// Auth endpoints
POST   /api/v1/auth/login                 // Email/password login
POST   /api/v1/auth/register              // User registration
POST   /api/v1/auth/logout                // Logout
POST   /api/v1/auth/refresh               // Refresh JWT
GET    /api/v1/auth/me                    // Get current user
POST   /api/v1/auth/password-reset        // Request reset
POST   /api/v1/auth/password-reset/confirm  // Confirm reset
POST   /api/v1/auth/verify-email          // Verify email
POST   /api/v1/auth/change-email          // Change email
POST   /api/v1/auth/change-password       // Change password

Acceptance Criteria

  • Can login with email/password
  • Tokens stored securely
  • Auto-refresh works
  • Logout clears all tokens
  • Password reset flow works end-to-end
  • Email verification works
  • No Supabase dependencies

Task 2.2: OAuth Integration (4 hours)

Checklist

  • Create src/services/auth/oauthService.ts
  • Implement OAuth initiation
    • initiateOAuth(provider: 'google' | 'github'): void
    • Redirect to Django OAuth endpoint
    • Handle state parameter for security
  • Implement OAuth callback
    • handleOAuthCallback(code: string, state: string): Promise<AuthResponse>
    • Exchange code for tokens
    • Store tokens
    • Return user object
  • Handle OAuth errors
    • Access denied
    • Invalid state
    • Server errors
  • Test with Google OAuth
  • Test with GitHub OAuth

Django Endpoints

GET    /api/v1/auth/oauth/{provider}/       // Initiate OAuth
GET    /api/v1/auth/oauth/{provider}/callback  // Handle callback

Acceptance Criteria

  • Google OAuth works
  • GitHub OAuth works
  • Errors handled gracefully
  • State parameter validated
  • Tokens stored correctly

Task 2.3: MFA Service (3 hours)

Checklist

  • Create src/services/auth/mfaService.ts
  • Implement TOTP setup
    • setupTOTP(): Promise<{ secret: string, qrCode: string }>
    • Generate QR code URL
    • Return backup codes
  • Implement TOTP verification
    • verifyTOTP(code: string): Promise<void>
    • Enable MFA after verification
  • Implement MFA challenge
    • challengeMFA(code: string): Promise<AuthResponse>
    • Complete login with MFA code
  • Implement MFA removal
    • removeMFA(password: string): Promise<void>
    • Require password confirmation
  • Implement backup codes
    • generateBackupCodes(): Promise<string[]>
    • useBackupCode(code: string): Promise<AuthResponse>

Django Endpoints

POST   /api/v1/auth/mfa/setup              // Setup TOTP
POST   /api/v1/auth/mfa/verify             // Verify TOTP
POST   /api/v1/auth/mfa/challenge          // MFA challenge
DELETE /api/v1/auth/mfa/remove             // Remove MFA
POST   /api/v1/auth/mfa/backup-codes       // Generate backup codes

Acceptance Criteria

  • TOTP setup works
  • QR code displays correctly
  • MFA challenge works during login
  • Backup codes work
  • MFA can be removed

Task 2.4: Update useAuth Hook (5 hours)

Checklist

  • Open src/hooks/useAuth.tsx
  • Remove ALL Supabase imports
  • Replace supabase.auth.onAuthStateChange with custom implementation
    • Check token validity on mount
    • Set up interval to check token expiry
    • Trigger refresh before expiry
  • Replace supabase.auth.getSession with JWT validation
    • Decode JWT to get user info
    • Check expiry
    • Auto-refresh if needed
  • Update auth context state management
    • user state
    • session state
    • loading state
    • initialized state
  • Implement token refresh logic
    • Auto-refresh 5 minutes before expiry
    • Handle refresh failures
    • Logout on refresh failure
  • Update all auth methods to use new service
    • signIn()
    • signUp()
    • signOut()
    • resetPassword()
  • Handle session expiration gracefully
  • Add error handling for all auth operations
  • Test all auth flows

Acceptance Criteria

  • Hook works without Supabase
  • Token refresh is automatic
  • Session expiry is handled
  • User state updates correctly
  • Loading states work
  • All error cases handled

Task 2.5: Update Auth Components (4 hours)

Checklist

  • Update AuthModal.tsx
    • Remove Supabase imports
    • Use auth service instead
    • Update error handling
  • Update LoginForm.tsx
    • Use authService.login()
    • Handle MFA challenge
    • Show appropriate errors
  • Update RegisterForm.tsx
    • Use authService.register()
    • Handle validation errors
    • Show email verification message
  • Update PasswordResetForm.tsx
    • Use authService.requestPasswordReset()
    • Use authService.confirmPasswordReset()
    • Handle token expiry
  • Update TOTPSetup.tsx
    • Use mfaService.setupTOTP()
    • Display QR code
    • Handle verification
  • Update MFAChallenge.tsx
    • Use mfaService.challengeMFA()
    • Handle backup codes
  • Update MFARemovalDialog.tsx
    • Use mfaService.removeMFA()
    • Require password confirmation
  • Remove all supabase.* imports
  • Test all UI flows
  • Update error messages to be user-friendly

Acceptance Criteria

  • All forms work correctly
  • Errors display properly
  • Loading states work
  • Success messages show
  • No Supabase references remain

🎯 Phase Completion Criteria

Code Quality

  • Zero supabase.auth.* calls in codebase
  • All TypeScript errors resolved
  • No linter warnings
  • Code well-documented
  • Consistent error handling

Functionality

  • Login works (email/password)
  • Registration works
  • Logout works
  • Password reset works
  • Email verification works
  • Google OAuth works
  • GitHub OAuth works
  • TOTP MFA works
  • Backup codes work
  • Token refresh is automatic
  • Session expiry handled

Testing

  • Can login as regular user
  • Can login with OAuth
  • Can login with MFA
  • Can reset password
  • Can change email
  • Can change password
  • Token refresh works automatically
  • Session expiry redirects to login
  • All error cases handled

📊 Progress Tracking

Started: [Date]
Completed: [Date]
Time Spent: [Hours]

Tasks Completed

  • Task 2.1: Auth Service Core
  • Task 2.2: OAuth Integration
  • Task 2.3: MFA Service
  • Task 2.4: Update useAuth Hook
  • Task 2.5: Update Auth Components

🚨 Blockers & Issues

Document any issues:

  1. Issue: [Description]
    • Impact: [Impact]
    • Resolution: [Resolution]

📝 Notes

  • [Date] - [Important decision or learning]

⏭️ Next Phase

Once complete, proceed to Phase 3: Sacred Pipeline