1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* @copyright 2018 Hilmi Erdem KEREN |
5
|
|
|
* @license MIT |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace Erdemkeren\Otp\Http\Middleware; |
9
|
|
|
|
10
|
|
|
use Closure; |
11
|
|
|
use Erdemkeren\Otp\OtpFacade; |
12
|
|
|
use Erdemkeren\Otp\TokenInterface; |
13
|
|
|
use Illuminate\Contracts\Auth\Authenticatable; |
14
|
|
|
use Illuminate\Http\RedirectResponse; |
15
|
|
|
use Illuminate\Http\Request; |
16
|
|
|
|
17
|
|
|
class Otp |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Handle an incoming request. |
21
|
|
|
* |
22
|
|
|
* @param \Illuminate\Http\Request $request |
23
|
|
|
* @param \Closure $next |
24
|
|
|
* @param null|string $guard |
25
|
|
|
* |
26
|
|
|
* @return mixed |
27
|
|
|
*/ |
28
|
5 |
|
public function handle(Request $request, Closure $next, $guard = null) |
29
|
|
|
{ |
30
|
5 |
|
if (! $user = $request->user($guard)) { |
31
|
1 |
|
throw new \LogicException( |
32
|
1 |
|
'The otp access control middleware requires user authentication via laravel guards.' |
33
|
|
|
); |
34
|
|
|
} |
35
|
|
|
|
36
|
4 |
|
if (! $request->hasCookie('otp_token')) { |
37
|
2 |
|
$this->sendNewOtpToUser($user); |
38
|
|
|
|
39
|
1 |
|
return $this->redirectToOtpPage(); |
40
|
|
|
} |
41
|
|
|
|
42
|
2 |
|
$token = OtpFacade::retrieveByCipherText( |
43
|
2 |
|
$user->getAuthIdentifier(), |
44
|
2 |
|
$request->cookie('otp_token') |
|
|
|
|
45
|
|
|
); |
46
|
|
|
|
47
|
2 |
|
if (! $token || $token->expired()) { |
48
|
1 |
|
$this->sendNewOtpToUser($user); |
49
|
|
|
|
50
|
1 |
|
return $this->redirectToOtpPage(); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$request->macro('otpToken', function () use ($token): TokenInterface { |
54
|
1 |
|
return $token; |
55
|
1 |
|
}); |
56
|
|
|
|
57
|
1 |
|
return $next($request); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Get the redirect url if check do not pass. |
62
|
|
|
* |
63
|
|
|
* @return RedirectResponse |
64
|
|
|
*/ |
65
|
2 |
|
protected function redirectToOtpPage(): RedirectResponse |
66
|
|
|
{ |
67
|
2 |
|
session([ |
68
|
2 |
|
'otp_requested' => true, |
69
|
2 |
|
'otp_redirect_url' => url()->current(), |
70
|
|
|
]); |
71
|
|
|
|
72
|
2 |
|
return redirect()->route('otp.create'); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* Create a new otp and notify the user. |
77
|
|
|
* |
78
|
|
|
* @param Authenticatable $user |
79
|
|
|
*/ |
80
|
3 |
|
private function sendNewOtpToUser(Authenticatable $user): void |
81
|
|
|
{ |
82
|
3 |
|
$token = OtpFacade::create($user, 6); |
83
|
|
|
|
84
|
3 |
|
if (! method_exists($user, 'notify')) { |
85
|
1 |
|
throw new \UnexpectedValueException( |
86
|
1 |
|
'The otp owner should be an instance of notifiable or implement the notify method.' |
87
|
|
|
); |
88
|
|
|
} |
89
|
|
|
|
90
|
2 |
|
$user->notify($token->toNotification()); |
|
|
|
|
91
|
2 |
|
} |
92
|
|
|
} |
93
|
|
|
|