# Platform Integration Authentication Flows

## Overview

This document details the authentication flows for integrating the slide-show presentation platform with four key external platforms: Daily.co, Zoom, Microsoft Teams, and WhatsApp Business. Each platform has unique authentication requirements and integration patterns that must be seamlessly integrated with our Supabase authentication system.

## Integration Architecture Principles

### 1. Unified Authentication Experience
- **Single Sign-On (SSO)**: Users authenticate once through Supabase
- **Token Delegation**: Platform-specific tokens managed server-side
- **Seamless Handoff**: Transparent authentication between platforms
- **Error Handling**: Graceful fallback for authentication failures

### 2. Security Standards
- **OAuth 2.0 Compliance**: Standard authentication flows where supported
- **Token Security**: Secure storage and refresh of platform tokens
- **Scope Limitation**: Minimal required permissions for each platform
- **Audit Trail**: Complete logging of cross-platform authentication events

## Daily.co Integration Flow

### 1. Authentication Architecture

Daily.co uses API key-based authentication rather than OAuth, requiring a different integration pattern:

```typescript
interface DailyAuthConfig {
  apiKey: string;
  domain: string;
  meetingToken?: string;
  roomName?: string;
}

class DailyAuthManager {
  private apiKey: string;
  private domain: string;

  constructor(config: DailyAuthConfig) {
    this.apiKey = config.apiKey;
    this.domain = config.domain;
  }

  async createRoom(roomConfig: DailyRoomConfig): Promise<DailyRoom> {
    const response = await fetch(`https://api.daily.co/v1/rooms`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: roomConfig.name,
        privacy: roomConfig.privacy || 'private',
        properties: {
          enable_screenshare: true,
          enable_recording: true,
          max_participants: roomConfig.maxParticipants || 10,
          ...roomConfig.properties
        }
      })
    });

    if (!response.ok) {
      throw new Error(`Failed to create Daily room: ${response.statusText}`);
    }

    return response.json();
  }

  async generateMeetingToken(roomName: string, userContext: TenantContext): Promise<string> {
    const response = await fetch(`https://api.daily.co/v1/meeting-tokens`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        properties: {
          room_name: roomName,
          user_name: userContext.displayName,
          user_id: userContext.userId,
          is_owner: userContext.role === 'admin',
          exp: Math.floor(Date.now() / 1000) + (60 * 60 * 2), // 2 hours
          enable_screenshare: true,
          enable_recording: userContext.permissions.includes('record')
        }
      })
    });

    const result = await response.json();
    return result.token;
  }
}
```

### 2. Integration Flow Sequence

```mermaid
sequenceDiagram
    participant User
    participant Frontend
    participant AuthService
    participant DailyAPI
    participant PresentationApp

    User->>Frontend: Start Presentation
    Frontend->>AuthService: Validate Supabase Session
    AuthService->>AuthService: Extract Tenant Context
    AuthService->>DailyAPI: Create Room with API Key
    DailyAPI-->>AuthService: Room Created
    AuthService->>DailyAPI: Generate Meeting Token
    DailyAPI-->>AuthService: Meeting Token
    AuthService->>Frontend: Room URL + Token
    Frontend->>PresentationApp: Launch with Daily Room
    PresentationApp->>DailyAPI: Join with Meeting Token
