# Authentication Architecture Patterns for Multi-Tenant Slide Show Platform

## Overview

This document outlines the authentication architecture patterns designed for the slide-show presentation platform, focusing on multi-tenant security, data isolation, and cross-platform integration. The architecture implements a security-first approach using Supabase Auth with Row Level Security (RLS) policies to ensure complete tenant isolation.

## Architecture Principles

### 1. Security-First Design
- **Zero Trust Model**: No implicit trust between components
- **Least Privilege Access**: Minimum required permissions for each role
- **Defense in Depth**: Multiple security layers for comprehensive protection
- **Data Isolation**: Complete separation between tenant data

### 2. Multi-Tenant Isolation
- **Shared Infrastructure**: Single database with logical separation
- **Tenant Identification**: JWT-based tenant context propagation
- **Resource Isolation**: Separate storage buckets and compute resources
- **Audit Segregation**: Tenant-specific logging and monitoring

## Core Authentication Architecture

### 1. Authentication Flow Architecture

```mermaid
graph TD
    A[Client Application] --> B[Supabase Auth]
    B --> C{Authentication Method}
    C -->|Email/Password| D[Email Auth]
    C -->|OAuth| E[OAuth Provider]
    C -->|Magic Link| F[Email Magic Link]
    C -->|Phone| G[SMS/WhatsApp Auth]

    D --> H[JWT Token Generation]
    E --> H
    F --> H
    G --> H

    H --> I[Custom Claims Injection]
    I --> J[Tenant Context Addition]
    J --> K[Client Session Establishment]

    K --> L[API Gateway]
    L --> M[RLS Policy Enforcement]
    M --> N[Database Access]
```

### 2. Tenant Context Propagation

```typescript
interface TenantContext {
  tenantId: string;
  userId: string;
  role: 'admin' | 'user' | 'viewer';
  permissions: string[];
  organizationId?: string;
  teamIds: string[];
}

interface CustomJWTClaims {
  sub: string;
  email: string;
  app_metadata: {
    tenant_id: string;
    role: string;
    permissions: string[];
    organization_id?: string;
    team_ids: string[];
  };
  user_metadata: {
    full_name: string;
    avatar_url?: string;
    preferences: Record<string, any>;
  };
}
```

## Multi-Tenant Data Architecture

### 1. Database Schema with Tenant Isolation

```sql
-- Core tenant table
CREATE TABLE tenants (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  subdomain TEXT UNIQUE NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  settings JSONB DEFAULT '{}'::jsonb,
  status TEXT DEFAULT 'active' CHECK (status IN ('active', 'suspended', 'terminated'))
);

-- Enhanced user profiles with tenant context
CREATE TABLE user_profiles (
  id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('admin', 'user', 'viewer')),
  permissions TEXT[] DEFAULT ARRAY[]::TEXT[],
  team_ids UUID[] DEFAULT ARRAY[]::UUID[],
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  metadata JSONB DEFAULT '{}'::jsonb
);

-- Presentations with multi-tenant support
CREATE TABLE presentations (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  created_by UUID NOT NULL REFERENCES auth.users(id),
  team_id UUID REFERENCES teams(id),
  title TEXT NOT NULL,
  description TEXT,
  slides JSONB DEFAULT '[]'::jsonb,
  settings JSONB DEFAULT '{}'::jsonb,
  status TEXT DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Team management with tenant isolation
CREATE TABLE teams (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  name TEXT NOT NULL,
  description TEXT,
  created_by UUID NOT NULL REFERENCES auth.users(id),
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Team membership with role-based access
CREATE TABLE team_members (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  team_id UUID NOT NULL REFERENCES teams(id) ON DELETE CASCADE,
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  role TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('owner', 'admin', 'member', 'viewer')),
  permissions TEXT[] DEFAULT ARRAY[]::TEXT[],
  joined_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(team_id, user_id)
);
```

### 2. Comprehensive RLS Policy Framework

