# Facebook OAuth Integration Documentation

## Overview

This document provides complete setup instructions for Facebook OAuth integration in Magasinet KBH's authentication system using Better Auth.

## Current Status

✅ **Code integration**: Complete  
✅ **Client-side implementation**: Complete  
✅ **Account linking**: Configured  
⏳ **Facebook App setup**: Required (follow steps below)  
⏳ **Environment variables**: Need actual credentials

---

## Quick Setup Guide

### Step 1: Create Facebook App

1. Go to [Facebook Developer Portal](https://developers.facebook.com/)
2. Click **"My Apps"** → **"Create App"**
3. Select **"Consumer"** as the app type
4. Fill in your app details:
   - **App Name**: Magasinet KBH (or your preferred name)
   - **Contact Email**: Your email address
5. Click **"Create App"**

### Step 2: Configure Facebook Login

1. In your app dashboard, find **"Facebook Login"** product
2. Click **"Set Up"** or **"Settings"**
3. Navigate to **Facebook Login → Settings**
4. Add the following **Valid OAuth Redirect URIs**:
   - Development: `http://localhost:3000/api/auth/callback/facebook`
   - Production: `https://your-domain.com/api/auth/callback/facebook`
5. Click **"Save Changes"**

### Step 3: Get Your Credentials

1. Go to **Settings → Basic** in your Facebook App dashboard
2. Locate the following credentials:
   - **App ID**: This is your `FACEBOOK_CLIENT_ID`
   - **App Secret**: Click **"Show"** to reveal your `FACEBOOK_CLIENT_SECRET`
   
   ⚠️ **Important**: Keep your App Secret confidential! Never expose it in client-side code.

### Step 4: Update Environment Variables

Add your Facebook credentials to `.env.local` (development) or `.env` (production):

```env
# Facebook OAuth Configuration
FACEBOOK_CLIENT_ID=your_actual_facebook_app_id
FACEBOOK_CLIENT_SECRET=your_actual_facebook_app_secret
```

Replace `your_actual_facebook_app_id` and `your_actual_facebook_app_secret` with the values from Step 3.

### Step 5: Test the Integration

1. Restart your development server
2. Navigate to the sign-in page
3. Click the **"Facebook"** button
4. You should be redirected to Facebook for authentication
5. After authorizing, you'll be redirected back to your app

---

## Technical Implementation

### Architecture

- **Auth System**: Better Auth v1.3.7
- **Framework**: Next.js 15.5 with TypeScript
- **Database**: PostgreSQL with Drizzle ORM
- **OAuth Provider**: Facebook Login

### Server Configuration

**File**: `/src/lib/auth/auth.ts`

Facebook is configured in your Better Auth setup:

```typescript
socialProviders: {
  facebook: {
    clientId: config.socialAuth.facebook.clientId,
    clientSecret: config.socialAuth.facebook.clientSecret
  }
}
```

### Account Linking

**File**: `/src/lib/auth/auth.ts` (Line 52)

Facebook is already configured as a trusted provider for account linking:

```typescript
account: {
  accountLinking: {
    trustedProviders: ['google', 'github', 'demo-app', 'facebook']
  }
}
```

This allows users to link their Facebook account to an existing email/password account.

### Environment Configuration

**File**: `/src/config/env.ts`

Environment variables are validated using Zod:

```typescript
// Environment schema validation
const envSchema = z.object({
  FACEBOOK_CLIENT_ID: z.string().optional(),
  FACEBOOK_CLIENT_SECRET: z.string().optional(),
  // ... other variables
});

// Config object
socialAuth: {
  facebook: {
    clientId: env.FACEBOOK_CLIENT_ID || '',
    clientSecret: env.FACEBOOK_CLIENT_SECRET || ''
  }
}
```

### Client-Side Implementation

**Files**: 
- `/src/app/(main)/(auth)/_components/sign-in-form.tsx`
- `/src/app/(main)/payments/personal/_components/forms/sign-in.tsx`

Facebook login button implementation:

```typescript
<Button
  className='relative w-full bg-[#3B5998] font-medium text-white hover:bg-[#5875b2]'
  onClick={async () => {
    await signIn.social({
      provider: 'facebook',
      callbackURL: Routes.HOME
    });
  }}
>
  <Image
    src='/icons/facebook_icon_white.svg'
    alt='Facebook icon'
    width={20}
    height={20}
  />
  <span>Facebook</span>
</Button>
```

---

## Facebook Developer Portal Setup

### Step 1: Create a Facebook App

1. **Navigate to Facebook Developers Console**
   - Go to [https://developers.facebook.com/](https://developers.facebook.com/)
   - Log in with your Facebook account

2. **Create New App**
   - Click **"My Apps"** in the top right
   - Click **"Create App"**
   - Select app type: **"Consumer"** or **"None"** (recommended for login)
   - Click **"Next"**

3. **Configure App Details**
   - **Display Name**: `Magasinet KBH`
   - **App Contact Email**: `medlem@magasinetkbh.dk`
   - **Business Account**: (optional, but recommended)
   - Click **"Create App"**

### Step 2: Add Facebook Login Product

1. **Navigate to Dashboard**
   - From your app's dashboard, find **"Add a Product"** section

2. **Add Facebook Login**
   - Find **"Facebook Login"** in the product list
   - Click **"Set Up"**
   - Choose platform: **"Web"**

3. **Configure Web Platform**
   - **Site URL**: `https://magasinetkbh.vercel.app`
   - Click **"Save"** and **"Continue"**

### Step 3: Configure OAuth Settings

1. **Navigate to Facebook Login Settings**
   - In the left sidebar, expand **"Facebook Login"**
   - Click **"Settings"**

2. **Configure OAuth Redirect URIs**
   
   Add these URLs to **Valid OAuth Redirect URIs**:
   
   ```
   https://magasinetkbh.vercel.app/api/auth/callback/facebook
   ```
   
   For local development, also add:
   ```
   http://localhost:3000/api/auth/callback/facebook
   ```

3. **Additional Settings**
   - **Client OAuth Login**: ✅ Enable
   - **Web OAuth Login**: ✅ Enable
   - **Force Web OAuth Reauthentication**: ❌ Disable (optional)
   - **Use Strict Mode for Redirect URIs**: ✅ Enable (recommended)
   - **Enforce HTTPS**: ✅ Enable
   - **Embedded Browser OAuth Login**: ❌ Disable (not needed for web)
   - **Login from Devices**: ❌ Disable (not needed)

4. **Deauthorize Callback URL** (optional)
   ```
   https://magasinetkbh.vercel.app/api/auth/deauthorize/facebook
   ```

5. **Data Deletion Instructions URL** (required for review)
   ```
   https://magasinetkbh.vercel.app/data-deletion
   ```
   
   Note: You'll need to create a data deletion page or instructions for users.

6. Click **"Save Changes"**

### Step 4: Configure App Settings

1. **Navigate to Settings → Basic**
   - In the left sidebar, click **"Settings"** → **"Basic"**

2. **Configure App Domains**
   - **App Domains**: `magasinetkbh.vercel.app`
   - **Privacy Policy URL**: `https://magasinetkbh.vercel.app/privacy` (create if doesn't exist)
   - **Terms of Service URL**: `https://magasinetkbh.vercel.app/terms` (create if doesn't exist)

3. **Get Your Credentials**
   - **App ID**: Copy this value → This is your `FACEBOOK_CLIENT_ID`
   - **App Secret**: Click **"Show"**, copy the value → This is your `FACEBOOK_CLIENT_SECRET`
   
   ⚠️ **Security Warning**: Never commit these values to version control!

4. **Select App Category**
   - **Category**: "News" or "Magazines and Newspapers"

### Step 5: Configure Data Permissions

1. **Navigate to App Review → Permissions and Features**
   
2. **Default Permissions** (Already granted):
   - ✅ `email` - User's email address
   - ✅ `public_profile` - User's name, profile picture

3. **Additional Permissions** (If needed in future):
   - `user_friends` - For social features (requires review)
   - `user_birthday` - For age verification (requires review)
   - `user_location` - For local content (requires review)

   Note: Additional permissions require Facebook App Review. Start with basic permissions first.

### Step 6: App Modes

Facebook apps have two modes:

#### Development Mode (Current)
- **Available to**: App administrators, developers, and testers only
- **Limitations**: Up to 100 test users
- **Use for**: Testing integration before public launch

#### Live Mode (Production)
To make the app available to all users:

1. **Complete Prerequisites**:
   - ✅ Valid privacy policy URL
   - ✅ Valid terms of service URL
   - ✅ App icon (1024x1024px)
   - ✅ Business verification (if required)

2. **Switch to Live Mode**:
   - Navigate to **"Settings"** → **"Basic"**
   - Toggle **"App Mode"** from Development to Live
   - Confirm the switch

3. **App Review** (If using advanced permissions):
   - Navigate to **"App Review"**
   - Submit for review with use case explanations
   - Provide screencast demo of feature usage
   - Wait 1-5 business days for approval

---

## Adding Environment Variables

### For Local Development

1. Update your `.env.local` file:
   ```env
   FACEBOOK_CLIENT_ID=your_app_id_from_facebook
   FACEBOOK_CLIENT_SECRET=your_app_secret_from_facebook
   ```

2. Restart your development server:
   ```bash
   npm run dev
   ```

### For Vercel Production

1. **Navigate to Vercel Dashboard**
   - Go to [https://vercel.com](https://vercel.com)
   - Select your project: `magasinetkbh`

2. **Add Environment Variables**
   - Go to **"Settings"** → **"Environment Variables"**
   - Add the following:
   
   | Name | Value | Environments |
   |------|-------|--------------|
   | `FACEBOOK_CLIENT_ID` | Your Facebook App ID | Production, Preview |
   | `FACEBOOK_CLIENT_SECRET` | Your Facebook App Secret | Production, Preview |

3. **Redeploy**
   - Vercel will automatically redeploy
   - Or manually trigger: **"Deployments"** → **"Redeploy"**

---

## Testing

### Local Development Testing

1. **Start Development Server**
   ```bash
   npm run dev
   ```

2. **Add Test Users** (in Facebook Developer Portal)
   - Navigate to **"Roles"** → **"Test Users"**
   - Click **"Add Test Users"**
   - Create test accounts with email and password
   - Use these to test login flow

3. **Test Login Flow**
   - Navigate to `http://localhost:3000/sign-in`
   - Click the Facebook button
   - Log in with test user credentials
   - Verify redirect to home page
   - Check database for new user record

### Production Testing

1. **Before Going Live**
   - Test with real Facebook accounts (added as developers/testers)
   - Verify OAuth redirect URLs are correct
   - Check that user data is saved correctly
   - Test account linking (if user already exists with same email)

2. **After Going Live**
   - Test with personal Facebook account
   - Monitor error logs for failed authentications
   - Check user experience is smooth

### Common Test Scenarios

#### 1. New User Sign Up with Facebook
- User clicks "Facebook" on sign-in page
- Redirected to Facebook OAuth
- Grants permissions
- Redirected back to `http://localhost:3000` or `https://magasinetkbh.vercel.app`
- New user account created
- User is logged in

#### 2. Existing User Sign In with Facebook
- User previously registered with Facebook
- Clicks "Facebook" button
- Automatically logged in (no permission prompt if previously granted)
- Redirected to home page

#### 3. Account Linking (Same Email)
- User has existing account with `test@example.com`
- Tries to sign in with Facebook using same email
- Accounts are automatically linked (if Facebook is in `trustedProviders`)
- User can now sign in with either method

#### 4. Failed Authentication
- User clicks "Facebook" button
- Denies permissions on Facebook
- Redirected back with error
- Error toast displayed: "Authentication failed"
- User remains on sign-in page

---

## User Data Handling

### Data Collected from Facebook

When a user signs in with Facebook, Better Auth automatically collects:

1. **Email Address** (`email` permission)
   - Used as unique identifier
   - Stored in `users.email`

2. **Name** (`public_profile` permission)
   - User's full name
   - Stored in `users.name`

3. **Profile Picture** (`public_profile` permission)
   - URL to Facebook profile picture
   - Stored in `users.image`

4. **Facebook User ID**
   - Unique Facebook identifier
   - Stored in `accounts` table

### Database Schema

Better Auth creates these records automatically:

#### `users` table
```sql
INSERT INTO users (id, email, name, image, email_verified)
VALUES (
  'uuid-generated',
  'user@example.com',
  'User Name',
  'https://graph.facebook.com/12345/picture',
  true  -- Facebook accounts are pre-verified
);
```

#### `accounts` table
```sql
INSERT INTO accounts (id, user_id, account_id, provider)
VALUES (
  'uuid-generated',
  'user-uuid',
  'facebook-user-id',
  'facebook'
);
```

### Account Linking

If a user exists with the same email:

```typescript
// In auth.ts
account: {
  accountLinking: {
    trustedProviders: ['google', 'github', 'demo-app', 'facebook']
  }
}
```

Better Auth will:
1. Find existing user by email
2. Link Facebook account to existing user
3. Allow user to sign in with either method

---

## Security Considerations

### 1. App Secret Protection
- ✅ Never commit `FACEBOOK_CLIENT_SECRET` to Git
- ✅ Store in environment variables only
- ✅ Rotate secret if accidentally exposed
- ✅ Use different apps for development/production

### 2. Redirect URI Validation
- ✅ Only add legitimate redirect URIs in Facebook settings
- ✅ Use HTTPS in production
- ✅ Enable "Use Strict Mode for Redirect URIs"

### 3. Token Security
- ✅ Better Auth handles token storage securely
- ✅ Tokens stored in HTTP-only cookies
- ✅ Automatic token refresh

### 4. User Permissions
- ✅ Only request necessary permissions (`email`, `public_profile`)
- ✅ Request additional permissions only when needed
- ✅ Explain why permissions are needed

### 5. Data Privacy
- ✅ Have a privacy policy
- ✅ Explain what data is collected
- ✅ Provide data deletion mechanism
- ✅ Comply with GDPR (if applicable)

---

## Troubleshooting

### Common Issues

#### 1. "Invalid OAuth Redirect URI" Error

**Symptoms**: After clicking Facebook button, error appears about invalid redirect URI.

**Solutions**:
- Verify redirect URI in Facebook settings exactly matches: `https://magasinetkbh.vercel.app/api/auth/callback/facebook`
- Check for trailing slashes (should not have one)
- Ensure HTTPS is used (not HTTP) in production
- Wait a few minutes after saving changes in Facebook portal

#### 2. "App Not Set Up" Error

**Symptoms**: Facebook shows "App Not Set Up: This app is still in development mode"

**Solutions**:
- Add your account as a developer/tester in Facebook app
- Or switch app to Live mode (see Step 6 above)
- Verify app has Facebook Login product added

#### 3. User Created But Missing Email

**Symptoms**: User account created but email field is null

**Solutions**:
- Check that `email` permission is granted
- Verify user's Facebook account has a verified email
- Check Better Auth logs for permission errors

#### 4. Account Not Linking to Existing User

**Symptoms**: User with same email creates duplicate account

**Solutions**:
- Verify `facebook` is in `trustedProviders` array
- Check that existing user's email matches Facebook email exactly
- Ensure email is verified on both accounts

#### 5. Authentication Works Locally But Fails on Vercel

**Symptoms**: Facebook login works on localhost but not on production

**Solutions**:
- Verify environment variables are set in Vercel
- Check that production redirect URI is added in Facebook settings
- Ensure `BETTER_AUTH_URL` is set to `https://magasinetkbh.vercel.app`
- Check Vercel deployment logs for errors

#### 6. "Error Validating Access Token" Error

**Symptoms**: Authentication fails with token validation error

**Solutions**:
- Verify `FACEBOOK_CLIENT_SECRET` is correct in environment variables
- Check that app is not in development mode blocking your user
- Ensure Facebook app is active (not deleted/suspended)

---

## Data Deletion Callback (Required for App Review)

Facebook requires apps to provide a way for users to delete their data.

### Option 1: Create Data Deletion Page

**File**: `/src/app/(main)/data-deletion/page.tsx` (Create this)

```typescript
export default function DataDeletionPage() {
  return (
    <div className="max-w-2xl mx-auto p-8">
      <h1 className="text-3xl font-bold mb-4">Data Deletion Instructions</h1>
      
      <p className="mb-4">
        If you wish to delete your data associated with Magasinet KBH:
      </p>
      
      <ol className="list-decimal pl-6 space-y-2">
        <li>Go to your Facebook Account Settings</li>
        <li>Navigate to "Apps and Websites"</li>
        <li>Find "Magasinet KBH" in the list</li>
        <li>Click "Remove" to revoke access</li>
        <li>Your data will be automatically deleted within 90 days</li>
      </ol>
      
      <p className="mt-6">
        Alternatively, you can email us at{' '}
        <a href="mailto:medlem@magasinetkbh.dk" className="text-blue-600 underline">
          medlem@magasinetkbh.dk
        </a>{' '}
        to request immediate data deletion.
      </p>
    </div>
  );
}
```

### Option 2: Implement Deletion Callback Endpoint

**File**: `/src/app/api/auth/deauthorize/facebook/route.ts` (Create this)

```typescript
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

export async function POST(request: NextRequest) {
  const body = await request.json();
  const signedRequest = body.signed_request;
  
  if (!signedRequest) {
    return NextResponse.json({ error: 'Missing signed_request' }, { status: 400 });
  }

  // Parse Facebook signed request
  const [encodedSig, payload] = signedRequest.split('.');
  const data = JSON.parse(Buffer.from(payload, 'base64').toString('utf-8'));
  
  // Verify signature
  const expectedSig = crypto
    .createHmac('sha256', process.env.FACEBOOK_CLIENT_SECRET!)
    .update(payload)
    .digest('base64')
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
  
  if (encodedSig !== expectedSig) {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
  }

  const userId = data.user_id;
  
  // TODO: Delete user data from your database
  // await deleteUserByFacebookId(userId);
  
  // Return confirmation URL (required by Facebook)
  const confirmationCode = crypto.randomBytes(16).toString('hex');
  const statusUrl = `https://magasinetkbh.vercel.app/data-deletion-status?code=${confirmationCode}`;
  
  return NextResponse.json({
    url: statusUrl,
    confirmation_code: confirmationCode
  });
}
```

---

## Privacy & Compliance

### GDPR Compliance

If you have users in the EU, ensure:

1. **Consent**
   - Users must explicitly consent to data collection
   - Add checkbox: "I agree to the Privacy Policy and Terms of Service"

2. **Right to Access**
   - Users can view their data
   - Provide profile page with all stored information

3. **Right to Deletion**
   - Users can delete their account
   - Implement account deletion feature

4. **Data Minimization**
   - Only collect necessary data
   - Don't request unnecessary Facebook permissions

### Privacy Policy Requirements

Your privacy policy should include:

- What data is collected from Facebook (email, name, profile picture)
- How the data is used (authentication, advertising personalization)
- How long data is stored
- How users can delete their data
- Third-party data sharing (if any)

---

## Monitoring & Analytics

### Metrics to Track

1. **Authentication Success Rate**
   - Monitor failed vs. successful Facebook logins
   - Track errors by type

2. **User Adoption**
   - Percentage of users signing up via Facebook vs. email
   - Time to complete registration

3. **Account Linking**
   - How many users link Facebook to existing accounts
   - Error rate for linking

### Facebook Analytics

**Navigation**: Facebook Developer Portal → Analytics

Track:
- Daily/Monthly Active Users
- New users
- Retention rate
- Geographic distribution

---

## Migration & Rollback

### Deploying to Production

1. **Pre-deployment Checklist**
   - [ ] Facebook app created and configured
   - [ ] Environment variables set in Vercel
   - [ ] Redirect URIs added in Facebook settings
   - [ ] Privacy policy and terms of service pages created
   - [ ] Data deletion mechanism implemented
   - [ ] Tested with test users in development mode
   - [ ] Added 'facebook' to trustedProviders

2. **Gradual Rollout**
   - Keep app in Development mode initially
   - Add real users as testers
   - Monitor for issues
   - Switch to Live mode once stable

3. **Going Live**
   - Toggle app to Live mode in Facebook settings
   - Announce Facebook login feature to users
   - Monitor authentication logs closely

### Rollback Plan

If issues occur:

1. **Option 1: Disable Feature**
   - Remove Facebook button from sign-in page
   - Keep existing Facebook accounts working
   - Fix issues in development

2. **Option 2: Switch to Development Mode**
   - Toggle Facebook app back to Development
   - Only administrators can use it
   - Fix issues, then re-launch

---

## Advanced Features

### Future Enhancements

1. **Profile Picture Sync** (Priority: Medium)
   - Automatically update user avatar from Facebook
   - Refresh periodically

2. **Friends Integration** (Priority: Low)
   - Show which friends also use Magasinet KBH
   - Requires `user_friends` permission + App Review

3. **Share to Facebook** (Priority: Medium)
   - Allow users to share articles to Facebook
   - Requires Facebook Share Dialog

4. **Facebook Pixel** (Priority: Medium)
   - Track conversions for ads
   - Integrate Facebook Pixel for remarketing

---

## Support & Resources

### Official Documentation
- [Facebook Login for the Web](https://developers.facebook.com/docs/facebook-login/web)
- [Better Auth Facebook Provider](https://www.better-auth.com/facebook)
- [Facebook App Review](https://developers.facebook.com/docs/app-review)

### Common Links
- [Facebook Developer Console](https://developers.facebook.com/)
- [Facebook App Dashboard](https://developers.facebook.com/apps/)
- [Better Auth Documentation](https://www.better-auth.com/docs)

### Contact
For implementation questions or issues:
- Email: medlem@magasinetkbh.dk
- Facebook Support: [Developer Support](https://developers.facebook.com/support/)

---

## Checklist

### Setup Checklist

- [ ] Create Facebook app in Developer Portal
- [ ] Add Facebook Login product
- [ ] Configure OAuth redirect URIs
- [ ] Get App ID and App Secret
- [ ] Add environment variables to `.env.local`
- [ ] Add environment variables to Vercel
- [ ] Add 'facebook' to trustedProviders in auth.ts
- [ ] Create privacy policy page
- [ ] Create terms of service page
- [ ] Create data deletion page
- [ ] Test with test users in Development mode
- [ ] Switch app to Live mode
- [ ] Test with real Facebook accounts
- [ ] Monitor authentication logs

---

## Version History

| Version | Date | Changes |
|---------|------|---------|
| 1.0.0   | 2025-10-08 | Initial Facebook OAuth integration documentation |

---

**Last Updated**: October 8, 2025  
**Status**: ⚙️ Configuration required

**Next Steps**:
1. Create Facebook app in Developer Portal
2. Configure OAuth redirect URIs
3. Add credentials to Vercel environment variables
4. Add 'facebook' to trustedProviders in `/src/lib/auth/auth.ts`
5. Test authentication flow

