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

ApiKeyAuthenticator   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 128
Duplicated Lines 14.84 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 3
Bugs 1 Features 2
Metric Value
c 3
b 1
f 2
dl 19
loc 128
rs 10
wmc 14
lcom 1
cbo 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getCredentials() 0 17 3
A getUser() 0 9 1
A checkCredentials() 0 4 1
A onAuthenticationSuccess() 0 4 1
A onAuthenticationFailure() 10 10 1
A start() 9 9 1
A supportsRememberMe() 0 4 1
B saveSwindler() 0 22 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace AppBundle\Security;
4
5
use AppBundle\Entity\Swindler;
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
use Symfony\Component\HttpKernel\Exception\HttpException;
17
18
class ApiKeyAuthenticator extends AbstractGuardAuthenticator
19
{
20
    /**
21
     * @var ManagerRegistry
22
     */
23
    private $registry;
24
    /**
25
     * @var Logger
26
     */
27
    private $logger;
28
29
    public function __construct(ManagerRegistry $registry, Logger $logger)
30
    {
31
        $this->registry = $registry;
32
        $this->logger = $logger;
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function getCredentials(Request $request)
39
    {
40
        $swindler = $this->registry->getRepository('AppBundle:Swindler')
41
            ->findSwindlerIsBanned($request->getClientIp());
42
43
        if ($swindler) {
44
            throw new HttpException(403, 'Forbidden. You\'re banned!');
45
        }
46
47
        if (!$token = $request->headers->get('API-Key-Token')) {
48
            return null;
49
        }
50
51
        return array(
52
            'token' => $token,
53
        );
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function getUser($credentials, UserProviderInterface $userProvider)
60
    {
61
        $apiKey = $credentials['token'];
62
63
        $user = $this->registry->getRepository('AppBundle:User')
64
            ->findOneBy(['apiKey' => $apiKey]);
65
66
        return $user;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function checkCredentials($credentials, UserInterface $user)
73
    {
74
        return true;
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
81
    {
82
        return null;
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88 View Code Duplication
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
89
    {
90
        $this->saveSwindler($request);
91
        $data = [
92
            'code' => '403',
93
            'message' => 'Forbidden. You don\'t have necessary permissions for the resource',
94
        ];
95
96
        return new JsonResponse($data, Response::HTTP_FORBIDDEN);
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102 View Code Duplication
    public function start(Request $request, AuthenticationException $authException = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
    {
104
        $data = [
105
            'code' => '401',
106
            'message' => 'Authentication required',
107
        ];
108
109
        return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
110
    }
111
112
    /**
113
     * {@inheritdoc}
114
     */
115
    public function supportsRememberMe()
116
    {
117
        return false;
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    private function saveSwindler($request)
124
    {
125
        $swindler = $this->registry->getRepository('AppBundle:Swindler')
126
            ->findOneBy(['ip' => $request->getClientIp()]);
127
128
        if ($swindler) {
129
            $countAttempts = $swindler->getCountAttempts();
130
            $swindler->setCountAttempts(++$countAttempts);
131
            $this->registry->getManager()->flush();
132
        } else {
133
            $swindler = new Swindler();
134
            $swindler->setCountAttempts(1);
135
            $swindler->setIp($request->getClientIp());
136
            $swindler->setBanned(false);
137
            $this->registry->getManager()->persist($swindler);
138
            $this->registry->getManager()->flush();
139
        }
140
141
        if (($swindler->getCountAttempts() % 50 == 0) || $swindler->getCountAttempts() == 1) {
142
            $this->logger->err('403. api_key not valid!');
143
        }
144
    }
145
}
146