```

### 3. Daily.co Session Management

```typescript
class DailySessionManager {
  async initializeSession(presentationId: string, userContext: TenantContext): Promise<DailySession> {
    // Create or retrieve existing room
    const roomName = `presentation-${presentationId}-${userContext.tenantId}`;

    try {
      let room = await this.dailyAuth.getRoom(roomName);
      if (!room) {
        room = await this.dailyAuth.createRoom({
          name: roomName,
          privacy: 'private',
          maxParticipants: 50,
          properties: {
            enable_recording: userContext.permissions.includes('record'),
            enable_screenshare: true,
            enable_chat: true,
            start_video_off: false,
            start_audio_off: false
          }
        });
      }

      // Generate user-specific meeting token
      const meetingToken = await this.dailyAuth.generateMeetingToken(roomName, userContext);

      // Log session creation
      await this.securityLogger.logEvent({
        tenantId: userContext.tenantId,
        userId: userContext.userId,
        eventType: 'daily_session_created',
        eventCategory: 'access',
        resourceType: 'daily_room',
        resourceId: room.name,
        eventData: { roomName, permissions: userContext.permissions }
      });

      return {
        roomUrl: room.url,
        meetingToken,
        roomName: room.name,
        config: room.config
      };
    } catch (error) {
      await this.securityLogger.logEvent({
        tenantId: userContext.tenantId,
        userId: userContext.userId,
        eventType: 'daily_session_failed',
        eventCategory: 'auth',
        eventData: { error: error.message },
        riskScore: 25
      });
      throw error;
    }
  }
}
```

## Zoom Integration Flow

### 1. OAuth 2.0 Configuration

```typescript
interface ZoomOAuthConfig {
  clientId: string;
  clientSecret: string;
  redirectUri: string;
  scopes: string[];
}

class ZoomAuthManager {
  private config: ZoomOAuthConfig;
  private readonly authUrl = 'https://zoom.us/oauth/authorize';
  private readonly tokenUrl = 'https://zoom.us/oauth/token';

  constructor(config: ZoomOAuthConfig) {
    this.config = config;
  }

  generateAuthUrl(state: string): string {
    const params = new URLSearchParams({
      response_type: 'code',
      client_id: this.config.clientId,
      redirect_uri: this.config.redirectUri,
      scope: this.config.scopes.join(' '),
      state: state // Include tenant and user context
    });

    return `${this.authUrl}?${params.toString()}`;
  }

  async exchangeCodeForTokens(code: string): Promise<ZoomTokens> {
    const response = await fetch(this.tokenUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Basic ${Buffer.from(`${this.config.clientId}:${this.config.clientSecret}`).toString('base64')}`,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        grant_type: 'authorization_code',
        code: code,
        redirect_uri: this.config.redirectUri
      })
    });

    if (!response.ok) {
      throw new Error(`Zoom token exchange failed: ${response.statusText}`);
    }

    const tokens = await response.json();
    return {
      accessToken: tokens.access_token,
      refreshToken: tokens.refresh_token,
      expiresIn: tokens.expires_in,
      scope: tokens.scope,
      tokenType: tokens.token_type
    };
  }

  async refreshAccessToken(refreshToken: string): Promise<ZoomTokens> {
    const response = await fetch(this.tokenUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Basic ${Buffer.from(`${this.config.clientId}:${this.config.clientSecret}`).toString('base64')}`,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        grant_type: 'refresh_token',
        refresh_token: refreshToken
      })
    });

    if (!response.ok) {
      throw new Error(`Zoom token refresh failed: ${response.statusText}`);
    }

    return response.json();
  }
}
```

### 2. Zoom Meeting Creation Flow

```typescript
class ZoomMeetingManager {
  async createMeeting(accessToken: string, meetingConfig: ZoomMeetingConfig): Promise<ZoomMeeting> {
    const response = await fetch('https://api.zoom.us/v2/users/me/meetings', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        topic: meetingConfig.topic,
        type: 2, // Scheduled meeting
        start_time: meetingConfig.startTime,
        duration: meetingConfig.duration,
        timezone: meetingConfig.timezone || 'UTC',
        settings: {
          join_before_host: true,
          mute_upon_entry: false,
          use_pmi: false,
          approval_type: 0, // Automatically approve
          registration_type: 1, // Attendees register once
          audio: 'both',
          video: true,
          enforce_login: false,
          enforce_login_domains: '',
          alternative_hosts: '',
          close_registration: false,
          show_share_button: true,
          allow_multiple_devices: true,
          registrants_confirmation_email: true,
          waiting_room: false,
          request_permission_to_unmute_participants: false,
          meeting_authentication: false
        }
      })
    });

    if (!response.ok) {
      throw new Error(`Failed to create Zoom meeting: ${response.statusText}`);
    }

    return response.json();
  }
}
```

### 3. Zoom Integration Sequence

```mermaid
sequenceDiagram
    participant User
    participant Frontend
    participant AuthService
    participant ZoomOAuth
    participant ZoomAPI

    User->>Frontend: Connect Zoom Account
    Frontend->>AuthService: Initiate Zoom OAuth
    AuthService->>ZoomOAuth: Generate Auth URL
    ZoomOAuth-->>AuthService: Auth URL
    AuthService->>Frontend: Redirect to Zoom
    Frontend->>ZoomOAuth: User Authorizes
    ZoomOAuth->>AuthService: Authorization Code
    AuthService->>ZoomOAuth: Exchange Code for Tokens
    ZoomOAuth-->>AuthService: Access & Refresh Tokens
    AuthService->>AuthService: Store Tokens Securely

    Note over User, ZoomAPI: Later: Create Meeting
    User->>Frontend: Start Zoom Meeting
    Frontend->>AuthService: Request Meeting Creation
    AuthService->>AuthService: Validate & Refresh Token
    AuthService->>ZoomAPI: Create Meeting
    ZoomAPI-->>AuthService: Meeting Details
    AuthService->>Frontend: Meeting URL & Details
