# Authentication System Migration Guide

This guide explains how to migrate from the old authentication system to the new modular auth system.

## Overview

The new authentication system provides:
- **Modular architecture** with clear separation of concerns
- **Provider-agnostic** design supporting multiple auth providers
- **Type-safe** with full TypeScript support
- **React hooks** for easy integration
- **Route guards** for protecting components
- **Comprehensive testing** with Playwright
- **Better error handling** and user feedback

## Migration Steps

### 1. Update Imports

**Old:**
```typescript
import { auth } from '../lib/auth-unified'
import { requireAuth } from '../lib/auth-unified'
```

**New:**
```typescript
import { useAuth, RequireAuth, authManager } from '../lib/auth'
```

### 2. Replace Auth Context Usage

**Old:**
```typescript
const { user, isAuthenticated } = useContext(AuthContext)
```

**New:**
```typescript
const { state, signIn, signOut } = useAuth()
const { user, isAuthenticated } = state
```

### 3. Update Component Protection

**Old:**
```typescript
import { ProtectedRoute } from '../components/ProtectedRoute'

function Dashboard() {
  return (
    <ProtectedRoute>
      <div>Dashboard content</div>
    </ProtectedRoute>
  )
}
```

**New:**
```typescript
import { RequireAuth } from '../lib/auth'

function Dashboard() {
  return (
    <RequireAuth>
      <div>Dashboard content</div>
    </RequireAuth>
  )
}
```

### 4. Update Role-based Access Control

**Old:**
```typescript
if (user?.is_admin) {
  // Admin content
}
```

**New:**
```typescript
import { usePermissions } from '../lib/auth'

const { isAdmin, canAccessAdminPanel } = usePermissions()

if (isAdmin) {
  // Admin content
}
```

### 5. Update API Client Usage

**Old:**
```typescript
import { apiClient } from '../lib/api-client'

const response = await apiClient.get('/api/events')
```

**New:**
```typescript
import { createAuthAwareApiClient } from '../lib/auth'

const apiClient = createAuthAwareApiClient(authManager)
const response = await apiClient.get('/api/events')
```

### 6. Update Login/Logout Handlers

**Old:**
```typescript
const handleLogin = async (email: string, password: string) => {
  const result = await auth.signIn({ email, password })
  if (result.error) {
    setError(result.error.message)
  }
}
```

**New:**
```typescript
const { signIn } = useAuth()

const handleLogin = async (email: string, password: string) => {
  const result = await signIn({ email, password })
  if (result.error) {
    setError(result.error.message)
  }
}
```

### 7. Update Forms

**Old:**
```typescript
<form onSubmit={handleSubmit}>
  <input name="email" type="email" />
  <input name="password" type="password" />
  <button type="submit">Sign In</button>
</form>
```

**New:**
```typescript
import { SignInForm } from '../lib/auth'

<SignInForm 
  onSuccess={() => navigate('/dashboard')}
  onError={(error) => setError(error)}
/>
```

## Component Replacements

### AuthProvider Setup

**Old:**
```typescript
// No central auth provider
```

**New:**
```typescript
import { AuthProvider, authManager } from '../lib/auth'

function App() {
  return (
    <AuthProvider authManager={authManager}>
      <Routes>
        {/* Your routes */}
      </Routes>
    </AuthProvider>
  )
}
```

### Route Protection

**Old:**
```typescript
// Manual auth checks in components
useEffect(() => {
  if (!user) {
    navigate('/login')
  }
}, [user])
```

**New:**
```typescript
import { RequireAuth, RequireRole } from '../lib/auth'

<RequireAuth>
  <Dashboard />
</RequireAuth>

<RequireRole role="admin">
  <AdminPanel />
</RequireRole>
```

### Permission Checking

**Old:**
```typescript
const canManageEvents = user?.is_admin || user?.is_super_admin
```

**New:**
```typescript
const { canManageEvents } = usePermissions()
```

