# Black Canyon Tickets - New Authentication System

A complete, modular authentication system built for the Black Canyon Tickets platform using Astro, React, and Supabase.

## Features

✅ **Modular Architecture** - Clean separation of concerns with pluggable providers  
✅ **Type Safety** - Full TypeScript support with generated types  
✅ **Provider Agnostic** - Easy to switch between auth providers  
✅ **React Integration** - Custom hooks and context for seamless React usage  
✅ **Route Protection** - Declarative guards for protecting components  
✅ **Role-based Access** - Granular permissions and role management  
✅ **Session Management** - Secure cookie-based sessions with auto-refresh  
✅ **Comprehensive Testing** - Full Playwright test suite  
✅ **Error Handling** - Robust error handling with user-friendly messages  
✅ **NGINX Compatible** - Works behind reverse proxy with SSL termination  

## Quick Start

### 1. Installation

```bash
npm install @supabase/supabase-js
```

### 2. Environment Setup

```bash
# .env
PUBLIC_SUPABASE_URL=https://your-project.supabase.co
PUBLIC_SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
```

### 3. Basic Usage

```typescript
import { AuthProvider, useAuth, RequireAuth } from '../lib/auth'
import { authManager } from '../lib/auth'

// Wrap your app with AuthProvider
function App() {
  return (
    <AuthProvider authManager={authManager}>
      <Routes />
    </AuthProvider>
  )
}

// Use auth in components
function Dashboard() {
  const { state, signOut } = useAuth()
  
  return (
    <RequireAuth>
      <div>
        <h1>Welcome, {state.user?.email}!</h1>
        <button onClick={signOut}>Sign Out</button>
      </div>
    </RequireAuth>
  )
}
```

## Architecture

### Core Components

```
src/lib/auth/
├── core/           # Authentication manager and core logic
├── providers/      # Auth providers (Supabase, etc.)
├── hooks/          # React hooks for auth state
├── components/     # Pre-built auth components
├── guards/         # Route protection components
├── utils/          # Utilities and helpers
├── middleware/     # API middleware for auth
└── types/          # TypeScript type definitions
```

### Key Classes

- **AuthManager** - Central authentication manager
- **SupabaseAuthProvider** - Supabase authentication implementation
- **SessionManager** - Session storage and management
- **AuthAwareApiClient** - API client with automatic auth headers

## API Reference

### useAuth Hook

```typescript
const {
  state,           // AuthState: { user, session, isLoading, isAuthenticated, error }
  signIn,          // (credentials) => Promise<AuthResult>
  signUp,          // (credentials) => Promise<AuthResult>
  signOut,         // () => Promise<void>
  resetPassword,   // (email) => Promise<void>
  updatePassword,  // (password) => Promise<void>
  refreshSession,  // () => Promise<Session | null>
  hasPermission,   // (permission) => boolean
  hasRole,         // (role) => boolean
  requireAuth,     // () => void (throws if not authenticated)
  requireRole,     // (role) => void (throws if insufficient role)
} = useAuth()
```

### usePermissions Hook

```typescript
const {
  hasPermission,        // (permission) => boolean
  hasRole,             // (role) => boolean
  canManageEvents,     // boolean
  canManageUsers,      // boolean
  canAccessAdminPanel, // boolean
  isAdmin,            // boolean
  isSuperAdmin,       // boolean
  // ... more permissions
} = usePermissions()
```

## Components

### AuthProvider

```typescript
<AuthProvider authManager={authManager}>
  <App />
</AuthProvider>
```

### SignInForm

```typescript
<SignInForm 
  onSuccess={() => navigate('/dashboard')}
  onError={(error) => setError(error)}
  className="my-form-styles"
/>
```

### SignUpForm

```typescript
<SignUpForm 
  onSuccess={() => navigate('/dashboard')}
  onError={(error) => setError(error)}
  organizationId="optional-org-id"
/>
```

### UserMenu

```typescript
<UserMenu className="ml-auto" />
```

## Route Guards

### RequireAuth