```

## Microsoft Teams Integration Flow

### 1. Microsoft Graph OAuth Configuration

```typescript
interface TeamsOAuthConfig {
  clientId: string;
  clientSecret: string;
  tenantId: string;
  redirectUri: string;
  scopes: string[];
}

class TeamsAuthManager {
  private config: TeamsOAuthConfig;
  private readonly authUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
  private readonly tokenUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';

  constructor(config: TeamsOAuthConfig) {
    this.config = config;
  }

  generateAuthUrl(state: string): string {
    const params = new URLSearchParams({
      client_id: this.config.clientId,
      response_type: 'code',
      redirect_uri: this.config.redirectUri,
      scope: this.config.scopes.join(' '),
      response_mode: 'query',
      state: state
    });

    return `${this.authUrl}?${params.toString()}`;
  }

  async exchangeCodeForTokens(code: string): Promise<TeamsTokens> {
    const response = await fetch(this.tokenUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        client_id: this.config.clientId,
        client_secret: this.config.clientSecret,
        code: code,
        grant_type: 'authorization_code',
        redirect_uri: this.config.redirectUri,
        scope: this.config.scopes.join(' ')
      })
    });

    if (!response.ok) {
      throw new Error(`Teams token exchange failed: ${response.statusText}`);
    }

    return response.json();
  }
}
```

### 2. Teams Meeting Creation

```typescript
class TeamsMeetingManager {
  async createOnlineMeeting(accessToken: string, meetingConfig: TeamsMeetingConfig): Promise<TeamsMeeting> {
    const response = await fetch('https://graph.microsoft.com/v1.0/me/onlineMeetings', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        subject: meetingConfig.subject,
        startDateTime: meetingConfig.startDateTime,
        endDateTime: meetingConfig.endDateTime,
        participants: {
          organizer: {
            identity: {
              user: {
                id: meetingConfig.organizerId
              }
            }
          },
          attendees: meetingConfig.attendees?.map(attendee => ({
            identity: {
              user: {
                id: attendee.userId,
                displayName: attendee.displayName
              }
            }
          })) || []
        },
        allowedPresenters: 'everyone',
        allowMeetingChat: 'enabled',
        allowTeamworkReactions: true,
        recordAutomatically: meetingConfig.recordAutomatically || false
      })
    });

    if (!response.ok) {
      throw new Error(`Failed to create Teams meeting: ${response.statusText}`);
    }

    return response.json();
  }

  async generateJoinUrl(accessToken: string, meetingId: string, userContext: TenantContext): Promise<string> {
    // Get meeting details
    const response = await fetch(`https://graph.microsoft.com/v1.0/me/onlineMeetings/${meetingId}`, {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    });

    if (!response.ok) {
      throw new Error(`Failed to get Teams meeting: ${response.statusText}`);
    }

    const meeting = await response.json();
    return meeting.joinWebUrl;
  }
}
```

## WhatsApp Business Integration Flow

### 1. WhatsApp Business Authentication

```typescript
interface WhatsAppAuthConfig {
  appId: string;
  appSecret: string;
  systemUserToken: string;
  businessAccountId: string;
  phoneNumberId: string;
}

