# 2FA Status Endpoint Documentation

## 📊 2FA Status Endpoint

### **GET /api/2fa/status**

**Authentication:** Required (Sanctum token)

**Headers:**
```
Authorization: Bearer {access_token}
Content-Type: application/json
```

**Request Body:** None

**Response:**
```json
{
  "success": true,
  "data": {
    "enabled": false,
    "confirmed": false,
    "setup_completed": false,
    "has_recovery_codes": false,
    "recovery_codes_count": 0
  }
}
```

### **Response Fields:**

| Field | Type | Description |
|-------|------|-------------|
| `enabled` | boolean | Whether 2FA is currently enabled |
| `confirmed` | boolean | Whether 2FA setup has been confirmed (same as enabled) |
| `setup_completed` | boolean | Whether the 2FA setup process is complete |
| `has_recovery_codes` | boolean | Whether the user has backup codes available |
| `recovery_codes_count` | integer | Number of remaining backup codes (0-8) |

### **Example Responses:**

#### **2FA Not Enabled:**
```json
{
  "success": true,
  "data": {
    "enabled": false,
    "confirmed": false,
    "setup_completed": false,
    "has_recovery_codes": false,
    "recovery_codes_count": 0
  }
}
```

#### **2FA Enabled with Full Backup Codes:**
```json
{
  "success": true,
  "data": {
    "enabled": true,
    "confirmed": true,
    "setup_completed": true,
    "has_recovery_codes": true,
    "recovery_codes_count": 8
  }
}
```

#### **2FA Enabled with Some Backup Codes Used:**
```json
{
  "success": true,
  "data": {
    "enabled": true,
    "confirmed": true,
    "setup_completed": true,
    "has_recovery_codes": true,
    "recovery_codes_count": 3
  }
}
```

## 🎯 Frontend Integration

### **JavaScript Example:**
```javascript
class TwoFactorManager {
  async checkTwoFactorStatus() {
    try {
      const token = localStorage.getItem('auth_token');
      
      if (!token) {
        throw new Error('No authentication token found');
      }

      const response = await fetch('/api/2fa/status', {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      const data = await response.json();

      if (response.ok && data.success) {
        return data.data;
      } else {
        throw new Error(data.message || 'Failed to check 2FA status');
      }
    } catch (error) {
      console.error('2FA status check failed:', error);
      return null;
    }
  }

  async updateTwoFactorUI() {
    const status = await this.checkTwoFactorStatus();
    
    if (status) {
      if (status.enabled) {
        this.showTwoFactorEnabled(status);
      } else {
        this.showTwoFactorDisabled();
      }
    }
  }

  showTwoFactorEnabled(status) {
    // Update UI to show 2FA is enabled
    document.getElementById('2fa-status').textContent = 'Enabled';
    document.getElementById('2fa-status').className = 'badge badge-success';
    
    // Show backup codes info
    if (status.has_recovery_codes) {
      document.getElementById('backup-codes-count').textContent = 
        `${status.recovery_codes_count} remaining`;
    }
    
    // Show disable button, hide setup button
    document.getElementById('setup-2fa-btn').style.display = 'none';
    document.getElementById('disable-2fa-btn').style.display = 'block';
  }

  showTwoFactorDisabled() {
    // Update UI to show 2FA is disabled
    document.getElementById('2fa-status').textContent = 'Disabled';
    document.getElementById('2fa-status').className = 'badge badge-secondary';
    
    // Hide backup codes info
    document.getElementById('backup-codes-info').style.display = 'none';
    
    // Show setup button, hide disable button
    document.getElementById('setup-2fa-btn').style.display = 'block';
    document.getElementById('disable-2fa-btn').style.display = 'none';
  }
}

// Usage
const twoFactorManager = new TwoFactorManager();

// Check status on page load
document.addEventListener('DOMContentLoaded', () => {
  twoFactorManager.updateTwoFactorUI();
});

// Check status after 2FA setup/disable
twoFactorManager.onTwoFactorChanged = () => {
  twoFactorManager.updateTwoFactorUI();
};
```

