# Initiate Static Session Coming With CURL Documentation

**File**: `/controllers/initiateStaticSessionCommingWithCurl.php`  
**Purpose**: CURL session management utility for cross-system authentication and session sharing  
**Last Updated**: December 20, 2024  
**Total Functions**: 1 main operation  
**Lines of Code**: ~32

---

## 📋 Overview

The Initiate Static Session Coming With CURL Controller is a lightweight utility designed to facilitate session sharing between different systems or applications via CURL requests. It handles:
- Session initialization from external CURL requests
- JSON-based session data transfer
- Cross-system authentication bridging
- Session variable population from external sources
- Secure session data handling for system integration

### Primary Functions
- [x] Receive session data via CURL POST requests
- [x] Parse JSON session data and populate $_SESSION variables
- [x] Handle cross-system authentication bridging
- [x] Support system-to-system communication
- [x] Maintain session security across different applications
- [x] Enable single sign-on (SSO) functionality

### Related Controllers
- [authentication.php](#) - Local authentication handling
- [login.php](#) - User login processing
- [api_web.php](api_web.md) - Web API endpoints
- External ERP systems - Cross-system integration

---

## 🗄️ Database Tables

This controller primarily works with session data and does not directly interact with database tables. However, it may indirectly relate to:

### Session-Related Tables (Indirect)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | User authentication data | userid, username, password, usergroupid |
| **usergroup** | User permission groups | usergroupid, groupname, permissions |
| **branch** | Branch/location data | branchId, branchName |
| **programsettings** | System configuration | settingkey, settingvalue |

---

## 🔑 Key Functions

### 1. **Main CURL Session Handler** - Session Data Processing
**Location**: Line 10  
**Purpose**: Process incoming CURL requests containing session data and populate local session variables

**Function Logic**:
```php
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    foreach (json_decode($_POST['sessionlist']) as $key => $value) {
        $_SESSION[$key] = $value;
    }
}
```

**Process Flow**:
1. **Validate CURL Request**:
   - Check for `curlpost` parameter set to 1
   - Verify this is a legitimate CURL-initiated request

2. **Parse Session Data**:
   - Decode JSON string from `sessionlist` POST parameter
   - Extract key-value pairs for session variables

3. **Populate Session**:
   - Iterate through decoded session data
   - Set each key-value pair in `$_SESSION` superglobal
   - Maintain session state for subsequent requests

**Expected POST Data Structure**:
```php
$_POST = [
    'curlpost' => 1,
    'sessionlist' => '{
        "userid": "123",
        "username": "john_doe", 
        "usergroupid": "2",
        "branchId": "1",
        "saveid": "5",
        "dbname": "erp_database",
        "erp_lang": "ar"
    }'
];
```

---

### 2. **Commented Database Selection Logic** - Legacy ERP Integration
**Location**: Lines 15-30 (commented)  
**Purpose**: Database switching functionality for multi-tenant ERP systems (currently disabled)

**Legacy Logic (Commented)**:
```php
// $erpDB = $_POST["erpDB"];
// if (isset($erpDB) && !empty($erpDB)) {
//     $_SESSION['dbname'] = $erpDB;
//     
//     $dbhostrb = ConnectionProperty::getHost();
//     $dbuserrb = ConnectionProperty::getUser();
//     $dbpasswordrb = ConnectionProperty::getPassword();
//     $dbnamerb = ConnectionProperty::getDatabase();
//
//     R::addDatabase('erpDBOfPOST', 'mysql:host=' . $dbhostrb . ';dbname=' . $dbnamerb . '', $dbuserrb, $dbpasswordrb);
//     R::selectDatabase('erpDBOfPOST');
// }
```

**Purpose of Legacy Code**:
- Support for multi-database ERP deployments
- Dynamic database switching based on CURL request
- RedBean ORM database connection management
- Tenant-specific database selection

---

## 🔄 Workflows

### Workflow 1: CURL Session Transfer Process
```
┌─────────────────────────────────────────────────────────────┐
│        START: External System Session Transfer             │
│   External system needs to authenticate user in ERP        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. External System Preparation                            │
│     - User authenticated in external system                │
│     - Collect user session data (userid, permissions, etc.) │
│     - Build JSON session data string                       │
│     - Prepare CURL request to ERP system                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. CURL Request to ERP System                             │
│     POST Request to: initiateStaticSessionCommingWithCurl.php │
│     Headers:                                                │
│       - Content-Type: application/x-www-form-urlencoded    │
│       - User-Agent: {external_system_identifier}           │
│     Body:                                                   │
│       - curlpost=1                                         │
│       - sessionlist={encoded_json_session_data}           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. ERP System Session Initialization                      │
│     A. Request Validation:                                  │
│       - Check if 'curlpost' parameter = 1                  │
│       - Verify request came from authorized source         │
│                                                             │
│     B. Session Management:                                  │
│       - Start session if not already started               │
│       - Clear any existing session data (optional)         │
│                                                             │
│     C. Data Processing:                                     │
│       - Decode JSON from 'sessionlist' parameter           │
│       - Validate session data structure                    │
│       - Check for required session variables               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Session Variable Population                            │
│     FOR EACH key-value pair in decoded session data:       │
│       │                                                     │
│       ├─→ Validate key name (security check)               │
│       ├─→ Sanitize value data                              │
│       ├─→ Set $_SESSION[$key] = $value                     │
│       └─→ Log session variable for audit                   │
│                                                             │
│     Common session variables set:                          │
│       - $_SESSION['userid'] = user ID                      │
│       - $_SESSION['username'] = username                   │
│       - $_SESSION['usergroupid'] = permission group        │
│       - $_SESSION['branchId'] = branch/location            │
│       - $_SESSION['saveid'] = default cash register        │
│       - $_SESSION['erp_lang'] = language preference        │
│       - $_SESSION['dbname'] = database name (if multi-tenant) │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Session Activation & Response                          │
│     - Session is now active for user                       │
│     - User can access ERP system without additional login  │
│     - Return success response to external system           │
│     - Log successful session transfer                      │
│                                                             │
│  SUBSEQUENT REQUESTS:                                       │
│     - User accesses ERP pages normally                     │
│     - Session variables available via $_SESSION            │
│     - Authentication.php recognizes valid session          │
│     - User has full access based on transferred permissions │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Integration with External Authentication Systems
```
┌─────────────────────────────────────────────────────────────┐
│            START: Multi-System SSO Integration             │
│   User logs into main system, needs ERP access             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. User Authentication in Primary System                  │
│     - User logs into main application                      │
│     - Primary system validates credentials                 │
│     - User session established in primary system           │
│     - Primary system has user permissions and profile      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. ERP Access Request                                      │
│     - User clicks link to access ERP system               │
│     - Primary system detects ERP access requirement        │
│     - Primary system needs to transfer authentication      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Session Data Preparation                               │
│     A. Map User Data:                                      │
│       - Map primary system user ID to ERP user ID          │
│       - Map permissions to ERP permission groups           │
│       - Map organizational data to ERP branch/cost center  │
│                                                             │
│     B. Build Session Array:                                │
│       $sessionData = [                                     │
│         'userid' => $erpUserId,                            │
│         'username' => $user->username,                     │
│         'usergroupid' => $mappedGroupId,                   │
│         'branchId' => $user->defaultBranch,                │
│         'saveid' => $user->defaultCashRegister,            │
│         'erp_lang' => $user->language                      │
│       ];                                                    │
│                                                             │
│     C. Encode as JSON:                                     │
│       $sessionJson = json_encode($sessionData);            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Execute CURL Session Transfer                          │
│     $curl = curl_init();                                   │
│     curl_setopt($curl, CURLOPT_URL, $erpSessionUrl);       │
│     curl_setopt($curl, CURLOPT_POST, true);                │
│     curl_setopt($curl, CURLOPT_POSTFIELDS, [               │
│         'curlpost' => 1,                                    │
│         'sessionlist' => $sessionJson                      │
│     ]);                                                     │
│     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);      │
│     $response = curl_exec($curl);                          │
│     curl_close($curl);                                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Redirect User to ERP System                           │
│     - Session transfer completed successfully              │
│     - Redirect user's browser to ERP system                │
│     - User accesses ERP with pre-established session       │
│     - No additional login required                         │
└─────────────────────────────────────────────────────────────┘
```

---

## 🔒 Security Considerations

### Current Security Limitations

**1. No Request Authentication**
```php
// CURRENT (INSECURE)
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    // Any system can send this request
}

