Passed
Branch master (98ecdf)
by Michael
56:56
created

SimplePreAuthenticator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 2
1
<?php
2
3
/*
4
 * This file is part of the OsLabSecurityApiBundle package.
5
 *
6
 * (c) OsLab <https://github.com/OsLab>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace OsLab\SecurityApiBundle\Security\Authentication;
13
14
use OsLab\SecurityApiBundle\Security\User\InMemoryApiUserProvider;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
17
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
18
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
19
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
20
use Symfony\Component\Security\Core\User\UserProviderInterface;
21
use Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface;
22
23
/**
24
 * Class SimplePreAuthenticator
25
 *
26
 * @author Michael COULLERET <[email protected]>
27
 * @author Florent DESPIERRES <[email protected]>
28
 */
29
class SimplePreAuthenticator implements SimplePreAuthenticatorInterface
30
{
31
    /**
32
     * @var string
33
     */
34
    protected $keyName;
35
36
    /**
37
     * @var string
38
     */
39
    protected $method;
40
41
    /**
42
     * Constructor.
43
     *
44
     * @param string $keyName
45
     * @param string $method
46
     */
47
    public function __construct($keyName, $method)
48
    {
49
        $this->keyName = $keyName;
50
        $this->method  = $method;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function createToken(Request $request, $providerKey)
57
    {
58
        $apiKey = null;
59
60
        if ($this->method === 'header') {
61
            $apiKey = $request->headers->get($this->keyName);
62
        } elseif ($this->method === 'query') {
63
            $apiKey = $request->query->get($this->keyName);
64
        }
65
66
        if (isset($apiKey) === false) {
67
            throw new AccessDeniedException(sprintf('The key "%s" is not provided', $this->keyName));
68
        }
69
70
        return new PreAuthenticatedToken(
71
            'anon.',
72
            $apiKey,
73
            $providerKey
74
        );
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function supportsToken(TokenInterface $token, $providerKey)
81
    {
82
        return $token instanceof PreAuthenticatedToken && $token->getProviderKey() == $providerKey;
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
89
    {
90
        if (!$userProvider instanceof InMemoryApiUserProvider) {
91
            throw new \InvalidArgumentException(
92
                sprintf(
93
                    'The user provider must be an instance of %s; (%s was given).',
94
                    InMemoryApiUserProvider::class,
95
                    get_class($userProvider)
96
                )
97
            );
98
        }
99
100
        $apiKey   = $token->getCredentials();
101
        $username = $userProvider->getUsernameByApiKey($apiKey);
102
103
        if (isset($username) === false && strlen($username) <= 0) {
104
            $exception = new UsernameNotFoundException(sprintf('API Key "%s" does not exist.', $apiKey));
105
            $exception->setUsername($username);
106
107
            throw $exception;
108
        }
109
110
        $user = $userProvider->loadUserByUsername($username);
111
112
        return new PreAuthenticatedToken(
113
            $user,
114
            $apiKey,
115
            $providerKey,
116
            $user->getRoles()
117
        );
118
    }
119
}
120