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