Skip to content

Commit 991526a

Browse files
authored
Merge pull request #14 from dpdconnect/1.1.6
1.1.6
2 parents 289c441 + d0d377b commit 991526a

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/ClientBuilder.php

+1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ class ClientBuilder implements ClientBuilderInterface
3737
public function __construct($endpoint = null, $meta = null)
3838
{
3939
$this->endpoint = 1 === preg_match('#((https?)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i', $endpoint) ? $endpoint : Client::ENDPOINT;
40+
$this->meta = $meta;
4041
}
4142

4243
/**

src/Resources/Token.php

+64
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ public function __construct($httpClient)
3535
*/
3636
public function getPublicJWTToken($username, $password)
3737
{
38+
$result = $this->getCachedPublicJWTToken($username);
39+
if ($result && $this->isTokenValid($result)) {
40+
return $result;
41+
}
42+
3843
$requestBody = [
3944
'username' => $username,
4045
'password' => $password,
@@ -60,6 +65,65 @@ public function getPublicJWTToken($username, $password)
6065
return $response;
6166
}
6267

68+
$this->storeCachedPublicJWTToken($decoded['token'], $username);
69+
6370
return $decoded['token'];
6471
}
72+
73+
/**
74+
* @param $token
75+
*
76+
* @return bool
77+
*/
78+
private function isTokenValid($token)
79+
{
80+
$explodedToken = explode('.', $token);
81+
82+
// Check if token has header, payload and signature
83+
if (count($explodedToken) != 3) {
84+
return false;
85+
}
86+
87+
list($header, $payload, $signature) = $explodedToken;
88+
89+
$payload = json_decode(base64_decode($payload), true);
90+
91+
// Check if token is expired
92+
// Subtract 5 minutes of token to prevent returning a shortly-expiring token
93+
if (time() >= (int)$payload['exp'] - (5*60)) {
94+
return false;
95+
}
96+
97+
return true;
98+
}
99+
100+
/**
101+
* @param $username
102+
*
103+
* @return false|mixed
104+
*/
105+
private function getCachedPublicJWTToken($username)
106+
{
107+
$filename = sys_get_temp_dir() . '/dpd/' . sha1('dpd-products' . date('YmdH') . serialize($username));
108+
109+
if (!file_exists($filename) || filesize($filename) == 0) {
110+
return false;
111+
}
112+
113+
return unserialize(file_get_contents($filename));
114+
}
115+
116+
/**
117+
* @param $token
118+
* @param $username
119+
*/
120+
private function storeCachedPublicJWTToken($token, $username)
121+
{
122+
if (!file_exists(sys_get_temp_dir() . '/dpd/')) {
123+
mkdir(sys_get_temp_dir() . '/dpd/');
124+
}
125+
126+
$filename = sys_get_temp_dir() .'/dpd/' . sha1('dpd-products' . date('YmdH') . serialize($username));
127+
file_put_contents($filename, serialize($token));
128+
}
65129
}

0 commit comments

Comments
 (0)