## API Changes

### Authentication Methods

| Old Method | New Method | Notes |
|------------|------------|-------|
| `auth.signIn()` | `signIn()` from `useAuth()` | Returns Promise with result |
| `auth.signOut()` | `signOut()` from `useAuth()` | Async method |
| `auth.getUser()` | `state.user` from `useAuth()` | Reactive state |
| `auth.isAuthenticated()` | `state.isAuthenticated` from `useAuth()` | Reactive state |

### Permission Methods

| Old Method | New Method | Notes |
|------------|------------|-------|
| `user?.is_admin` | `hasRole('admin')` | Centralized role checking |
| `user?.is_super_admin` | `hasRole('super_admin')` | Consistent naming |
| Manual permission checks | `hasPermission('canManageEvents')` | Granular permissions |

## Configuration

### Environment Variables

The new system uses the same environment variables:
- `PUBLIC_SUPABASE_URL`
- `PUBLIC_SUPABASE_ANON_KEY`
- `SUPABASE_SERVICE_ROLE_KEY`

### Cookie Configuration

The new system automatically handles cookies with secure defaults:
- `httpOnly: true`
- `secure: true` (in production)
- `sameSite: 'lax'`
- `path: '/'`

## Testing

### Unit Tests

**Old:**
```typescript
// Manual mocking required
```

**New:**
```typescript
import { render, screen } from '@testing-library/react'
import { AuthProvider } from '../lib/auth'

// Mock auth manager for testing
const mockAuthManager = {
  getState: () => ({ user: null, isAuthenticated: false }),
  signIn: jest.fn(),
  signOut: jest.fn(),
  // ... other methods
}

render(
  <AuthProvider authManager={mockAuthManager}>
    <YourComponent />
  </AuthProvider>
)
```

### Integration Tests

The new system includes comprehensive Playwright tests:
- Authentication flows
- Role-based access control
- Error handling
- Session management

## Common Migration Issues

### 1. Missing Auth Provider

**Error:** "useAuth must be used within an AuthProvider"

**Solution:** Wrap your app with `AuthProvider`:
```typescript
<AuthProvider authManager={authManager}>
  <App />
</AuthProvider>
```

### 2. Async State Updates

**Error:** Component renders before auth state is loaded

**Solution:** Check loading state:
```typescript
const { state } = useAuth()

if (state.isLoading) {
  return <LoadingSpinner />
}
```

### 3. Role Checking

**Error:** `user.is_admin` is undefined

**Solution:** Use permission hooks:
```typescript
const { isAdmin } = usePermissions()
```

### 4. API Authentication

**Error:** API calls not authenticated

**Solution:** Use auth-aware API client:
```typescript
import { createAuthAwareApiClient } from '../lib/auth'

const apiClient = createAuthAwareApiClient(authManager)
```

## Performance Considerations

### 1. Auth State Subscriptions

The new system uses React context with optimized re-renders. Components only re-render when auth state actually changes.

### 2. Token Refresh

Automatic token refresh happens in the background without affecting user experience.

### 3. Session Storage

Efficient session storage with automatic cleanup and validation.

## Security Improvements

### 1. Secure Cookies

All session data is stored in httpOnly cookies, preventing XSS attacks.

### 2. Token Validation

Automatic token validation and refresh prevents expired token issues.

### 3. Role-based Access

Centralized permission system prevents authorization bypass.

## Rollback Plan

If issues arise, you can temporarily revert to the old system:

1. Keep old auth files temporarily
2. Update imports to use old system
3. Fix any immediate issues
4. Plan migration fixes

## Support

For migration issues:
1. Check the integration example in `src/lib/auth/integration-example.tsx`
2. Review test files for usage patterns
3. Refer to TypeScript types for API documentation

## Next Steps

After migration:
1. Remove old auth files
2. Update documentation
3. Train team on new patterns
4. Monitor for issues
5. Optimize performance