Users are already logged and their username is stored in a PHP session. I'm trying to allow users to chat using Socket.io without having to log in again. For a moment I thought I'd solved the problem using CURL to push the username to the Socket.io server and then redirecting the user with header('Location: http://'.$domain.':3000');
While this does send the needed information to the server it does not restrict it to a single user. So anyone who reloads their Socket.io client page essentially logs in again as the last user who's information was sent via CURL. How can I send the username from the PHP sesion to the Socket.io server and restrict that information to a single user?
PHP
<?php
session_start();
echo $_SESSION['member'];
$member = $_SESSION['member'];
$number = $_SESSION['Member_Number'];
$data = array("name" => $member, "number" => $number);
$data_string = json_encode($data);
$domain = $_SERVER['SERVER_NAME'];
$ch = curl_init('http://'.$domain.':3000/push');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
curl_exec($ch);
curl_close($ch);
header('Location: http://'.$domain.':3000');
?>
SERVER
app.all('/push', function(req, res) {
console.log(req.body.name); // member's name
console.log(req.body.number); // member's public id
memberName = req.body.name.trim();
memberNumber = req.body.number;
});
UPDATE: After taking Felix Fong's advice I'm attempting to solve this problem using JSON Web Tokens. Here is the PHP I'm using to create the tokens. I'm still not sure exactly how to get the tokens over to the socket.io server.
$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
// Create token payload as a JSON string
$payload = json_encode(['user_id' => 123]);
// Encode Header to Base64Url String
$base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
// Encode Payload to Base64Url String
$base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
// Create Signature Hash
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, 'abC123!', true);
// Encode Signature to Base64Url String
$base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
// Create JWT
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
echo $jwt;