# Salesforce OAuth Integration Setup Guide

This guide will help you configure Salesforce OAuth authentication for your Centralized Reporting System application.

## Table of Contents
1. [Prerequisites](#prerequisites)
2. [Create a Salesforce Connected App](#create-a-salesforce-connected-app)
3. [Configure OAuth Settings](#configure-oauth-settings)
4. [Update Application Configuration](#update-application-configuration)
5. [Test the Integration](#test-the-integration)
6. [Troubleshooting](#troubleshooting)

---

## Prerequisites

Before you begin, ensure you have:
- A Salesforce account (Production or Sandbox)
- Administrator access to Salesforce
- Your backend API ready to handle OAuth token exchange
- React Native app with WebView capability

---

## Create a Salesforce Connected App

### Step 1: Access Setup
1. Log in to your Salesforce account
2. Click the **gear icon** (⚙️) in the top right corner
3. Select **Setup** from the dropdown menu

### Step 2: Navigate to App Manager
1. In the Quick Find box, type **"App Manager"**
2. Click **App Manager** under Platform Tools > Apps
3. Click **New Connected App** button

### Step 3: Basic Information
Fill in the following required fields:
- **Connected App Name**: `Centralized Reporting System` (or your preferred name)
- **API Name**: `Centralized_Reporting_System` (auto-populated)
- **Contact Email**: Your email address

### Step 4: API (Enable OAuth Settings)
1. Check the box **"Enable OAuth Settings"**
2. **Callback URL**: Enter your redirect URI
   ```
   centralizedreportingsystem://oauth/salesforce/callback
   ```
   > Note: You can add multiple callback URLs for different environments (development, staging, production)

3. **Selected OAuth Scopes**: Select the following scopes and move them to "Selected OAuth Scopes":
   - Access the identity URL service (id, profile, email, address, phone)
   - Access unique user identifiers (openid)
   - Perform requests at any time (refresh_token, offline_access)
   - Manage user data via APIs (api)
   - Full access to all data (full) - Optional, use with caution

4. **Additional OAuth Settings**:
   - ✅ **Enable for Device Flow**: Check this if you want to support device authentication
   - ✅ **Require Secret for Web Server Flow**: Recommended for security
   - ✅ **Require Secret for Refresh Token Flow**: Recommended for security
   - ✅ **Enable Authorization Code and Credentials Flow**: Check this

5. Click **Save** button

### Step 5: Wait for Salesforce Processing
After saving, Salesforce will process your app (usually 2-10 minutes).

### Step 6: Retrieve OAuth Credentials
1. Once processing is complete, navigate back to **App Manager**
2. Find your Connected App and click the dropdown arrow (▼)
3. Select **View**
4. In the "API (Enable OAuth Settings)" section, you'll see:
   - **Consumer Key** (Client ID)
   - **Consumer Secret** (Client Secret) - Click "Click to reveal"

> ⚠️ **Important**: Keep these credentials secure! Never commit them to public repositories.

---

## Configure OAuth Settings

### Environment-Specific Endpoints

#### Production
```
Auth Base URL: https://login.salesforce.com
```

#### Sandbox
```
Auth Base URL: https://test.salesforce.com
```

### OAuth Scopes Explained

| Scope | Description |
|-------|-------------|
| `api` | Access to all standard Salesforce REST APIs |
| `refresh_token` | Ability to refresh the access token |
| `offline_access` | Perform requests even when the user is offline |
| `id` | Access to the unique identifier for the user |
| `profile` | Access to user's profile information |
| `email` | Access to user's email address |
| `address` | Access to user's address |
| `phone` | Access to user's phone number |
| `openid` | OpenID Connect authentication |

---

## Update Application Configuration

### Step 1: Update SalesforceAuth.tsx

Open `src/modules/integrations/screens/SalesforceAuth.tsx` and update the following:

```typescript
const SALESFORCE_CONFIG = {
  // Replace with your Consumer Key (Client ID) from Salesforce
  CLIENT_ID: '3MVG9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  
  // This must match exactly what you configured in Salesforce Connected App
  REDIRECT_URI: 'centralizedreportingsystem://oauth/salesforce/callback',
  
  // Use login.salesforce.com for production
  // Use test.salesforce.com for sandbox
  AUTH_BASE_URL: 'https://login.salesforce.com',
  
  RESPONSE_TYPE: 'code',
  DISPLAY: 'touch', // Optimized for mobile
};
```

### Step 2: Configure Deep Linking (Android)

#### Android - Update AndroidManifest.xml
Add the intent filter to handle the OAuth callback:

```xml
<!-- android/app/src/main/AndroidManifest.xml -->
<activity
  android:name=".MainActivity"
  android:label="@string/app_name"
  android:launchMode="singleTask">
  
  <!-- Existing intent filters -->
  <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
  
  <!-- Salesforce OAuth Callback -->
  <intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data
      android:scheme="centralizedreportingsystem"
      android:host="oauth"
      android:pathPrefix="/salesforce/callback" />
  </intent-filter>
</activity>
```

### Step 3: Configure Deep Linking (iOS)

#### iOS - Update Info.plist
Add URL types for the OAuth callback:

```xml
<!-- ios/CentralizedReportingSystem/Info.plist -->
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>centralizedreportingsystem</string>
    </array>
    <key>CFBundleURLName</key>
    <string>com.yourcompany.centralizedreportingsystem</string>
  </dict>
</array>
```

### Step 4: Backend Token Exchange Endpoint

Your backend should have an endpoint to exchange the authorization code for an access token:

```typescript
// Example backend endpoint
POST /api/v1/integrations/manage-token

Request Body:
{
  "authorization_code": "aPrxXXXXXXXXXXXXXXXXXXXXXXXXX",
  "id": "user-uuid",
  "service_name": "salesforce",
  "access_token": "user-session-token"
}
```

The backend should:
1. Receive the authorization code
2. Exchange it with Salesforce for an access token
3. Store the tokens securely (encrypted)
4. Return success/failure response

#### Salesforce Token Exchange Request

Your backend should make this request to Salesforce:

```http
POST https://login.salesforce.com/services/oauth2/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code={AUTHORIZATION_CODE}
&client_id={YOUR_CLIENT_ID}
&client_secret={YOUR_CLIENT_SECRET}
&redirect_uri={YOUR_REDIRECT_URI}
```

#### Expected Salesforce Response

```json
{
  "access_token": "00D...ABC",
  "refresh_token": "5Aep...XYZ",
  "signature": "signature-value",
  "scope": "api refresh_token offline_access id profile email",
  "id_token": "eyJ...",
  "instance_url": "https://yourinstance.salesforce.com",
  "id": "https://login.salesforce.com/id/00D.../005...",
  "token_type": "Bearer",
  "issued_at": "1699999999999"
}
```

---

## Test the Integration

### Testing Steps

1. **Launch the App**
   - Open your React Native application
   - Navigate to **Integrations** > **CRM & Sales Integration**

2. **Select Salesforce**
   - Tap on the **Salesforce** option
   - The Salesforce authentication WebView should open

3. **Authenticate**
   - Enter your Salesforce username and password
   - If using Two-Factor Authentication, complete the verification
   - Review and approve the OAuth permissions

4. **Verify Success**
   - The app should capture the authorization code
   - Backend should exchange it for tokens
   - You should see a success message
   - The auth modal should close automatically

5. **Check Data Sync** (if implemented)
   - Navigate to the Salesforce dashboard
   - Verify that data is being synced properly

### Testing with Different Salesforce Orgs

To test with different Salesforce organizations:
1. Tap the **Re-auth** button next to Salesforce
2. Confirm the re-authentication
3. Log in with a different Salesforce account

---

## Troubleshooting

### Common Issues and Solutions

#### 1. **"redirect_uri_mismatch" Error**

**Problem**: The redirect URI doesn't match what's configured in Salesforce.

**Solution**:
- Ensure the redirect URI in `SalesforceAuth.tsx` exactly matches what's in the Salesforce Connected App
- Check for trailing slashes, capitalization, and special characters
- Both values must be identical: `centralizedreportingsystem://oauth/salesforce/callback`

---

#### 2. **"invalid_client_id" Error**

**Problem**: The Client ID is incorrect or the Connected App is not yet active.

**Solution**:
- Wait 2-10 minutes after creating the Connected App for Salesforce to process it
- Double-check the Consumer Key (Client ID) from Salesforce matches your config
- Ensure there are no extra spaces or characters

---

#### 3. **WebView Doesn't Load**

**Problem**: The Salesforce login page doesn't appear.

**Solution**:
- Check your internet connection
- Verify the `AUTH_BASE_URL` is correct (login.salesforce.com or test.salesforce.com)
- Check console logs for error messages
- Ensure WebView has internet permission (Android)

---

#### 4. **App Doesn't Capture the Code**

**Problem**: After authentication, the app doesn't proceed.

**Solution**:
- Verify deep linking is configured correctly for both iOS and Android
- Check that the redirect URI scheme matches your app's URL scheme
- Test the deep link manually using ADB (Android) or xcrun (iOS)
- Check console logs for navigation state changes

---

#### 5. **"access_denied" Error**

**Problem**: User denied the OAuth permissions.

**Solution**:
- User must approve all requested permissions
- If permissions are too broad, consider reducing the requested scopes
- Check if the Connected App is enabled for the user's profile

---

#### 6. **Token Exchange Fails**

**Problem**: Backend returns an error when exchanging the authorization code.

**Solution**:
- Verify backend endpoint is working: `/api/v1/integrations/manage-token`
- Check that the backend has the correct Consumer Secret
- Authorization codes expire after 15 minutes - ensure timely exchange
- Check backend logs for detailed error messages
- Verify the authorization code is being sent correctly

---

#### 7. **Sandbox vs Production Confusion**

**Problem**: Using the wrong Salesforce environment.

**Solution**:
- **Production**: Use `https://login.salesforce.com`
- **Sandbox**: Use `https://test.salesforce.com`
- Create separate Connected Apps for each environment
- Update the config based on your current environment

---

### Debug Logging

Enable comprehensive logging to troubleshoot issues:

```typescript
// In SalesforceAuth.tsx, check console logs for:
console.log('[SalesforceAuth] Authorization code received:', authCode);
console.log('[SalesforceAuth] Response from manageToken:', response);
console.log('[SalesforceAuth] nav change url:', url, 'loading:', loading);
```

---

## Security Best Practices

1. **Never Store Credentials in Code**
   - Use environment variables or secure config management
   - Never commit `.env` files with credentials to version control

2. **Use HTTPS Only**
   - Always use `https://` for Salesforce endpoints
   - Never use `http://` in production

3. **Implement Token Refresh**
   - Store refresh tokens securely
   - Implement automatic token refresh on expiration
   - Handle refresh token failures gracefully

4. **Encrypt Stored Tokens**
   - Use encryption for tokens stored on device
   - Use secure storage mechanisms (Keychain, KeyStore)

5. **Validate State Parameter**
   - Include CSRF protection using state parameter
   - Verify state on callback to prevent CSRF attacks

6. **Limit OAuth Scopes**
   - Request only the minimum scopes needed
   - Avoid using `full` scope unless absolutely necessary

7. **Monitor Token Usage**
   - Log token usage and refresh patterns
   - Set up alerts for unusual authentication patterns

---

## Additional Resources

### Salesforce Documentation
- [Connected Apps Overview](https://help.salesforce.com/s/articleView?id=sf.connected_app_overview.htm)
- [OAuth 2.0 Authorization Flow](https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_flow.htm)
- [OAuth Scopes](https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_tokens_scopes.htm)

### React Native Resources
- [React Native WebView](https://github.com/react-native-webview/react-native-webview)
- [Deep Linking in React Native](https://reactnative.dev/docs/linking)

---

## Support

If you encounter issues not covered in this guide:

1. Check Salesforce Setup Audit Trail for any configuration errors
2. Review React Native console logs
3. Check backend API logs for token exchange errors
4. Verify network requests in the debugger
5. Test with both Production and Sandbox environments

---

## Changelog

### Version 1.0.0
- Initial Salesforce OAuth integration
- Support for mobile OAuth flow
- Backend token exchange implementation
- Data sync scheduling

---

## License

This integration follows your application's license terms.

---

**Last Updated**: October 2025
**Maintained By**: Your Development Team

