Completed
Pull Request — master (#137)
by
unknown
14:38
created

ApiKeyAuthenticator::authenticateToken()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 17
c 1
b 0
f 1
nc 3
nop 3
dl 0
loc 31
rs 8.8571
1
<?php
2
3
namespace AppBundle\Security;
4
5
use Symfony\Component\HttpFoundation\Request;
6
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
7
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
8
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
9
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
10
use Symfony\Component\Security\Core\User\UserProviderInterface;
11
use Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface;
12
use Doctrine\Common\Persistence\ManagerRegistry;
13
14
class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface
15
{
16
    private $registry;
17
18
    public function __construct(ManagerRegistry $registry)
19
    {
20
        $this->registry = $registry;
21
    }
22
23
    public function createToken(Request $request, $providerKey)
24
    {
25
26
        $apiKey = $request->headers->get('API-Key-Token');
27
        if (!$apiKey) {
28
            throw new BadCredentialsException();
29
        }
30
31
        return new PreAuthenticatedToken(
32
                 'customer.',
33
                 $apiKey,
34
                $providerKey
35
            );
36
    }
37
38
    public function supportsToken(TokenInterface $token, $providerKey)
39
    {
40
        return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
41
    }
42
43
    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
44
    {
45
        if (!$userProvider instanceof ApiKeyUserProvider) {
46
            throw new \InvalidArgumentException(
47
                sprintf(
48
                    'The user provider must be an instance of ApiKeyUserProvider (%s was given).',
49
                    get_class($userProvider)
50
                )
51
            );
52
        }
53
54
        $apiKey = $token->getCredentials();
55
        $username = $userProvider->getUsernameForApiKey($apiKey);
56
57
        if (!$username) {
58
            // CAUTION: this message will be returned to the client
59
            // (so don't put any un-trusted messages / error strings here)
60
            throw new CustomUserMessageAuthenticationException(
61
                sprintf('API Key "%s" does not exist.', $apiKey)
62
            );
63
        }
64
65
        $user = $userProvider->loadUserByUsername($username);
66
67
        return new PreAuthenticatedToken(
68
            $user,
69
            $apiKey,
70
            $providerKey,
71
            $user->getRoles()
72
        );
73
    }
74
}
75