Completed
Pull Request — master (#137)
by
unknown
19:25 queued 05:24
created

ApiKeyUserProvider::loadUserByUsername()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 10
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
c 1
b 0
f 1
1
<?php
2
3
namespace AppBundle\Security;
4
5
use Symfony\Component\Security\Core\User\UserProviderInterface;
6
use Symfony\Component\Security\Core\User\User;
7
use Symfony\Component\Security\Core\User\UserInterface;
8
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
9
use Doctrine\Common\Persistence\ManagerRegistry;
10
11
class ApiKeyUserProvider implements UserProviderInterface
12
{
13
    /**
14
     * @var ManagerRegistry
15
     */
16
    private $registry;
17
18
    /**
19
     * @param ManagerRegistry $registry
20
     */
21 60
    public function __construct(ManagerRegistry $registry)
22
    {
23 60
        $this->registry = $registry;
24 60
    }
25
26
    /**
27
     * @param string $apiKey
28
     * @return null|object
29
     */
30 9
    public function getUsernameByApiKey($apiKey)
31
    {
32
        // Look up the username based on the token in the database, via
33
        // an API call, or do something entirely different
34
        $user = $this
35 9
            ->registry
36 9
            ->getManager()
37 9
            ->getRepository('AppBundle:Customer')
38 9
            ->findOneBy(['apiKey' => $apiKey]);
39
40 9
        if (!$user) {
41 3
            return null;
42
        }
43
44 7
        return $user->getUsername();
45
    }
46
47
    /**
48
     * @inheritdoc
49
     */
50 7
    public function loadUserByUsername($username)
51
    {
52 7
        return new User(
53
            $username,
54 7
            null,
55
            // the roles for the user - you may choose to determine
56
            // these dynamically somehow based on the user
57 7
            array('ROLE_API')
58
        );
59
    }
60
61
    /**
62
     * @inheritdoc
63
     */
64
    public function refreshUser(UserInterface $user)
65
    {
66
        // this is used for storing authentication in the session
67
        // but in this example, the token is sent in each request,
68
        // so authentication can be stateless. Throwing this exception
69
        // is proper to make things stateless
70
        throw new UnsupportedUserException();
71
    }
72
73
    /**
74
     * @inheritdoc
75
     */
76
    public function supportsClass($class)
77
    {
78
        return User::class === $class;
79
    }
80
}
81