```sql
-- Enable RLS on all tables
ALTER TABLE tenants ENABLE ROW LEVEL SECURITY;
ALTER TABLE user_profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE presentations ENABLE ROW LEVEL SECURITY;
ALTER TABLE teams ENABLE ROW LEVEL SECURITY;
ALTER TABLE team_members ENABLE ROW LEVEL SECURITY;

-- Tenant isolation policies
CREATE POLICY "Tenant isolation - tenants"
ON tenants
USING (id = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')::UUID);

CREATE POLICY "Tenant isolation - user_profiles"
ON user_profiles
USING (tenant_id = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')::UUID);

CREATE POLICY "Tenant isolation - presentations"
ON presentations
USING (tenant_id = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')::UUID);

CREATE POLICY "Tenant isolation - teams"
ON teams
USING (tenant_id = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')::UUID);

-- Role-based access policies
CREATE POLICY "Admin full access - presentations"
ON presentations
USING (
  tenant_id = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')::UUID
  AND (
    (auth.jwt() ->> 'app_metadata' ->> 'role') = 'admin'
    OR created_by = auth.uid()
    OR team_id IN (
      SELECT team_id FROM team_members
      WHERE user_id = auth.uid()
      AND role IN ('owner', 'admin', 'member')
    )
  )
);

-- Team-based access policies
CREATE POLICY "Team member access - teams"
ON teams
USING (
  tenant_id = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')::UUID
  AND (
    created_by = auth.uid()
    OR id IN (
      SELECT team_id FROM team_members
      WHERE user_id = auth.uid()
    )
  )
);

CREATE POLICY "Team membership access"
ON team_members
USING (
  team_id IN (
    SELECT id FROM teams
    WHERE tenant_id = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')::UUID
  )
  AND (
    user_id = auth.uid()
    OR team_id IN (
      SELECT team_id FROM team_members
      WHERE user_id = auth.uid()
      AND role IN ('owner', 'admin')
    )
  )
);
```

### 3. Performance Optimization Indexes

```sql
-- Critical indexes for RLS performance
CREATE INDEX idx_user_profiles_tenant_id ON user_profiles(tenant_id);
CREATE INDEX idx_user_profiles_user_id ON user_profiles(id);
CREATE INDEX idx_presentations_tenant_id ON presentations(tenant_id);
CREATE INDEX idx_presentations_created_by ON presentations(created_by);
CREATE INDEX idx_presentations_team_id ON presentations(team_id);
CREATE INDEX idx_teams_tenant_id ON teams(tenant_id);
CREATE INDEX idx_team_members_user_id ON team_members(user_id);
CREATE INDEX idx_team_members_team_id ON team_members(team_id);
CREATE INDEX idx_team_members_lookup ON team_members(team_id, user_id, role);

-- Composite indexes for complex queries
CREATE INDEX idx_presentations_tenant_status ON presentations(tenant_id, status);
CREATE INDEX idx_presentations_tenant_created_by ON presentations(tenant_id, created_by);
CREATE INDEX idx_team_members_user_teams ON team_members(user_id, team_id) WHERE role IN ('owner', 'admin', 'member');
```

## Authentication Service Architecture

### 1. Custom Access Token Hook Implementation

```typescript
// Custom Access Token Hook for dynamic claims injection
export const customAccessTokenHook = async (event: AuthHookEvent) => {
  const { user_id, claims } = event;

  try {
    // Fetch user profile with tenant context
    const { data: profile } = await supabase
      .from('user_profiles')
      .select(`
        tenant_id,
        role,
        permissions,
        team_ids,
        tenants!inner(
          id,
          name,
          subdomain,
          status
        )
      `)
      .eq('id', user_id)
      .single();

    if (!profile || profile.tenants.status !== 'active') {
      throw new Error('Invalid tenant or user profile');
    }

    // Enhance JWT claims with tenant context
    const enhancedClaims = {
      ...claims,
      app_metadata: {
        ...claims.app_metadata,
        tenant_id: profile.tenant_id,
        tenant_name: profile.tenants.name,
        tenant_subdomain: profile.tenants.subdomain,
        role: profile.role,
        permissions: profile.permissions,
        team_ids: profile.team_ids,
      }
    };

    return { claims: enhancedClaims };
  } catch (error) {
    console.error('Custom access token hook error:', error);
    throw error;
  }
};
```

### 2. Authentication Middleware

```typescript
// Express middleware for API protection
export const authenticateRequest = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const authHeader = req.headers.authorization;
    if (!authHeader?.startsWith('Bearer ')) {
      return res.status(401).json({ error: 'Missing or invalid authorization header' });
    }

    const token = authHeader.replace('Bearer ', '');
    const { data: { user }, error } = await supabase.auth.getUser(token);

    if (error || !user) {
      return res.status(401).json({ error: 'Invalid token' });
    }

    // Decode JWT for tenant context
    const claims = jwt.decode(token) as CustomJWTClaims;
    const tenantId = claims.app_metadata?.tenant_id;

    if (!tenantId) {
      return res.status(403).json({ error: 'Missing tenant context' });
    }

    // Attach user and tenant context to request
    req.user = user;
    req.tenantId = tenantId;
    req.userRole = claims.app_metadata?.role;
    req.userPermissions = claims.app_metadata?.permissions || [];

    next();
  } catch (error) {
    console.error('Authentication middleware error:', error);
    res.status(500).json({ error: 'Authentication error' });
  }
};

// Role-based authorization middleware
export const requireRole = (allowedRoles: string[]) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const userRole = req.userRole;

    if (!userRole || !allowedRoles.includes(userRole)) {
      return res.status(403).json({ error: 'Insufficient permissions' });
    }

    next();
  };
};

// Permission-based authorization middleware
export const requirePermission = (requiredPermissions: string[]) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const userPermissions = req.userPermissions || [];

    const hasPermission = requiredPermissions.every(permission =>
      userPermissions.includes(permission)
    );

    if (!hasPermission) {
      return res.status(403).json({ error: 'Missing required permissions' });
    }

    next();
  };
};
```