class WhatsAppAuthManager {
  private config: WhatsAppAuthConfig;
  private readonly baseUrl = 'https://graph.facebook.com/v18.0';

  constructor(config: WhatsAppAuthConfig) {
    this.config = config;
  }

  async generateBusinessToken(customerCode: string): Promise<WhatsAppBusinessToken> {
    // Exchange code for business integration token
    const response = await fetch(`${this.baseUrl}/oauth/access_token`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        client_id: this.config.appId,
        client_secret: this.config.appSecret,
        code: customerCode
      })
    });

    if (!response.ok) {
      throw new Error(`WhatsApp token exchange failed: ${response.statusText}`);
    }

    return response.json();
  }

  async validateToken(accessToken: string): Promise<boolean> {
    try {
      const response = await fetch(`${this.baseUrl}/me?access_token=${accessToken}`);
      return response.ok;
    } catch (error) {
      return false;
    }
  }
}
```

### 2. WhatsApp Message Integration

```typescript
class WhatsAppMessagingManager {
  async sendPresentationInvite(
    accessToken: string,
    phoneNumberId: string,
    invite: PresentationInvite
  ): Promise<WhatsAppMessageResponse> {
    const messageData = {
      messaging_product: 'whatsapp',
      to: invite.recipientPhone,
      type: 'template',
      template: {
        name: 'presentation_invite',
        language: {
          code: 'en_US'
        },
        components: [
          {
            type: 'header',
            parameters: [
              {
                type: 'text',
                text: invite.presentationTitle
              }
            ]
          },
          {
            type: 'body',
            parameters: [
              {
                type: 'text',
                text: invite.organizerName
              },
              {
                type: 'text',
                text: invite.scheduledTime
              },
              {
                type: 'text',
                text: invite.joinUrl
              }
            ]
          }
        ]
      }
    };

    const response = await fetch(`${this.baseUrl}/${phoneNumberId}/messages`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(messageData)
    });

    if (!response.ok) {
      throw new Error(`Failed to send WhatsApp invitation: ${response.statusText}`);
    }

    return response.json();
  }

  async handleWebhook(webhookData: WhatsAppWebhookData): Promise<void> {
    // Process incoming WhatsApp messages
    for (const entry of webhookData.entry) {
      for (const change of entry.changes) {
        if (change.field === 'messages') {
          for (const message of change.value.messages || []) {
            await this.processIncomingMessage(message, change.value.metadata);
          }
        }
      }
    }
  }

  private async processIncomingMessage(message: WhatsAppMessage, metadata: WhatsAppMetadata): Promise<void> {
    // Handle RSVP responses, questions, etc.
    if (message.type === 'text') {
      const response = await this.parseTextResponse(message.text.body);
      if (response.type === 'rsvp') {
        await this.updatePresentationRSVP(message.from, response.presentationId, response.status);
      }
    }
  }
}
```

## Unified Platform Authentication Service

### 1. Platform Integration Orchestrator

```typescript
class PlatformIntegrationOrchestrator {
  private dailyAuth: DailyAuthManager;
  private zoomAuth: ZoomAuthManager;
  private teamsAuth: TeamsAuthManager;
  private whatsappAuth: WhatsAppAuthManager;
  private securityLogger: SecurityLogger;

