Completed
Push — master ( 7e589b...500fd9 )
by Tarmo
16s queued 11s
created

ApiKeyUserProvider   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 42
ccs 13
cts 13
cp 1
rs 10
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A refreshUser() 0 3 1
A loadUserByUsername() 0 3 1
A getApiKeyForToken() 0 3 1
A loadUserByIdentifier() 0 9 2
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
class ApiKeyUserProvider implements ApiKeyUserProviderInterface, UserProviderInterface
28
{
29 341
    public function __construct(
30
        private ApiKeyRepository $apiKeyRepository,
31
        private RolesService $rolesService,
32
    ) {
33 341
    }
34
35 9
    public function supportsClass(string $class): bool
36
    {
37 9
        return $class === ApiKeyUser::class;
38
    }
39
40 29
    public function loadUserByIdentifier(string $identifier): ApiKeyUser
41
    {
42 29
        $apiKey = $this->getApiKeyForToken($identifier);
43
44 29
        if ($apiKey === null) {
45 2
            throw new UserNotFoundException('API key is not valid');
46
        }
47
48 27
        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 40
    public function getApiKeyForToken(string $token): ?ApiKey
57
    {
58 40
        return $this->apiKeyRepository->findOneBy(['token' => $token]);
59
    }
60
61
    /**
62
     * @todo Remove this method when Symfony 6.0.0 is released
63
     *
64
     * @codeCoverageIgnore
65
     */
66
    public function loadUserByUsername(string $username): ApiKeyUser
67
    {
68
        return $this->loadUserByIdentifier($username);
69
    }
70
}
71