## Storage Security Architecture

### 1. Tenant-Isolated Storage Structure

```sql
-- Storage bucket configuration
INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
VALUES (
  'presentations',
  'presentations',
  false,
  52428800, -- 50MB limit
  ARRAY['image/jpeg', 'image/png', 'image/gif', 'video/mp4', 'video/webm', 'application/pdf']
);

-- Storage RLS policies
CREATE POLICY "Tenant file isolation"
ON storage.objects
FOR ALL
USING (
  bucket_id = 'presentations'
  AND (storage.foldername(name))[1] = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')
);

CREATE POLICY "Authenticated users can upload"
ON storage.objects
FOR INSERT
WITH CHECK (
  bucket_id = 'presentations'
  AND (storage.foldername(name))[1] = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')
  AND auth.role() = 'authenticated'
);
```

### 2. File Organization Pattern

```typescript
// Storage path generation with tenant isolation
export class StorageManager {
  private getTenantPath(tenantId: string, type: 'slides' | 'recordings' | 'avatars'): string {
    return `${tenantId}/${type}`;
  }

  async uploadFile(
    tenantId: string,
    type: 'slides' | 'recordings' | 'avatars',
    fileName: string,
    file: File
  ): Promise<string> {
    const path = `${this.getTenantPath(tenantId, type)}/${fileName}`;

    const { data, error } = await supabase.storage
      .from('presentations')
      .upload(path, file, {
        cacheControl: '3600',
        upsert: false
      });

    if (error) throw error;
    return data.path;
  }

  async getSignedUrl(tenantId: string, filePath: string, expiresIn: number = 3600): Promise<string> {
    const { data, error } = await supabase.storage
      .from('presentations')
      .createSignedUrl(filePath, expiresIn);

    if (error) throw error;
    return data.signedUrl;
  }
}
```

## Security Event Logging Architecture

### 1. Audit Trail System

```sql
-- Security events table with tenant isolation
CREATE TABLE security_events (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES tenants(id),
  user_id UUID REFERENCES auth.users(id),
  event_type TEXT NOT NULL,
  event_category TEXT NOT NULL CHECK (event_category IN ('auth', 'access', 'data', 'admin')),
  resource_type TEXT,
  resource_id UUID,
  event_data JSONB DEFAULT '{}'::jsonb,
  ip_address INET,
  user_agent TEXT,
  session_id TEXT,
  risk_score INTEGER DEFAULT 0 CHECK (risk_score BETWEEN 0 AND 100),
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- RLS for security events
CREATE POLICY "Tenant security events access"
ON security_events
USING (tenant_id = (auth.jwt() ->> 'app_metadata' ->> 'tenant_id')::UUID);

-- Indexes for performance
CREATE INDEX idx_security_events_tenant_id ON security_events(tenant_id);
CREATE INDEX idx_security_events_user_id ON security_events(user_id);
CREATE INDEX idx_security_events_created_at ON security_events(created_at);
CREATE INDEX idx_security_events_event_type ON security_events(event_type);
CREATE INDEX idx_security_events_risk_score ON security_events(risk_score);
```

### 2. Security Event Logger Service

```typescript
export class SecurityLogger {
  async logEvent(params: {
    tenantId: string;
    userId?: string;
    eventType: string;
    eventCategory: 'auth' | 'access' | 'data' | 'admin';
    resourceType?: string;
    resourceId?: string;
    eventData?: Record<string, any>;
    ipAddress?: string;
    userAgent?: string;
    sessionId?: string;
    riskScore?: number;
  }) {
    const { data, error } = await supabase
      .from('security_events')
      .insert({
        tenant_id: params.tenantId,
        user_id: params.userId,
        event_type: params.eventType,
        event_category: params.eventCategory,
        resource_type: params.resourceType,
        resource_id: params.resourceId,
        event_data: params.eventData || {},
        ip_address: params.ipAddress,
        user_agent: params.userAgent,
        session_id: params.sessionId,
        risk_score: params.riskScore || 0
      });

    if (error) {
      console.error('Failed to log security event:', error);
    }

    return { data, error };
  }

  async logAuthEvent(tenantId: string, userId: string, eventType: 'login' | 'logout' | 'failed_login', metadata: any) {
    return this.logEvent({
      tenantId,
      userId,
      eventType,
      eventCategory: 'auth',
      eventData: metadata,
      riskScore: eventType === 'failed_login' ? 25 : 0
    });
  }

  async logDataAccess(tenantId: string, userId: string, resourceType: string, resourceId: string, action: string) {
    return this.logEvent({
      tenantId,
      userId,
      eventType: `${action}_${resourceType}`,
      eventCategory: 'access',
      resourceType,
      resourceId,
      riskScore: action === 'delete' ? 50 : 0
    });
  }
}
```

