Completed
Pull Request — master (#137)
by
unknown
11:18
created

ApiKeyUserProvider::loadUserByUsername()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 5
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 10
rs 9.4285
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
    private $registry;
14
15
    public function __construct(ManagerRegistry $registry)
16
    {
17
        $this->registry = $registry;
18
    }
19
20
    public function getUsernameForApiKey($apiKey)
21
    {
22
        // Look up the username based on the token in the database, via
23
        // an API call, or do something entirely different
24
25
        $user = $this->registry->getManager()
26
            ->getRepository('AppBundle:Customer')
27
            ->findOneByApiKey($apiKey);
28
        if ($user) {
29
            $username = $user->getUsername();
30
        } else {
31
            $username = null;
32
        }
33
34
        return $username;
35
    }
36
37
    public function loadUserByUsername($username)
38
    {
39
        return new User(
40
            $username,
41
            null,
42
            // the roles for the user - you may choose to determine
43
            // these dynamically somehow based on the user
44
            array('ROLE_API')
45
        );
46
    }
47
48
    public function refreshUser(UserInterface $user)
49
    {
50
        // this is used for storing authentication in the session
51
        // but in this example, the token is sent in each request,
52
        // so authentication can be stateless. Throwing this exception
53
        // is proper to make things stateless
54
        throw new UnsupportedUserException();
55
    }
56
57
    public function supportsClass($class)
58
    {
59
        return User::class === $class;
60
    }
61
62
    public function createApiKeyUser()
63
    {
64
    }
65
}
66