Passed
Push — master ( cfceb1...4bf73b )
by Koen
09:48
created

AuthServiceProvider   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 45
ccs 15
cts 15
cp 1
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A registerSpaRequestGuard() 0 20 1
A boot() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Providers;
6
7
use App\Models\User;
8
use App\Models\UserToken;
9
use Illuminate\Auth\AuthenticationException;
10
use Illuminate\Auth\AuthManager;
11
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
12
use Illuminate\Http\Request;
13
14
final class AuthServiceProvider extends ServiceProvider
15
{
16
    /**
17
     * The policy mappings for the application.
18
     *
19
     * @var array
20
     */
21
    protected $policies = [];
22
23
    /**
24
     * Register any authentication / authorization services.
25
     *
26
     * @return void
27
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
28
     */
29 58
    public function boot(): void
30
    {
31 58
        $this->registerPolicies();
32
33 58
        $this->registerSpaRequestGuard();
34 58
    }
35
36
    /**
37
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
38
     */
39 58
    private function registerSpaRequestGuard(): void
40
    {
41
        /** @var AuthManager $authManager */
42 58
        $authManager = $this->app->make(AuthManager::class);
43
44
        $authManager->viaRequest('spa', static function (Request $request): User {
45
            /** @var UserToken $userToken */
46 3
            $userToken = UserToken::query()
47 3
                ->with('user')
48 3
                ->where('token', $request->bearerToken())
49 3
                ->whereNotNull('token')
50
                ->firstOr(static function () {
51 1
                    throw new AuthenticationException();
52 3
                });
53
54 2
            $user = $userToken->getUser();
55
56 2
            $user->setCurrentToken($userToken);
57
58 2
            return $user;
59 58
        });
60 58
    }
61
}
62