TokenAuthenticator::getCredentials()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
namespace AppBundle\Security;
3
4
use Symfony\Component\HttpFoundation\Request;
5
use Symfony\Component\HttpFoundation\JsonResponse;
6
use Symfony\Component\Security\Core\User\UserInterface;
7
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
8
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
9
use Symfony\Component\Security\Core\Exception\AuthenticationException;
10
use Symfony\Component\Security\Core\User\UserProviderInterface;
11
use Doctrine\ORM\EntityManager;
12
13
class TokenAuthenticator extends AbstractGuardAuthenticator
14
{
15
    private $em;
16
17
    public function __construct(EntityManager $em)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $em. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
18
    {
19
        $this->em = $em;
20
    }
21
22
    /**
23
     * Called on every request. Return whatever credentials you want,
24
     * or null to stop authentication.
25
     */
26
    public function getCredentials(Request $request)
27
    {
28
        if (!$token = $request->headers->get('X-AUTH-TOKEN')) {
29
            // no token? Return null and no other methods will be called
30
            return;
31
        }
32
33
        // What you return here will be passed to getUser() as $credentials
34
        return array(
35
            'token' => $token,
36
        );
37
    }
38
39
    public function getUser($credentials, UserProviderInterface $userProvider)
40
    {
41
        $accessToken = $credentials['token'];
42
43
        // if null, authentication will fail
44
        // if a User object, checkCredentials() is called
45
        return $this->em->getRepository('AppBundle:User')
46
            ->findOneBy(array('accessToken' => $accessToken));
47
    }
48
49
    public function checkCredentials($credentials, UserInterface $user)
50
    {
51
        // check credentials - e.g. make sure the password is valid
52
        // no credential check is needed in this case
53
54
        // return true to cause authentication success
55
        return true;
56
    }
57
58
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
59
    {
60
        // on success, let the request continue
61
        return null;
62
    }
63
64
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
65
    {
66
        $data = array(
67
            'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
68
69
            // or to translate this message
70
            // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
71
        );
72
73
        return new JsonResponse($data, 403);
74
    }
75
76
    /**
77
     * Called when authentication is needed, but it's not sent
78
     */
79
    public function start(Request $request, AuthenticationException $authException = null)
80
    {
81
        $data = array(
82
            // you might translate this message
83
            'message' => 'Authentication Required'
84
        );
85
86
        return new JsonResponse($data, 401);
87
    }
88
89
    public function supportsRememberMe()
90
    {
91
        return false;
92
    }
93
}