Passed
Pull Request — master (#1636)
by Tarmo
09:53
created

ApiKeyUserProvider::loadUserByUsername()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
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
class ApiKeyUserProvider implements ApiKeyUserProviderInterface, UserProviderInterface
28
{
29 627
    public function __construct(
30
        private ApiKeyRepository $apiKeyRepository,
31
        private RolesService $rolesService,
32
    ) {
33 627
    }
34
35 9
    public function supportsClass(string $class): bool
36
    {
37 9
        return $class === ApiKeyUser::class;
38
    }
39
40 14
    public function loadUserByIdentifier(string $identifier): ApiKeyUser
41
    {
42 14
        $apiKey = $this->getApiKeyForToken($identifier);
43
44 14
        if ($apiKey === null) {
45 2
            throw new UserNotFoundException('API key is not valid');
46
        }
47
48 12
        return new ApiKeyUser($apiKey, $this->rolesService->getInheritedRoles($apiKey->getRoles()));
49
    }
50
51 2
    public function refreshUser(UserInterface $user): UserInterface
52
    {
53 2
        throw new UnsupportedUserException('API key cannot refresh user');
54
    }
55
56 25
    public function getApiKeyForToken(string $token): ?ApiKey
57
    {
58 25
        return $this->apiKeyRepository->findOneBy([
59 25
            'token' => $token,
60
        ]);
61
    }
62
}
63