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