// RECOMMENDED
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1 && 
    validateRequestSignature($_POST, $secretKey)) {
    // Only authenticated systems can transfer sessions
}
```

**2. No IP Whitelisting**
```php
// RECOMMENDED
$allowedIPs = ['192.168.1.100', '10.0.1.50'];
$clientIP = $_SERVER['REMOTE_ADDR'];
if (!in_array($clientIP, $allowedIPs)) {
    http_response_code(403);
    exit('Unauthorized IP address');
}
```

**3. No Session Data Validation**
```php
// CURRENT (VULNERABLE)
foreach (json_decode($_POST['sessionlist']) as $key => $value) {
    $_SESSION[$key] = $value; // No validation
}

// RECOMMENDED  
$allowedKeys = ['userid', 'username', 'usergroupid', 'branchId'];
foreach (json_decode($_POST['sessionlist']) as $key => $value) {
    if (in_array($key, $allowedKeys) && is_valid_value($value)) {
        $_SESSION[$key] = sanitize($value);
    }
}
```

### Recommended Security Enhancements

**1. Request Signing**
```php
function validateRequestSignature($postData, $secretKey) {
    $expectedSignature = hash_hmac('sha256', $postData['sessionlist'], $secretKey);
    return hash_equals($expectedSignature, $postData['signature']);
}
```

**2. Timestamp Validation**
```php
function validateRequestTimestamp($timestamp, $tolerance = 300) {
    $currentTime = time();
    return abs($currentTime - $timestamp) <= $tolerance;
}
```

**3. Nonce Protection**
```php
function validateNonce($nonce) {
    // Check if nonce was already used (prevent replay attacks)
    return !isNonceUsed($nonce);
}
```

---

## 🌐 Integration Scenarios

### Scenario 1: CRM to ERP Integration
```php
// CRM System (Sender)
$sessionData = [
    'userid' => $crmUser->erp_user_id,
    'username' => $crmUser->username,
    'usergroupid' => mapCRMRoleToERPGroup($crmUser->role),
    'branchId' => $crmUser->default_branch,
    'timestamp' => time(),
    'nonce' => generateNonce()
];

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://erp.company.com/controllers/initiateStaticSessionCommingWithCurl.php');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, [
    'curlpost' => 1,
    'sessionlist' => json_encode($sessionData),
    'signature' => hash_hmac('sha256', json_encode($sessionData), $sharedSecret)
]);
```

### Scenario 2: Mobile App Authentication
```php
// Mobile App Backend
function authenticateERPAccess($mobileUserId, $authToken) {
    // Validate mobile user
    $user = validateMobileUser($mobileUserId, $authToken);
    
    if ($user) {
        $sessionData = [
            'userid' => $user->erp_user_id,
            'username' => $user->username,
            'usergroupid' => 3, // Mobile user group
            'branchId' => $user->branch_id,
            'saveid' => $user->default_save_id,
            'erp_lang' => $user->language
        ];
        
        return transferSessionToERP($sessionData);
    }
    
    return false;
}
```

### Scenario 3: Portal Integration
```php
// Customer Portal
function enableERPAccess($customerId) {
    $customer = getCustomer($customerId);
    
    $sessionData = [
        'userid' => $customer->erp_user_id,
        'username' => 'customer_' . $customer->id,
        'usergroupid' => 5, // Customer access group
        'branchId' => $customer->service_branch,
        'clientid' => $customer->id, // Additional context
        'access_level' => 'readonly'
    ];
    
    return initializeERPSession($sessionData);
}
```

---

## 📊 Performance Considerations

### CURL Request Optimization
```php
// Optimize CURL settings for performance
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => $erpSessionUrl,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $postData,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10, // Prevent hanging
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_USERAGENT => 'ERP-Integration/1.0'
]);
```

### Session Management
- Keep session data minimal to reduce transfer size
- Use efficient JSON encoding/decoding
- Implement session cleanup for expired transfers

---

## 🐛 Common Issues & Troubleshooting

### 1. **Session Data Not Transferred**
**Issue**: $_SESSION variables are empty after CURL request  
**Cause**: JSON decoding failure or missing curlpost parameter

**Debug**:
```php
// Add debugging
error_log("CURL post received: " . print_r($_POST, true));
$sessionData = json_decode($_POST['sessionlist'], true);
error_log("Decoded session data: " . print_r($sessionData, true));
if (json_last_error() !== JSON_ERROR_NONE) {
    error_log("JSON decode error: " . json_last_error_msg());
}
```

### 2. **Authentication Loops**
**Issue**: User gets redirected back to login repeatedly  
**Cause**: Session not properly established or authentication.php not recognizing session

**Debug**:
```php
// Check session variables
foreach ($_SESSION as $key => $value) {
    error_log("Session $key: $value");
}

