Completed
Pull Request — master (#144)
by Serhii
24:57
created

ApiKeyAuthenticator::onAuthenticationFailure()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 27
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 2

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 2
eloc 20
c 2
b 1
f 1
nc 2
nop 2
dl 0
loc 27
ccs 18
cts 18
cp 1
crap 2
rs 8.8571
1
<?php
2
3
namespace AppBundle\Security;
4
5
use AppBundle\Entity\Client;
6
use Monolog\Logger;
7
use Doctrine\Common\Persistence\ManagerRegistry;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\Security\Core\User\UserInterface;
12
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
13
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
14
use Symfony\Component\Security\Core\Exception\AuthenticationException;
15
use Symfony\Component\Security\Core\User\UserProviderInterface;
16
17
class ApiKeyAuthenticator extends AbstractGuardAuthenticator
18
{
19
    /**
20
     * @var ManagerRegistry
21
     */
22
    private $registry;
23
    /**
24
     * @var Logger
25
     */
26
    private $logger;
27
28 104
    public function __construct(ManagerRegistry $registry, Logger $logger)
29
    {
30 104
        $this->registry = $registry;
31 104
        $this->logger = $logger;
32 104
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37 26
    public function getCredentials(Request $request)
38
    {
39 26
        if (!$token = $request->headers->get('API-Key-Token')) {
40 6
            return null;
41
        }
42
43
        return array(
44 20
            'token' => $token,
45
        );
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 20
    public function getUser($credentials, UserProviderInterface $userProvider)
52
    {
53 20
        $apiKey = $credentials['token'];
54
55 20
        $user = $this->registry->getRepository('AppBundle:User')
56 20
            ->findOneBy(['apiKey' => $apiKey]);
57
58 20
        return $user;
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64 13
    public function checkCredentials($credentials, UserInterface $user)
65
    {
66 13
        return true;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 13
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
73
    {
74 13
        return null;
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 8
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
81
    {
82
        $data = [
83 8
            'code' => '403',
84
            'message' => 'Forbidden. You don\'t have necessary permissions for the resource',
85
        ];
86 8
        $client = $this->registry->getRepository('AppBundle:Client')
87 8
            ->findOneBy(['ip' => $request->getClientIp()]);
88 8
        if ($client) {
89 1
            $countAttempts = $client->getCountAttempts();
90 1
            $client->setCountAttempts(++$countAttempts);
91 1
            $this->registry->getManager()->flush();
92 1
            $this->writeLogger($client);
93
94 1
            return new JsonResponse($data, Response::HTTP_FORBIDDEN);
95
        }
96
97 7
        $client = new Client();
98 7
        $client->setCountAttempts(1);
99 7
        $client->setIp($request->getClientIp());
100 7
        $client->setBanned(false);
101 7
        $this->registry->getManager()->persist($client);
102 7
        $this->registry->getManager()->flush();
103 7
        $this->writeLogger($client);
104
105 7
        return new JsonResponse($data, Response::HTTP_FORBIDDEN);
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111 6
    public function start(Request $request, AuthenticationException $authException = null)
112
    {
113
        $data = [
114 6
            'code' => '401',
115
            'message' => 'Authentication required',
116
        ];
117
118 6
        return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    public function supportsRememberMe()
125
    {
126
        return false;
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132 8
    private function writeLogger($client)
133
    {
134 8
        if ($client->getCountAttempts() % 50 == 0 || $client->getCountAttempts() == 1) {
135 8
            $this->logger->err('403. api_key not valid!');
136
        }
137 8
    }
138
}
139