1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Alish\LaravelOtp\Drivers; |
4
|
|
|
|
5
|
|
|
use Alish\LaravelOtp\Contracts\Otp; |
6
|
|
|
use Illuminate\Cache\CacheManager; |
7
|
|
|
use Illuminate\Contracts\Hashing\Hasher; |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
class CacheDriver implements Otp |
11
|
|
|
{ |
12
|
|
|
use HasConfig, TokenGenerator, TokenManipulator; |
13
|
|
|
|
14
|
|
|
protected string $namespace = 'laravel-otp'; |
|
|
|
|
15
|
|
|
|
16
|
|
|
protected CacheManager $cache; |
17
|
|
|
|
18
|
|
|
protected Hasher $hash; |
19
|
|
|
|
20
|
|
|
protected array $config; |
21
|
|
|
|
22
|
|
|
public function __construct(CacheManager $cache, Hasher $hash, array $config) |
23
|
|
|
{ |
24
|
|
|
$this->cache = $cache; |
25
|
|
|
$this->hash = $hash; |
26
|
|
|
$this->config = $config; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function issue(string $key): string |
30
|
|
|
{ |
31
|
|
|
$this->storeToken($key, $token = $this->generateToken()); |
32
|
|
|
|
33
|
|
|
return $token; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
protected function storeToken(string $key, string $token): bool |
37
|
|
|
{ |
38
|
|
|
if (is_null($this->timeout())) { |
39
|
|
|
return $this->cache->forever( |
40
|
|
|
$this->key($key), |
41
|
|
|
$this->storableToken($token) |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return $this->cache->set( |
46
|
|
|
$this->key($key), |
47
|
|
|
$this->storableToken($token), |
48
|
|
|
$this->timeout() |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function key(string $key): string |
53
|
|
|
{ |
54
|
|
|
return $this->namespace . '-' . $key; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function check(string $key, string $token): bool |
58
|
|
|
{ |
59
|
|
|
return $this->compareTokens( |
60
|
|
|
$token, |
61
|
|
|
$this->cache->get($this->key($key)) |
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function use(string $key, string $token): bool |
66
|
|
|
{ |
67
|
|
|
$result = $this->check($key, $token); |
68
|
|
|
|
69
|
|
|
if ($result) { |
70
|
|
|
$this->forgetToken($key); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return $result; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
public function forgetToken(string $key): bool |
77
|
|
|
{ |
78
|
|
|
return $this->cache->forget($this->key($key)); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
public function revoke(string $key): bool |
82
|
|
|
{ |
83
|
|
|
return $this->forgetToken($key); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
|
87
|
|
|
} |
88
|
|
|
|