```typescript
<RequireAuth redirectTo="/login">
  <Dashboard />
</RequireAuth>
```

### RequireRole

```typescript
<RequireRole role="admin" fallback={<AccessDenied />}>
  <AdminPanel />
</RequireRole>
```

### RequirePermission

```typescript
<RequirePermission permission="canManageEvents">
  <EventManager />
</RequirePermission>
```

## Role-based Access Control

### User Roles

- **user** - Basic user access
- **admin** - Organization admin access  
- **super_admin** - Platform-wide admin access
- **territory_manager** - Territory management access

### Permissions

- `canManageEvents` - Create/edit/delete events
- `canManageUsers` - Manage organization users
- `canManageOrganization` - Organization settings
- `canAccessAdminPanel` - Admin dashboard access
- `canManageTerritories` - Territory management
- `canViewAnalytics` - Analytics access
- `canManagePayments` - Payment management

## API Client

### Basic Usage

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

const apiClient = createAuthAwareApiClient(authManager)

// Automatic auth headers
const response = await apiClient.get('/api/events')
const newEvent = await apiClient.post('/api/events', eventData)
```

### Configuration

```typescript
const apiClient = createAuthAwareApiClient(authManager, {
  baseUrl: 'https://api.example.com',
  timeout: 30000,
  retryAttempts: 3,
  retryDelay: 1000,
  defaultHeaders: {
    'X-Client-Version': '1.0.0'
  }
})
```

## Testing

### Unit Tests

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

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

test('renders login form', () => {
  render(
    <AuthProvider authManager={mockAuthManager}>
      <LoginForm />
    </AuthProvider>
  )
  
  expect(screen.getByLabelText('Email')).toBeInTheDocument()
})
```

### Integration Tests

```bash
# Run Playwright tests
npx playwright test tests/auth/
```

## Security Features

### Session Management

- **httpOnly cookies** - Prevent XSS access to tokens
- **Secure cookies** - HTTPS-only in production
- **SameSite protection** - CSRF protection
- **Automatic refresh** - Seamless token renewal

### Role-based Access

- **Centralized permissions** - Single source of truth
- **Server-side validation** - API routes validate auth
- **Client-side guards** - Prevent unauthorized renders

### Error Handling

- **Secure error messages** - No sensitive info exposed
- **Automatic retry** - Network failure recovery
- **Graceful degradation** - Fallback behaviors

## Production Deployment

### NGINX Configuration

The system is designed to work behind NGINX reverse proxy:

```nginx
server {
  listen 443 ssl;
  server_name yourdomain.com;
  
  # SSL configuration handled by Certbot
  
  location / {
    proxy_pass http://localhost:4321;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    
    # Cookie security
    proxy_cookie_path / "/; HttpOnly; Secure; SameSite=Lax";
  }
}
```

### Environment Variables

```bash
# Production
PUBLIC_SUPABASE_URL=https://your-project.supabase.co
PUBLIC_SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key

# Optional
NODE_ENV=production
```

### Docker Support

```dockerfile
FROM node:18-alpine

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

EXPOSE 4321
CMD ["npm", "start"]
```

## Migration from Old System

See [MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md) for detailed migration instructions.

## Troubleshooting

### Common Issues

1. **"useAuth must be used within an AuthProvider"**
   - Wrap your app with `<AuthProvider>`

2. **Components render before auth loads**
   - Check `state.isLoading` before rendering

3. **API calls not authenticated**
   - Use `createAuthAwareApiClient()` instead of fetch

4. **Permission denied errors**
   - Verify user roles and permissions

### Debug Mode

```typescript
// Enable debug logging
localStorage.setItem('auth_debug', 'true')
```

## Contributing

1. Follow TypeScript strict mode
2. Add tests for new features
3. Update documentation
4. Follow existing code patterns
5. Ensure NGINX compatibility

## License

This authentication system is part of the Black Canyon Tickets platform and is proprietary software.

## Support

For issues and questions:
- Check the [MIGRATION_GUIDE.md](./MIGRATION_GUIDE.md)
- Review test files for usage examples
- Check TypeScript types for API documentation