Completed
Pull Request — master (#70)
by
unknown
13:27
created

FormAuthenticator::supports()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 2
nop 1
1
<?php
2
3
namespace SumoCoders\FrameworkMultiUserBundle\Security;
4
5
use SumoCoders\FrameworkMultiUserBundle\User\Interfaces\User;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
8
use Symfony\Component\Security\Core\User\UserProviderInterface;
9
use Symfony\Component\Security\Core\User\UserInterface;
10
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
11
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
12
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
13
use Symfony\Component\Routing\RouterInterface;
14
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
15
use Symfony\Component\HttpFoundation\RedirectResponse;
16
use Symfony\Component\Translation\TranslatorInterface;
17
18
class FormAuthenticator extends AbstractFormLoginAuthenticator
19
{
20
    /** @var UserPasswordEncoderInterface */
21
    private $passwordEncoder;
22
23
    /** @var RouterInterface */
24
    private $router;
25
26
    /** @var FlashBagInterface */
27
    private $flashBag;
28
29
    /** @var TranslatorInterface */
30
    private $translator;
31
32
    /** array */
33
    private $redirectRoutes = [];
34
35
    public function __construct(
36
        UserPasswordEncoderInterface $passwordEncoder,
37
        RouterInterface $router,
38
        FlashBagInterface $flashBag,
39
        TranslatorInterface $translator,
40
        array $redirectRoutes = []
41
    ) {
42
        $this->passwordEncoder = $passwordEncoder;
43
        $this->router = $router;
44
        $this->flashBag = $flashBag;
45
        $this->translator = $translator;
46
        $this->redirectRoutes = $redirectRoutes;
47
    }
48
49
    public function getCredentials(Request $request): ?FormCredentials
50
    {
51
        if ($request->getPathInfo() !== $this->getLoginUrl()
52
            || !$request->isMethod(Request::METHOD_POST)) {
53
            return null;
54
        }
55
56
        return new FormCredentials(
57
            $request->request->get('_username'),
58
            $request->request->get('_password')
59
        );
60
    }
61
62
    public function getUser($credentials, UserProviderInterface $userProvider): User
63
    {
64
        return $userProvider->loadUserByUsername($credentials->getUsername());
65
    }
66
67
    /**
68
     * @param FormCredentials $credentials
69
     * @param UserInterface $user
70
     *
71
     * @return bool
72
     *
73
     * @throws BadCredentialsException
74
     */
75
    public function checkCredentials($credentials, UserInterface $user): bool
76
    {
77
        $plainPassword = $credentials->getPlainPassword();
78
        $encoder = $this->passwordEncoder;
79
80
        if (!$encoder->isPasswordValid($user, $plainPassword)) {
81
            throw new BadCredentialsException();
82
        }
83
84
        return true;
85
    }
86
87
    public function supports(Request $request)
88
    {
89
        return $request->getBasePath() === '/login' && $request->isMethod('POST');
90
    }
91
92
    protected function getLoginUrl(): string
93
    {
94
        return $this->router->generate('multi_user_login');
95
    }
96
97
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey): RedirectResponse
98
    {
99
        // if the user hit a secure page and start() was called, this was
100
        // the URL they were on, and probably where you want to redirect to
101
        $targetPath = $request->getSession()->get('_security.'.$providerKey.'.target_path');
102
103
        if (!$targetPath) {
104
            $targetPath = $this->getSuccessRedirectUrl($token);
105
        }
106
107
        $this->flashBag->add(
108
            'success',
109
            $this->translator->trans(
110
                'sumocoders.multiuserbundle.flash.login_success',
111
                [
112
                    '%username%' => $token->getUsername(),
113
                ]
114
            )
115
        );
116
117
        return new RedirectResponse($targetPath);
118
    }
119
120
    public function getSuccessRedirectUrl(TokenInterface $token): string
121
    {
122
        foreach ($this->redirectRoutes as $class => $route) {
123
            if (get_class($token->getUser()) === $class) {
124
                return $this->router->generate($route['route']);
125
            }
126
        }
127
128
        return $this->getDefaultSuccessRedirectURL();
129
    }
130
131
    protected function getDefaultSuccessRedirectURL(): string
132
    {
133
        return '/';
134
    }
135
}
136