## Session Management Architecture

### 1. Advanced Session Configuration

```typescript
// Session management service
export class SessionManager {
  private readonly sessionTimeout = 24 * 60 * 60; // 24 hours
  private readonly refreshThreshold = 60 * 60; // 1 hour

  async createSession(user: User, tenantId: string): Promise<Session> {
    const session = await supabase.auth.getSession();

    // Store session metadata
    await this.storeSessionMetadata(session.data.session?.access_token, {
      tenantId,
      userId: user.id,
      createdAt: new Date(),
      lastActivity: new Date(),
      ipAddress: this.getClientIp(),
      userAgent: this.getUserAgent()
    });

    return session.data.session;
  }

  async refreshSession(): Promise<Session | null> {
    const { data, error } = await supabase.auth.refreshSession();

    if (error) {
      console.error('Session refresh failed:', error);
      return null;
    }

    // Update session metadata
    if (data.session) {
      await this.updateSessionActivity(data.session.access_token);
    }

    return data.session;
  }

  async validateSession(token: string): Promise<boolean> {
    try {
      const { data: { user }, error } = await supabase.auth.getUser(token);

      if (error || !user) {
        return false;
      }

      // Check if session needs refresh
      const claims = jwt.decode(token) as any;
      const expiresAt = claims.exp * 1000;
      const now = Date.now();

      if (expiresAt - now < this.refreshThreshold * 1000) {
        // Session needs refresh
        await this.refreshSession();
      }

      await this.updateSessionActivity(token);
      return true;
    } catch (error) {
      console.error('Session validation error:', error);
      return false;
    }
  }

  private async storeSessionMetadata(token: string, metadata: any) {
    // Implementation for storing session metadata in Redis or database
  }

  private async updateSessionActivity(token: string) {
    // Implementation for updating last activity timestamp
  }
}
```

## Deployment Architecture

### 1. Environment Configuration

```typescript
// Environment-specific configuration
export const authConfig = {
  development: {
    supabaseUrl: process.env.SUPABASE_URL_DEV,
    supabaseAnonKey: process.env.SUPABASE_ANON_KEY_DEV,
    jwtSecret: process.env.JWT_SECRET_DEV,
    sessionTimeout: 24 * 60 * 60, // 24 hours
    refreshThreshold: 60 * 60, // 1 hour
    corsOrigins: ['http://localhost:3000', 'http://localhost:5173'],
  },
  staging: {
    supabaseUrl: process.env.SUPABASE_URL_STAGING,
    supabaseAnonKey: process.env.SUPABASE_ANON_KEY_STAGING,
    jwtSecret: process.env.JWT_SECRET_STAGING,
    sessionTimeout: 12 * 60 * 60, // 12 hours
    refreshThreshold: 30 * 60, // 30 minutes
    corsOrigins: ['https://staging.slideshow.buzztrail.ai'],
  },
  production: {
    supabaseUrl: process.env.SUPABASE_URL_PROD,
    supabaseAnonKey: process.env.SUPABASE_ANON_KEY_PROD,
    jwtSecret: process.env.JWT_SECRET_PROD,
    sessionTimeout: 8 * 60 * 60, // 8 hours
    refreshThreshold: 15 * 60, // 15 minutes
    corsOrigins: ['https://slideshow.buzztrail.ai'],
  }
};
```

### 2. Health Check & Monitoring

```typescript
// Health check endpoints for authentication service
export class HealthCheckService {
  async checkAuthHealth(): Promise<{ status: string; details: any }> {
    try {
      // Check Supabase connection
      const { data, error } = await supabase.from('tenants').select('count').limit(1);

      if (error) {
        return {
          status: 'unhealthy',
          details: { database: 'connection_failed', error: error.message }
        };
      }

      // Check JWT validation
      const testToken = await this.generateTestToken();
      const isValid = await this.validateTestToken(testToken);

      return {
        status: 'healthy',
        details: {
          database: 'connected',
          jwt_validation: isValid ? 'working' : 'failed',
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      return {
        status: 'unhealthy',
        details: { error: error.message }
      };
    }
  }
}
```

## Conclusion

This authentication architecture provides a comprehensive, secure, and scalable foundation for the slide-show presentation platform. The multi-tenant design ensures complete data isolation while maintaining performance and usability. The security-first approach protects against common threats while providing flexibility for future enhancements and platform integrations.

The architecture supports the planned platform integrations (Daily.co, Zoom, Teams, WhatsApp) through its flexible OAuth system and can be extended as needed for additional providers and authentication methods.