ApiKeyUserProvider   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 9
dl 0
loc 33
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getApiKeyForToken() 0 4 1
A loadUserByIdentifier() 0 9 2
A refreshUser() 0 3 1
A supportsClass() 0 3 1
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/Security/Provider/ApiKeyUserProvider.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\Security\Provider;
10
11
use App\Entity\ApiKey;
12
use App\Repository\ApiKeyRepository;
13
use App\Security\ApiKeyUser;
14
use App\Security\Interfaces\ApiKeyUserProviderInterface;
15
use App\Security\RolesService;
16
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
17
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
18
use Symfony\Component\Security\Core\User\UserInterface;
19
use Symfony\Component\Security\Core\User\UserProviderInterface;
20
21
/**
22
 * Class ApiKeyUserProvider
23
 *
24
 * @package App\Security\Provider
25
 * @author TLe, Tarmo Leppänen <[email protected]>
26
 *
27
 * @template-implements UserProviderInterface<ApiKeyUser>
28
 */
29
class ApiKeyUserProvider implements ApiKeyUserProviderInterface, UserProviderInterface
30
{
31 627
    public function __construct(
32
        private readonly ApiKeyRepository $apiKeyRepository,
33
        private readonly RolesService $rolesService,
34
    ) {
35 627
    }
36
37 9
    public function supportsClass(string $class): bool
38
    {
39 9
        return $class === ApiKeyUser::class;
40
    }
41
42 14
    public function loadUserByIdentifier(string $identifier): ApiKeyUser
43
    {
44 14
        $apiKey = $this->getApiKeyForToken($identifier);
45
46 14
        if ($apiKey === null) {
47 2
            throw new UserNotFoundException('API key is not valid');
48
        }
49
50 12
        return new ApiKeyUser($apiKey, $this->rolesService->getInheritedRoles($apiKey->getRoles()));
51
    }
52
53 2
    public function refreshUser(UserInterface $user): UserInterface
54
    {
55 2
        throw new UnsupportedUserException('API key cannot refresh user');
56
    }
57
58 25
    public function getApiKeyForToken(string $token): ?ApiKey
59
    {
60 25
        return $this->apiKeyRepository->findOneBy([
61 25
            'token' => $token,
62 25
        ]);
63
    }
64
}
65