1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Http\Controllers\Api\Auth; |
6
|
|
|
|
7
|
|
|
use App\Auth\Dispensary\Exceptions\TokenExpiredException; |
8
|
|
|
use App\Auth\LoginDispensary; |
9
|
|
|
use App\Models\User; |
10
|
|
|
use App\Models\UserToken; |
11
|
|
|
use App\SPA\UrlGenerator; |
12
|
|
|
use Illuminate\Contracts\Routing\ResponseFactory; |
13
|
|
|
use Illuminate\Contracts\Translation\Translator; |
14
|
|
|
use Illuminate\Http\RedirectResponse; |
15
|
|
|
use Illuminate\Http\Request; |
16
|
|
|
use Illuminate\Support\Str; |
17
|
|
|
|
18
|
|
|
final class Dispense |
19
|
|
|
{ |
20
|
|
|
private ResponseFactory $responseFactory; |
21
|
|
|
|
22
|
|
|
private UrlGenerator $urlGenerator; |
23
|
|
|
|
24
|
|
|
private LoginDispensary $dispensary; |
25
|
|
|
|
26
|
|
|
private Translator $translator; |
27
|
|
|
|
28
|
6 |
|
public function __construct( |
29
|
|
|
ResponseFactory $responseFactory, |
30
|
|
|
UrlGenerator $urlGenerator, |
31
|
|
|
LoginDispensary $dispensary, |
32
|
|
|
Translator $translator |
33
|
|
|
) { |
34
|
6 |
|
$this->responseFactory = $responseFactory; |
35
|
6 |
|
$this->urlGenerator = $urlGenerator; |
36
|
6 |
|
$this->dispensary = $dispensary; |
37
|
6 |
|
$this->translator = $translator; |
38
|
6 |
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param \Illuminate\Http\Request $request |
42
|
|
|
* @return \Illuminate\Http\RedirectResponse |
43
|
|
|
* @throws \Psr\SimpleCache\InvalidArgumentException |
44
|
|
|
*/ |
45
|
6 |
|
public function __invoke(Request $request): RedirectResponse |
46
|
|
|
{ |
47
|
6 |
|
$url = $this->urlGenerator->to('auth/callback', [ |
48
|
6 |
|
'redirect_uri' => $request->input('redirect_uri'), |
49
|
|
|
]); |
50
|
|
|
|
51
|
6 |
|
if (! $request->filled(['email', 'token'])) { |
52
|
1 |
|
return $this->responseFactory->redirectTo($url); |
53
|
|
|
} |
54
|
|
|
|
55
|
5 |
|
$user = User::query()->where('email', $request->input('email'))->first(); |
56
|
|
|
|
57
|
5 |
|
if (! $user instanceof User) { |
58
|
1 |
|
return $this->responseFactory->redirectTo($url); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
try { |
62
|
4 |
|
$verified = $this->dispensary->verify($user, $request->input('token')); |
63
|
|
|
|
64
|
3 |
|
if (! $verified) { |
65
|
1 |
|
return $this->responseFactory->redirectTo($url); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
do { |
69
|
2 |
|
$token = Str::random(128); |
70
|
2 |
|
} while (UserToken::query()->where('token', $token)->exists()); |
71
|
|
|
|
72
|
2 |
|
$user->tokens()->create(['token' => $token]); |
73
|
|
|
|
74
|
2 |
|
return $this->responseFactory->redirectTo($url . '#token=' . $token); |
75
|
1 |
|
} catch (TokenExpiredException $exception) { |
76
|
1 |
|
return $this->responseFactory->redirectTo($url); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|