FormAuthentication   A
last analyzed

Complexity

Total Complexity 21

Size/Duplication

Total Lines 218
Duplicated Lines 7.34 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 98.59%

Importance

Changes 0
Metric Value
wmc 21
dl 16
loc 218
ccs 70
cts 71
cp 0.9859
rs 10
c 0
b 0
f 0
lcom 1
cbo 6

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A login() 16 30 3
A findByUsername() 0 8 2
A find() 0 4 1
A checkingRequirements() 0 21 4
A logout() 0 16 2
A isAuthenticated() 0 4 1
A getAuthenticatedUser() 0 21 3
A checkForUserIdWithinSession() 0 4 1
A getUserIdFromSession() 0 4 1
A getCriteriaAsSting() 0 9 2

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
declare(strict_types=1);
4
5
namespace Chubbyphp\Security\Authentication;
6
7
use Chubbyphp\Security\Authentication\Exception\AuthenticationExceptionInterface;
8
use Chubbyphp\Security\Authentication\Exception\InvalidPasswordException;
9
use Chubbyphp\Security\Authentication\Exception\MissingRequirementException;
10
use Chubbyphp\Security\Authentication\Exception\UserNotFoundException;
11
use Chubbyphp\Security\UserRepositoryInterface;
12
use Chubbyphp\Session\SessionInterface;
13
use Psr\Http\Message\ServerRequestInterface as Request;
14
use Psr\Log\LoggerInterface;
15
use Psr\Log\NullLogger;
16
17
final class FormAuthentication implements AuthenticationInterface
18
{
19
    /**
20
     * @var PasswordManagerInterface
21
     */
22
    private $passwordManager;
23
24
    /**
25
     * @var SessionInterface
26
     */
27
    private $session;
28
29
    const USER_KEY = 'u';
30
31
    /**
32
     * @var UserRepositoryInterface|mixed
33
     */
34
    private $userRepository;
35
36
    /**
37
     * @var LoggerInterface
38
     */
39
    private $logger;
40
41
    /**
42
     * @param PasswordManagerInterface      $passwordManager
43
     * @param SessionInterface              $session
44
     * @param UserRepositoryInterface|mixed $userRepository
45
     */
46 13
    public function __construct(
47
        PasswordManagerInterface $passwordManager,
48
        SessionInterface $session,
49
        $userRepository,
50
        LoggerInterface $logger = null
51
    ) {
52 13
        $this->passwordManager = $passwordManager;
53 13
        $this->session = $session;
54 13
        $this->userRepository = $userRepository;
55 13
        $this->logger = $logger ?? new NullLogger();
56 13
    }
57
58
    /**
59
     * @param Request $request
60
     *
61
     * @throws AuthenticationExceptionInterface
62
     */
63 6
    public function login(Request $request)
64
    {
65 6
        $data = $request->getParsedBody();
66 6
        $this->checkingRequirements($data);
67
68
        /** @var UserPasswordInterface $user */
69 3 View Code Duplication
        if (null === $user = $this->findByUsername($data['username'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
70 1
            $this->logger->warning(
71 1
                'security.authentication.form: user not found with criteria {criteria}',
72 1
                ['criteria' => $this->getCriteriaAsSting(['username' => $data['username']])]
73
            );
74
75 1
            throw UserNotFoundException::create(['username' => $data['username']]);
76
        }
77
78 2 View Code Duplication
        if (!$this->passwordManager->verify($data['password'], $user->getPassword())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
79 1
            $this->logger->warning(
80 1
                'security.authentication.form: invalid password for user with criteria {criteria}',
81 1
                ['criteria' => $this->getCriteriaAsSting(['username' => $data['username']])]
82
            );
83
84 1
            throw InvalidPasswordException::create(['username' => $data['username']]);
85
        }
86
87 1
        $this->logger->info(
88 1
            'security.authentication.form: login successful for user with id {id}', ['id' => $user->getId()]
89
        );
90
91 1
        $this->session->set($request, self::USER_KEY, $user->getId());
92 1
    }
93
94
    /**
95
     * @param string $username
96
     *
97
     * @return UserInterface|null
98
     */
99 3
    private function findByUsername(string $username)
100
    {
101 3
        if ($this->userRepository instanceof UserRepositoryInterface) {
102 3
            return $this->userRepository->findByUsername($username);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->userRepository->findByUsername($username); of type Chubbyphp\Security\UserInterface|null adds the type Chubbyphp\Security\UserInterface to the return on line 102 which is incompatible with the return type documented by Chubbyphp\Security\Authe...ication::findByUsername of type Chubbyphp\Security\Authe...tion\UserInterface|null.
Loading history...
103
        }
104
105
        return $this->userRepository->findOneBy(['username' => $username]);
106
    }
107
108
    /**
109
     * @param string $id
110
     *
111
     * @return UserInterface|null
112
     */
113 3
    private function find(string $id)
114
    {
115 3
        return $this->userRepository->find($id);
116
    }
117
118
    /**
119
     * @param array|object|null $data
120
     */
121 6
    private function checkingRequirements($data)
122
    {
123 6
        $fields = [];
124 6
        if (!isset($data['username'])) {
125 2
            $fields[] = 'username';
126
        }
127
128 6
        if (!isset($data['password'])) {
129 2
            $fields[] = 'password';
130
        }
131
132 6
        if ([] === $fields) {
133 3
            return;
134
        }
135
136 3
        $this->logger->warning(
137 3
            'security.authentication.form: missing required fields {fields}', ['fields' => implode(', ', $fields)]
138
        );
139
140 3
        throw MissingRequirementException::create($fields);
141
    }
142
143
    /**
144
     * @param Request $request
145
     */
146 2
    public function logout(Request $request)
147
    {
148 2
        if (!$this->checkForUserIdWithinSession($request)) {
149 1
            $this->logger->warning('security.authentication.form: logout not authenticated');
150
151 1
            return;
152
        }
153
154 1
        $id = $this->getUserIdFromSession($request);
155
156 1
        $this->logger->info(
157 1
            'security.authentication.form: logout user with id {id}', ['id' => $id]
158
        );
159
160 1
        $this->session->remove($request, self::USER_KEY);
161 1
    }
162
163
    /**
164
     * @param Request $request
165
     *
166
     * @return bool
167
     */
168 2
    public function isAuthenticated(Request $request): bool
169
    {
170 2
        return null !== $this->getAuthenticatedUser($request);
171
    }
172
173
    /**
174
     * @param Request $request
175
     *
176
     * @return UserPasswordInterface|null
177
     */
178 5
    public function getAuthenticatedUser(Request $request)
179
    {
180 5
        if (!$this->checkForUserIdWithinSession($request)) {
181 2
            $this->logger->info('security.authentication.form: not authenticated');
182
183 2
            return null;
184
        }
185
186 3
        $id = $this->getUserIdFromSession($request);
187
188 3
        if (null === $user = $this->find($id)) {
189 1
            $this->logger->warning('security.authentication.form: user with id {id} is not resolvable', ['id' => $id]);
190 1
            $this->session->remove($request, self::USER_KEY);
191
192 1
            return null;
193
        }
194
195 2
        $this->logger->info('security.authentication.form: authenticated user with id {id}', ['id' => $id]);
196
197 2
        return $user;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $user; (Chubbyphp\Security\Authentication\UserInterface) is incompatible with the return type declared by the interface Chubbyphp\Security\Authe...e::getAuthenticatedUser of type Chubbyphp\Security\UserInterface|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
198
    }
199
200
    /**
201
     * @param Request $request
202
     *
203
     * @return bool
204
     */
205 7
    private function checkForUserIdWithinSession(Request $request): bool
206
    {
207 7
        return $this->session->has($request, self::USER_KEY);
208
    }
209
210
    /**
211
     * @param Request $request
212
     *
213
     * @return string
214
     */
215 4
    private function getUserIdFromSession(Request $request): string
216
    {
217 4
        return $this->session->get($request, self::USER_KEY);
218
    }
219
220
    /**
221
     * @param array $criteria
222
     *
223
     * @return string
224
     */
225 2
    private function getCriteriaAsSting(array $criteria): string
226
    {
227 2
        $criteriaString = '';
228 2
        foreach ($criteria as $key => $value) {
229 2
            $criteriaString .= $key.': '.$value.', ';
230
        }
231
232 2
        return substr($criteriaString, 0, -2);
233
    }
234
}
235