|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace LaravelWorkcast; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\Cache; |
|
6
|
|
|
use Illuminate\Support\Facades\Http; |
|
7
|
|
|
|
|
8
|
|
|
class Auth |
|
9
|
|
|
{ |
|
10
|
|
|
protected ?AccessToken $accessToken = null; |
|
11
|
|
|
|
|
12
|
|
|
protected string $cacheKey = 'workcast_access_token'; |
|
13
|
|
|
|
|
14
|
|
|
protected string $apiKey; |
|
15
|
|
|
|
|
16
|
16 |
|
public function __construct(string $apiKey) |
|
17
|
|
|
{ |
|
18
|
16 |
|
$this->apiKey = $apiKey; |
|
19
|
|
|
|
|
20
|
16 |
|
$this->restoreToken(); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
11 |
|
public function hasToken(): bool |
|
24
|
|
|
{ |
|
25
|
11 |
|
return $this->accessToken && $this->accessToken->valid(); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
10 |
|
public function getToken(): ?AccessToken |
|
29
|
|
|
{ |
|
30
|
10 |
|
if ($this->hasToken()) { |
|
31
|
8 |
|
return $this->accessToken; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
3 |
|
return $this->requestToken(); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
3 |
|
protected function requestToken(): ?AccessToken |
|
38
|
|
|
{ |
|
39
|
3 |
|
$response = Http::withHeaders([ |
|
40
|
3 |
|
'APIKey' => $this->apiKey, |
|
41
|
3 |
|
])->withOptions(array_merge( |
|
42
|
3 |
|
config('workcast.http_auth_config', []), |
|
43
|
3 |
|
[ |
|
44
|
3 |
|
'base_uri' => config('workcast.auth_url'), |
|
45
|
3 |
|
] |
|
46
|
3 |
|
))->post('/signin'); |
|
47
|
|
|
|
|
48
|
3 |
|
if ($response->ok() && ($responseData = $response->json()) && |
|
49
|
3 |
|
!empty($responseData['idToken']) && !empty($responseData['expiresIn']) |
|
50
|
|
|
) { |
|
51
|
1 |
|
$this->accessToken = new AccessToken($responseData['idToken'], $responseData['expiresIn']); |
|
52
|
|
|
} else { |
|
53
|
2 |
|
$this->accessToken = null; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
3 |
|
$this->storeToken(); |
|
57
|
|
|
|
|
58
|
3 |
|
return $this->accessToken; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
16 |
|
protected function restoreToken(): void |
|
62
|
|
|
{ |
|
63
|
16 |
|
$tokenData = Cache::get($this->cacheKey); |
|
64
|
16 |
|
$token = unserialize($tokenData); |
|
65
|
16 |
|
if ($token && ($token instanceof AccessToken) && $token->valid()) { |
|
66
|
11 |
|
$this->accessToken = $token; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
3 |
|
protected function storeToken(): bool |
|
71
|
|
|
{ |
|
72
|
3 |
|
if ($this->accessToken && $this->accessToken->valid()) { |
|
73
|
1 |
|
return Cache::add($this->cacheKey, serialize($this->accessToken), $this->accessToken->getExpiresAt()); |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
2 |
|
return Cache::forget($this->cacheKey); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
1 |
|
public function forgetToken(): void |
|
80
|
|
|
{ |
|
81
|
1 |
|
$this->accessToken = null; |
|
82
|
1 |
|
Cache::forget($this->cacheKey); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|