Passed
Push — master ( 23b55a...d3facb )
by Florian
03:55
created

PasswordAuthenticator::authenticateToken()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 23
rs 9.4555
c 0
b 0
f 0
cc 5
nc 5
nop 3
1
<?php
2
3
/*
4
 * This file is part of the feedback project.
5
 *
6
 * (c) Florian Moser <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace App\Security;
13
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
16
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
17
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
18
use Symfony\Component\Security\Core\User\UserInterface;
19
use Symfony\Component\Security\Core\User\UserProviderInterface;
20
use Symfony\Component\Security\Http\Authentication\SimpleFormAuthenticatorInterface;
21
22
class PasswordAuthenticator implements SimpleFormAuthenticatorInterface
23
{
24
    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
25
    {
26
        $user = $userProvider->loadUserByUsername($token->getUsername());
27
        $currentUser = $token->getUser();
28
29
        if ($currentUser instanceof UserInterface) {
30
            if ($currentUser->getPassword() !== $user->getPassword()) {
31
                throw new BadCredentialsException('The credentials were changed from another session.');
32
            }
33
        } else {
34
            if ('' === ($givenPassword = $token->getCredentials())) {
35
                throw new BadCredentialsException('The given password cannot be empty.');
36
            }
37
            if ($user->getPassword() !== $givenPassword) {
38
                throw new BadCredentialsException('The given password is invalid.');
39
            }
40
        }
41
42
        return new UsernamePasswordToken(
43
            $user,
44
            $user->getPassword(),
45
            $providerKey,
46
            $user->getRoles()
47
        );
48
    }
49
50
    public function supportsToken(TokenInterface $token, $providerKey)
51
    {
52
        return $token instanceof UsernamePasswordToken
53
            && $token->getProviderKey() === $providerKey;
54
    }
55
56
    public function createToken(Request $request, $username, $password, $providerKey)
57
    {
58
        return new UsernamePasswordToken($username, $password, $providerKey);
59
    }
60
}
61