Skip to content

Commit

Permalink
Merge pull request #14 from dpdconnect/1.1.6
Browse files Browse the repository at this point in the history
1.1.6
  • Loading branch information
dpdplugin authored Nov 18, 2021
2 parents 289c441 + d0d377b commit 991526a
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/ClientBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class ClientBuilder implements ClientBuilderInterface
public function __construct($endpoint = null, $meta = null)
{
$this->endpoint = 1 === preg_match('#((https?)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i', $endpoint) ? $endpoint : Client::ENDPOINT;
$this->meta = $meta;
}
/**
Expand Down
64 changes: 64 additions & 0 deletions src/Resources/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ public function __construct($httpClient)
*/
public function getPublicJWTToken($username, $password)
{
$result = $this->getCachedPublicJWTToken($username);
if ($result && $this->isTokenValid($result)) {
return $result;
}

$requestBody = [
'username' => $username,
'password' => $password,
Expand All @@ -60,6 +65,65 @@ public function getPublicJWTToken($username, $password)
return $response;
}

$this->storeCachedPublicJWTToken($decoded['token'], $username);

return $decoded['token'];
}

/**
* @param $token
*
* @return bool
*/
private function isTokenValid($token)
{
$explodedToken = explode('.', $token);

// Check if token has header, payload and signature
if (count($explodedToken) != 3) {
return false;
}

list($header, $payload, $signature) = $explodedToken;

$payload = json_decode(base64_decode($payload), true);

// Check if token is expired
// Subtract 5 minutes of token to prevent returning a shortly-expiring token
if (time() >= (int)$payload['exp'] - (5*60)) {
return false;
}

return true;
}

/**
* @param $username
*
* @return false|mixed
*/
private function getCachedPublicJWTToken($username)
{
$filename = sys_get_temp_dir() . '/dpd/' . sha1('dpd-products' . date('YmdH') . serialize($username));

if (!file_exists($filename) || filesize($filename) == 0) {
return false;
}

return unserialize(file_get_contents($filename));
}

/**
* @param $token
* @param $username
*/
private function storeCachedPublicJWTToken($token, $username)
{
if (!file_exists(sys_get_temp_dir() . '/dpd/')) {
mkdir(sys_get_temp_dir() . '/dpd/');
}

$filename = sys_get_temp_dir() .'/dpd/' . sha1('dpd-products' . date('YmdH') . serialize($username));
file_put_contents($filename, serialize($token));
}
}

0 comments on commit 991526a

Please sign in to comment.