Passed
Pull Request — master (#7)
by Koen
04:12
created

Dispense::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 4
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 1
rs 10
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\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 LoginDispensary $dispensary;
24
25
    private Translator $translator;
26
27 6
    public function __construct(
28
        ResponseFactory $responseFactory,
29
        UrlGenerator $urlGenerator,
30
        LoginDispensary $dispensary,
31
        Translator $translator
32
    ) {
33 6
        $this->responseFactory = $responseFactory;
34 6
        $this->urlGenerator = $urlGenerator;
35 6
        $this->dispensary = $dispensary;
36 6
        $this->translator = $translator;
37 6
    }
38
39
    /**
40
     * @param  \Illuminate\Http\Request $request
41
     * @return \Illuminate\Http\RedirectResponse
42
     * @throws \Psr\SimpleCache\InvalidArgumentException
43
     */
44 6
    public function __invoke(Request $request): RedirectResponse
45
    {
46 6
        $url = $this->urlGenerator->to('auth/callback', [
47 6
            'redirect_uri' => $request->input('redirect_uri'),
48
        ]);
49
50 6
        if (! $request->filled(['email', 'token'])) {
51 1
            return $this->responseFactory->redirectTo($url);
52
        }
53
54 5
        $user = User::query()->where('email', $request->input('email'))->first();
55
56 5
        if (! $user instanceof User) {
57 1
            return $this->responseFactory->redirectTo($url);
58
        }
59
60
        try {
61 4
            $verified = $this->dispensary->verify($user, $request->input('token'));
62
63 3
            if (! $verified) {
64 1
                return $this->responseFactory->redirectTo($url);
65
            }
66
67 2
            $user->tokens()->create(['token' => $token = Str::random(128)]);
68
69 2
            return $this->responseFactory->redirectTo($url . '#token=' . $token);
70 1
        } catch (TokenExpiredException $exception) {
71 1
            return $this->responseFactory->redirectTo($url);
72
        }
73
    }
74
}
75