  async initializePresentationSession(
    presentationId: string,
    userContext: TenantContext,
    platforms: string[]
  ): Promise<PlatformSessionResponse> {
    const sessions: Record<string, any> = {};
    const errors: Record<string, string> = {};

    // Initialize sessions for each requested platform
    for (const platform of platforms) {
      try {
        switch (platform) {
          case 'daily':
            sessions.daily = await this.initializeDailySession(presentationId, userContext);
            break;
          case 'zoom':
            sessions.zoom = await this.initializeZoomSession(presentationId, userContext);
            break;
          case 'teams':
            sessions.teams = await this.initializeTeamsSession(presentationId, userContext);
            break;
          case 'whatsapp':
            sessions.whatsapp = await this.initializeWhatsAppSession(presentationId, userContext);
            break;
          default:
            errors[platform] = 'Unsupported platform';
        }
      } catch (error) {
        errors[platform] = error.message;
        await this.securityLogger.logEvent({
          tenantId: userContext.tenantId,
          userId: userContext.userId,
          eventType: `${platform}_session_failed`,
          eventCategory: 'auth',
          eventData: { error: error.message, presentationId },
          riskScore: 25
        });
      }
    }

    return { sessions, errors };
  }

  async validateAllPlatformTokens(userContext: TenantContext): Promise<PlatformValidationResult> {
    const validationResults: Record<string, boolean> = {};

    // Check stored tokens for each platform
    const storedTokens = await this.getStoredPlatformTokens(userContext.tenantId, userContext.userId);

    for (const [platform, tokens] of Object.entries(storedTokens)) {
      try {
        switch (platform) {
          case 'zoom':
            validationResults[platform] = await this.validateZoomToken(tokens.accessToken);
            break;
          case 'teams':
            validationResults[platform] = await this.validateTeamsToken(tokens.accessToken);
            break;
          case 'whatsapp':
            validationResults[platform] = await this.validateWhatsAppToken(tokens.accessToken);
            break;
          default:
            validationResults[platform] = false;
        }
      } catch (error) {
        validationResults[platform] = false;
      }
    }

    return { validationResults, requiresReauth: Object.values(validationResults).some(v => !v) };
  }
}
```

### 2. Token Storage and Management

```sql
-- Platform tokens table with tenant isolation
CREATE TABLE platform_tokens (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  platform TEXT NOT NULL CHECK (platform IN ('zoom', 'teams', 'whatsapp')),
  access_token TEXT NOT NULL,
  refresh_token TEXT,
  expires_at TIMESTAMPTZ,
  scope TEXT,
  token_type TEXT DEFAULT 'Bearer',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(tenant_id, user_id, platform)
);

-- RLS for platform tokens
CREATE POLICY "Tenant platform tokens access"
ON platform_tokens
USING (
  tenant_id = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')::UUID
  AND user_id = auth.uid()
);

-- Indexes for performance
CREATE INDEX idx_platform_tokens_tenant_user ON platform_tokens(tenant_id, user_id);
CREATE INDEX idx_platform_tokens_platform ON platform_tokens(platform);
CREATE INDEX idx_platform_tokens_expires_at ON platform_tokens(expires_at);
```

### 3. Security and Monitoring

```typescript
class PlatformSecurityManager {
  async auditPlatformAccess(
    userContext: TenantContext,
    platform: string,
    action: string,
    resourceId?: string
  ): Promise<void> {
    await this.securityLogger.logEvent({
      tenantId: userContext.tenantId,
      userId: userContext.userId,
      eventType: `${platform}_${action}`,
      eventCategory: 'access',
      resourceType: platform,
      resourceId: resourceId,
      eventData: {
        platform,
        action,
        timestamp: new Date().toISOString(),
        userRole: userContext.role
      }
    });
  }

