1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Auth\Dispensary; |
6
|
|
|
|
7
|
|
|
use App\Auth\Dispensary\Exceptions\TokenExpired; |
8
|
|
|
use Illuminate\Contracts\Auth\Authenticatable; |
9
|
|
|
use Illuminate\Contracts\Cache\Repository; |
10
|
|
|
use Illuminate\Contracts\Hashing\Hasher; |
11
|
|
|
use Illuminate\Support\Str; |
12
|
|
|
use function class_basename; |
13
|
|
|
|
14
|
|
|
final class Dispensary |
15
|
|
|
{ |
16
|
|
|
private Repository $cache; |
17
|
|
|
|
18
|
|
|
private Hasher $hasher; |
19
|
|
|
|
20
|
|
|
private int $ttl; |
21
|
|
|
|
22
|
|
|
private int $chars; |
23
|
|
|
|
24
|
10 |
|
public function __construct(Repository $cache, Hasher $hasher, int $ttl = 60, int $chars = 128) |
25
|
|
|
{ |
26
|
10 |
|
$this->cache = $cache; |
27
|
10 |
|
$this->hasher = $hasher; |
28
|
10 |
|
$this->ttl = $ttl; |
29
|
10 |
|
$this->chars = $chars; |
30
|
10 |
|
} |
31
|
|
|
|
32
|
5 |
|
public function dispense(Authenticatable $user): string |
33
|
|
|
{ |
34
|
5 |
|
$token = $this->generateToken(); |
35
|
|
|
|
36
|
5 |
|
$this->cache->put($this->getCacheKey($user), $this->hasher->make($token), $this->ttl); |
37
|
|
|
|
38
|
5 |
|
return $token; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param \Illuminate\Contracts\Auth\Authenticatable $user |
43
|
|
|
* @param string $token |
44
|
|
|
* @return bool |
45
|
|
|
* @throws \App\Auth\Dispensary\Exceptions\TokenExpired |
46
|
|
|
* @throws \Psr\SimpleCache\InvalidArgumentException |
47
|
|
|
*/ |
48
|
4 |
|
public function verify(Authenticatable $user, string $token): bool |
49
|
|
|
{ |
50
|
4 |
|
$hashedToken = $this->cache->get($this->getCacheKey($user)); |
51
|
|
|
|
52
|
4 |
|
if (null === $hashedToken) { |
53
|
1 |
|
throw new TokenExpired(); |
54
|
|
|
} |
55
|
|
|
|
56
|
3 |
|
return $this->hasher->check($token, $hashedToken); |
57
|
|
|
} |
58
|
|
|
|
59
|
5 |
|
private function generateToken(): string |
60
|
|
|
{ |
61
|
5 |
|
return Str::random($this->chars); |
62
|
|
|
} |
63
|
|
|
|
64
|
5 |
|
private function getCacheKey(Authenticatable $user) |
65
|
|
|
{ |
66
|
5 |
|
return implode('_', [ |
67
|
5 |
|
class_basename($user), |
68
|
5 |
|
'Token', |
69
|
5 |
|
$user->getAuthIdentifier(), |
70
|
|
|
]); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|