Completed
Pull Request — master (#137)
by
unknown
14:15
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
    /**
17
     * @var ManagerRegistry
18
     */
19
    private $registry;
20
21
    /**
22
     * @param ManagerRegistry $registry
23
     */
24
    public function __construct(ManagerRegistry $registry)
25
    {
26
        $this->registry = $registry;
27
    }
28
29
    /**
30
     * @param Request $request
31
     * @param string $providerKey
32
     * @return PreAuthenticatedToken
33
     */
34
    public function createToken(Request $request, $providerKey)
35
    {
36
        $apiKey = $request->headers->get('API-Key-Token');
37
        if (!$apiKey) {
38
            throw new BadCredentialsException();
39
        }
40
41
        return new PreAuthenticatedToken(
42
            'customer',
43
            $apiKey,
44
            $providerKey
45
        );
46
    }
47
48
    /**
49
     * @param TokenInterface $token
50
     * @param string $providerKey
51
     * @return bool
52
     */
53
    public function supportsToken(TokenInterface $token, $providerKey)
54
    {
55
        return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
0 ignored issues
show
Bug introduced by
The class Symfony\Component\Securi...n\PreAuthenticatedToken does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
56
    }
57
58
    /**
59
     * @param TokenInterface $token
60
     * @param UserProviderInterface $userProvider
61
     * @param string $providerKey
62
     * @return PreAuthenticatedToken
63
     */
64
    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
65
    {
66
        if (!$userProvider instanceof ApiKeyUserProvider) {
67
            throw new \InvalidArgumentException(
68
                sprintf(
69
                    'The user provider must be an instance of ApiKeyUserProvider (%s was given).',
70
                    get_class($userProvider)
71
                )
72
            );
73
        }
74
75
        $apiKey = $token->getCredentials();
76
        $username = $userProvider->getUsernameByApiKey($apiKey);
77
78
        if (!$username) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $username of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
79
            // CAUTION: this message will be returned to the client
80
            // (so don't put any un-trusted messages / error strings here)
81
            throw new CustomUserMessageAuthenticationException(
82
                sprintf('API Key "%s" does not exist.', $apiKey)
83
            );
84
        }
85
86
        $user = $userProvider->loadUserByUsername($username);
87
88
        return new PreAuthenticatedToken(
89
            $user,
90
            $apiKey,
91
            $providerKey,
92
            $user->getRoles()
93
        );
94
    }
95
}
96