  async detectAnomalousActivity(userContext: TenantContext): Promise<SecurityAlert[]> {
    const alerts: SecurityAlert[] = [];

    // Check for unusual platform access patterns
    const recentEvents = await this.getRecentSecurityEvents(userContext.tenantId, userContext.userId);

    // Multiple platform failures in short time
    const failureEvents = recentEvents.filter(e =>
      e.event_type.includes('_failed') &&
      e.created_at > new Date(Date.now() - 15 * 60 * 1000) // Last 15 minutes
    );

    if (failureEvents.length >= 5) {
      alerts.push({
        type: 'multiple_auth_failures',
        severity: 'high',
        description: 'Multiple platform authentication failures detected',
        recommendedAction: 'Review user credentials and platform configurations'
      });
    }

    return alerts;
  }
}
```

## Error Handling and Fallback Strategies

### 1. Authentication Failure Recovery

```typescript
class AuthFailureRecoveryManager {
  async handlePlatformAuthFailure(
    platform: string,
    userContext: TenantContext,
    error: PlatformAuthError
  ): Promise<RecoveryAction> {
    switch (error.type) {
      case 'token_expired':
        return await this.attemptTokenRefresh(platform, userContext);

      case 'invalid_credentials':
        return {
          action: 'reauthenticate',
          redirectUrl: await this.generateReauthUrl(platform, userContext),
          message: `Please reconnect your ${platform} account`
        };

      case 'rate_limited':
        return {
          action: 'retry_later',
          retryAfter: error.retryAfter || 300,
          message: `${platform} rate limit exceeded. Please try again later.`
        };

      case 'platform_unavailable':
        return {
          action: 'use_alternative',
          alternatives: this.getAvailablePlatforms(userContext),
          message: `${platform} is currently unavailable. Please use an alternative platform.`
        };

      default:
        return {
          action: 'contact_support',
          message: 'An unexpected error occurred. Please contact support.'
        };
    }
  }

  private async attemptTokenRefresh(platform: string, userContext: TenantContext): Promise<RecoveryAction> {
    try {
      const tokens = await this.getStoredPlatformTokens(userContext.tenantId, userContext.userId);
      const platformTokens = tokens[platform];

      if (!platformTokens?.refresh_token) {
        throw new Error('No refresh token available');
      }

      let newTokens;
      switch (platform) {
        case 'zoom':
          newTokens = await this.zoomAuth.refreshAccessToken(platformTokens.refresh_token);
          break;
        case 'teams':
          newTokens = await this.teamsAuth.refreshAccessToken(platformTokens.refresh_token);
          break;
        default:
          throw new Error('Token refresh not supported for this platform');
      }

      await this.storePlatformTokens(userContext.tenantId, userContext.userId, platform, newTokens);

      return {
        action: 'retry_request',
        message: 'Authentication refreshed successfully'
      };
    } catch (error) {
      return {
        action: 'reauthenticate',
        redirectUrl: await this.generateReauthUrl(platform, userContext),
        message: `Token refresh failed. Please reconnect your ${platform} account`
      };
    }
  }
}
```

## Conclusion

This comprehensive platform integration authentication system provides secure, scalable access to Daily.co, Zoom, Microsoft Teams, and WhatsApp Business platforms. The architecture maintains security best practices while providing a seamless user experience across all platforms.

Key features include:
- **Unified Authentication**: Single sign-on through Supabase with platform-specific token management
- **Security First**: Complete audit trails, token encryption, and anomaly detection
- **Error Resilience**: Graceful failure handling with automatic recovery strategies
- **Multi-Tenant Isolation**: Complete data separation between tenants across all platforms
- **Performance Optimization**: Efficient token refresh and validation mechanisms

The system is designed to be extensible for additional platforms while maintaining the security and isolation requirements of the multi-tenant slide-show presentation platform.