1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Alish\LaravelOtp\Drivers; |
4
|
|
|
|
5
|
|
|
use Alish\LaravelOtp\Contracts\Otp; |
6
|
|
|
use Alish\LaravelOtp\Models\Otp as OtpModel; |
7
|
|
|
use Illuminate\Contracts\Hashing\Hasher; |
8
|
|
|
|
9
|
|
|
class DatabaseDriver implements Otp |
10
|
|
|
{ |
11
|
|
|
use HasConfig, TokenGenerator, TokenManipulator; |
12
|
|
|
|
13
|
|
|
protected array $config; |
|
|
|
|
14
|
|
|
|
15
|
|
|
protected Hasher $hash; |
16
|
|
|
|
17
|
|
|
public function __construct(Hasher $hash, array $config) |
18
|
|
|
{ |
19
|
|
|
$this->hash = $hash; |
20
|
|
|
$this->config = $config; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function issue(string $key): string |
24
|
|
|
{ |
25
|
|
|
$token = $this->generateToken(); |
26
|
|
|
$this->revokeAllTokensIfNeeded($key); |
27
|
|
|
$this->createOtpModel($key, $token); |
28
|
|
|
return $token; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function createOtpModel(string $key, string $token): OtpModel |
32
|
|
|
{ |
33
|
|
|
return OtpModel::forceCreate([ |
34
|
|
|
'key' => $key, |
35
|
|
|
'token' => $this->hashedToken($token), |
36
|
|
|
'expires_at' => now()->addSeconds($this->timeout()) |
37
|
|
|
]); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
protected function shouldRevoke(): bool |
41
|
|
|
{ |
42
|
|
|
return $this->getConfig('unique', false); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
protected function revokeAllTokensIfNeeded(string $key) |
46
|
|
|
{ |
47
|
|
|
if ($this->shouldRevoke()) { |
48
|
|
|
return $this->revoke($key); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return null; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function revoke(string $key): bool |
55
|
|
|
{ |
56
|
|
|
return OtpModel::valid($key) |
57
|
|
|
->update([ |
58
|
|
|
'revoked_at' => now() |
59
|
|
|
]) > 0; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function use(string $key, string $token): bool |
63
|
|
|
{ |
64
|
|
|
$foundValidOtp = $this->findValidOtp($key, $token); |
65
|
|
|
|
66
|
|
|
if (is_null($foundValidOtp)) { |
67
|
|
|
return false; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $foundValidOtp->useNow(); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function findValidOtp(string $key, string $token): ?OtpModel |
74
|
|
|
{ |
75
|
|
|
$otps = OtpModel::valid($key)->get(); |
76
|
|
|
|
77
|
|
|
if ($otps->count() === 0) { |
78
|
|
|
return null; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
foreach ($otps as $otp) { |
82
|
|
|
$result = $this->compareTokens($token, $otp->token); |
83
|
|
|
|
84
|
|
|
if ($result) { |
85
|
|
|
return $otp; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
return null; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
public function check(string $key, string $token): bool |
93
|
|
|
{ |
94
|
|
|
$foundValidOtp = $this->findValidOtp($key, $token); |
95
|
|
|
|
96
|
|
|
if (is_null($foundValidOtp)) { |
97
|
|
|
return false; |
98
|
|
|
} |
99
|
|
|
|
100
|
|
|
return true; |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
|