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\Http\RedirectResponse; |
14
|
|
|
use Illuminate\Http\Request; |
15
|
|
|
|
16
|
|
|
class Otp |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Handle an incoming request. |
20
|
|
|
* |
21
|
|
|
* @param \Illuminate\Http\Request $request |
22
|
|
|
* @param \Closure $next |
23
|
|
|
* @param null|string $guard |
24
|
|
|
* |
25
|
|
|
* @return mixed |
26
|
|
|
*/ |
27
|
|
|
public function handle(Request $request, Closure $next, $guard = null) |
28
|
5 |
|
{ |
29
|
|
|
if (! $user = $request->user($guard)) { |
30
|
5 |
|
throw new \LogicException( |
31
|
1 |
|
'The otp access control middleware requires user authentication via laravel guards.' |
32
|
1 |
|
); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
if (! $request->hasCookie('otp_token')) { |
36
|
4 |
|
OtpFacade::sendNewOtpToUser($user); |
37
|
2 |
|
|
38
|
|
|
return $this->redirectToOtpPage(); |
39
|
1 |
|
} |
40
|
|
|
|
41
|
|
|
$token = OtpFacade::retrieveByCipherText( |
42
|
2 |
|
$user->getAuthIdentifier(), |
43
|
2 |
|
$request->cookie('otp_token') |
|
|
|
|
44
|
2 |
|
); |
45
|
|
|
|
46
|
|
|
if (! $token || $token->expired()) { |
47
|
2 |
|
OtpFacade::sendNewOtpToUser($user); |
48
|
1 |
|
|
49
|
|
|
return $this->redirectToOtpPage(); |
50
|
1 |
|
} |
51
|
|
|
|
52
|
|
|
$request->macro('otpToken', function () use ($token): TokenInterface { |
53
|
1 |
|
return $token; |
54
|
1 |
|
}); |
55
|
1 |
|
|
56
|
|
|
return $next($request); |
57
|
1 |
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Get the redirect url if check do not pass. |
61
|
|
|
* |
62
|
|
|
* @return RedirectResponse |
63
|
|
|
*/ |
64
|
|
|
protected function redirectToOtpPage(): RedirectResponse |
65
|
2 |
|
{ |
66
|
|
|
session([ |
67
|
2 |
|
'otp_requested' => true, |
68
|
2 |
|
'otp_redirect_url' => url()->current(), |
69
|
2 |
|
]); |
70
|
|
|
|
71
|
|
|
return redirect()->route('otp.create'); |
72
|
2 |
|
} |
73
|
|
|
} |
74
|
|
|
|