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\RedirectResponse; |
12
|
|
|
use Erdemkeren\TemporaryAccess\TokenInterface; |
13
|
|
|
use Illuminate\Contracts\Auth\Authenticatable; |
14
|
|
|
use Erdemkeren\TemporaryAccess\TemporaryAccessFacade as TemporaryAccess; |
15
|
|
|
|
16
|
|
|
class OtpAccess |
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
|
4 |
|
public function handle($request, Closure $next, $guard = null) |
28
|
|
|
{ |
29
|
4 |
|
if (! $user = $request->user($guard)) { |
30
|
1 |
|
throw new \LogicException( |
31
|
1 |
|
'The otp access control middleware requires user authentication via laravel guards.' |
32
|
|
|
); |
33
|
|
|
} |
34
|
|
|
|
35
|
3 |
|
if (! $request->hasCookie('otp_token')) { |
36
|
1 |
|
$this->sendNewOtpToUser($user); |
37
|
|
|
|
38
|
1 |
|
return $this->redirectToOtpPage(); |
39
|
|
|
} |
40
|
|
|
|
41
|
2 |
|
$token = TemporaryAccess::retrieveByCipherText( |
42
|
2 |
|
$user->getAuthIdentifier(), |
43
|
2 |
|
$request->cookie('otp_token') |
|
|
|
|
44
|
|
|
); |
45
|
|
|
|
46
|
2 |
|
if (! $token || $token->expired()) { |
47
|
1 |
|
$this->sendNewOtpToUser($user); |
48
|
|
|
|
49
|
1 |
|
return $this->redirectToOtpPage(); |
50
|
|
|
} |
51
|
|
|
|
52
|
1 |
|
$request->macro('otpToken', function () use ($token): TokenInterface { |
53
|
1 |
|
return $token; |
54
|
1 |
|
}); |
55
|
|
|
|
56
|
1 |
|
return $next($request); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Get the redirect url if check do not pass. |
61
|
|
|
* |
62
|
|
|
* @return RedirectResponse |
63
|
|
|
*/ |
64
|
2 |
|
protected function redirectToOtpPage(): RedirectResponse |
65
|
|
|
{ |
66
|
2 |
|
session([ |
67
|
2 |
|
'otp_requested' => true, |
68
|
2 |
|
'otp_redirect_url' => url()->current(), |
69
|
|
|
]); |
70
|
|
|
|
71
|
2 |
|
return redirect()->route('otp.create'); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Create a new otp and notify the user. |
76
|
|
|
* |
77
|
|
|
* @param Authenticatable $user |
78
|
|
|
*/ |
79
|
2 |
|
private function sendNewOtpToUser(Authenticatable $user): void |
80
|
|
|
{ |
81
|
2 |
|
$token = TemporaryAccess::create($user, 6); |
82
|
|
|
|
83
|
2 |
|
$user->notify($token->toNotification()); |
|
|
|
|
84
|
2 |
|
} |
85
|
|
|
} |
86
|
|
|
|
This check looks at variables that are passed out again to other methods.
If the outgoing method call has stricter type requirements than the method itself, an issue is raised.
An additional type check may prevent trouble.