InitiateStaticSessionCommingWithCurl Documentation
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
- โ Receive session data via CURL POST requests
- โ Parse JSON session data and populate $_SESSION variables
- โ Handle cross-system authentication bridging
- โ Support system-to-system communication
- โ Maintain session security across different applications
- โ Enable single sign-on (SSO) functionality
Related Controllers
- โข authentication.php - Local authentication handling
- โข login.php - User login processing
- โข api_web.php - 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:
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:
$_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):
// $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
---
Workflow 2: Integration with External Authentication Systems
---
๐ Security Considerations
Current Security Limitations
1. No Request Authentication
// 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
// 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
// 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
function validateRequestSignature($postData, $secretKey) {
$expectedSignature = hash_hmac('sha256', $postData['sessionlist'], $secretKey);
return hash_equals($expectedSignature, $postData['signature']);
}
2. Timestamp Validation
function validateRequestTimestamp($timestamp, $tolerance = 300) {
$currentTime = time();
return abs($currentTime - $timestamp) <= $tolerance;
}
3. Nonce Protection
function validateNonce($nonce) {
// Check if nonce was already used (prevent replay attacks)
return !isNonceUsed($nonce);
}
---
๐ Integration Scenarios
Scenario 1: CRM to ERP Integration
// 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
// 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
// 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
// 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:
// 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:
// 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:
// 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 - PHP 8.2 migration guide
- โข authentication.php - Local authentication handling
- โข 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