Completed
Pull Request — master (#144)
by
unknown
12:31
created

ApiKeyUserProvider   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 2
Bugs 0 Features 1
Metric Value
dl 0
loc 70
rs 10
c 2
b 0
f 1
wmc 6
lcom 1
cbo 4

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getUsernameByApiKey() 0 16 2
A loadUserByUsername() 0 10 1
A refreshUser() 0 8 1
A supportsClass() 0 4 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
    public function __construct(ManagerRegistry $registry)
22
    {
23
        $this->registry = $registry;
24
    }
25
26
    /**
27
     * @param string $apiKey
28
     * @return null|object
29
     */
30
    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
            ->registry
36
            ->getManager()
37
            ->getRepository('AppBundle:Customer')
38
            ->findOneBy(['apiKey' => $apiKey]);
39
40
        if (!$user) {
41
            return null;
42
        }
43
44
        return $user->getUsername();
45
    }
46
47
    /**
48
     * @inheritdoc
49
     */
50
    public function loadUserByUsername($username)
51
    {
52
        return new User(
53
            $username,
54
            null,
55
            // the roles for the user - you may choose to determine
56
            // these dynamically somehow based on the user
57
            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