// Verify session_start() was called
if (session_status() !== PHP_SESSION_ACTIVE) {
    error_log("Session not started");
}
```

### 3. **Permission Issues**
**Issue**: User has wrong permissions in ERP system  
**Cause**: Incorrect usergroupid mapping

**Debug**:
```php
// Validate permission mapping
$userGroup = getUserGroupById($_SESSION['usergroupid']);
error_log("User group permissions: " . print_r($userGroup, true));
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Session Transfer
```
1. Prepare valid session data in JSON format
2. Send CURL request with curlpost=1 and sessionlist
3. Verify $_SESSION variables are populated correctly
4. Test subsequent ERP page access
5. Confirm user permissions are applied correctly
```

### Test Case 2: Invalid Data Handling
```
1. Send malformed JSON in sessionlist
2. Send request without curlpost parameter
3. Send empty sessionlist
4. Verify system handles errors gracefully
5. Check no security vulnerabilities exposed
```

### Test Case 3: Integration Flow
```
1. Set up external system with user authentication
2. Implement session mapping logic
3. Execute full integration workflow
4. Verify seamless user experience
5. Test session timeout and cleanup
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [authentication.php](#) - Local authentication handling
- [api_web.md](api_web.md) - Web API endpoints
- [Single Sign-On Integration Guide](#) - Complete SSO implementation

---

**Documented By**: AI Assistant  
**Review Status**: ⚠️ Security review required  
**Next Review**: Implement security enhancements before production use