### **React Hook Example:**
```javascript
import { useState, useEffect } from 'react';

function useTwoFactorStatus() {
  const [status, setStatus] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const checkStatus = async () => {
    try {
      const token = localStorage.getItem('auth_token');
      
      if (!token) {
        throw new Error('No authentication token');
      }

      const response = await fetch('/api/2fa/status', {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      const data = await response.json();

      if (response.ok && data.success) {
        setStatus(data.data);
        setError(null);
      } else {
        throw new Error(data.message || 'Failed to check status');
      }
    } catch (err) {
      setError(err.message);
      setStatus(null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    checkStatus();
  }, []);

  return { status, loading, error, refetch: checkStatus };
}

// Usage in component
function TwoFactorStatus() {
  const { status, loading, error, refetch } = useTwoFactorStatus();

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!status) return <div>No status available</div>;

  return (
    <div className="2fa-status">
      <h3>Two-Factor Authentication</h3>
      
      <div className={`status-badge ${status.enabled ? 'enabled' : 'disabled'}`}>
        {status.enabled ? '✅ Enabled' : '❌ Disabled'}
      </div>

      {status.enabled && (
        <div className="backup-codes-info">
          <p>Backup Codes: {status.recovery_codes_count}/8 remaining</p>
          {status.recovery_codes_count < 3 && (
            <p className="warning">⚠️ Low on backup codes! Consider regenerating.</p>
          )}
        </div>
      )}

      <div className="actions">
        {!status.enabled && (
          <button onClick={() => {/* Navigate to setup */}}>
            Enable 2FA
          </button>
        )}
        
        {status.enabled && (
          <button onClick={() => {/* Navigate to disable */}}>
            Disable 2FA
          </button>
        )}
      </div>
    </div>
  );
}
```

### **React Native Example:**
```javascript
import React, { useState, useEffect } from 'react';
import { View, Text, Button, ActivityIndicator } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

function TwoFactorStatusScreen() {
  const [status, setStatus] = useState(null);
  const [loading, setLoading] = useState(true);

  const checkStatus = async () => {
    try {
      const token = await AsyncStorage.getItem('auth_token');
      
      if (!token) {
        throw new Error('No authentication token');
      }

      const response = await fetch('/api/2fa/status', {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      const data = await response.json();

      if (response.ok && data.success) {
        setStatus(data.data);
      } else {
        throw new Error(data.message || 'Failed to check status');
      }
    } catch (error) {
      console.error('Status check failed:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    checkStatus();
  }, []);

  if (loading) {
    return <ActivityIndicator size="large" />;
  }

  return (
    <View style={{ padding: 20 }}>
      <Text style={{ fontSize: 18, fontWeight: 'bold' }}>
        Two-Factor Authentication
      </Text>
      
      <Text style={{ 
        color: status?.enabled ? 'green' : 'red',
        fontSize: 16,
        marginVertical: 10
      }}>
        Status: {status?.enabled ? 'Enabled' : 'Disabled'}
      </Text>

      {status?.enabled && (
        <Text style={{ marginVertical: 5 }}>
          Backup Codes: {status.recovery_codes_count}/8 remaining
        </Text>
      )}

      <Button 
        title={status?.enabled ? 'Disable 2FA' : 'Enable 2FA'}
        onPress={() => {
          // Navigate to appropriate screen
        }}
      />
    </View>
  );
}
```

## 🎯 Use Cases

### **1. Dashboard Status Display**
Show user's current 2FA status in their security settings:

```javascript
// On dashboard load
const status = await twoFactorManager.checkTwoFactorStatus();
updateSecuritySettingsUI(status);
```

### **2. Conditional Login Flow**
Check if user needs 2FA during login:

```javascript
// After successful password authentication
if (loginResponse.requires_2fa) {
  // Show 2FA input
} else {
  // Direct login success
}
```

### **3. Setup/Disable Flow**
Determine which action to show:

```javascript
if (status.enabled) {
  showDisableButton();
  showBackupCodesInfo();
} else {
  showSetupButton();
}
```

### **4. Backup Code Management**
Monitor backup code usage:

```javascript
if (status.recovery_codes_count < 3) {
  showWarning('Low backup codes! Consider regenerating.');
}
```

## 🔒 Security Considerations

- **Authentication Required** - Only authenticated users can check status
- **No Sensitive Data** - Status endpoint doesn't expose secrets or codes
- **Rate Limiting** - Consider rate limiting to prevent abuse
- **Cache Appropriately** - Status can be cached for short periods

Your frontend can now easily check and display 2FA status! 🎉
