LdapAuthenticationProvider::supports()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * This file is part of the LdapToolsBundle package.
4
 *
5
 * (c) Chad Sikorra <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LdapTools\Bundle\LdapToolsBundle\Security\Authentication\Provider;
12
13
use LdapTools\Bundle\LdapToolsBundle\Event\LdapLoginEvent;
14
use LdapTools\Bundle\LdapToolsBundle\Security\LdapAuthenticationTrait;
15
use LdapTools\Bundle\LdapToolsBundle\Security\User\LdapUserChecker;
16
use LdapTools\Bundle\LdapToolsBundle\Security\User\LdapUserProvider;
17
use LdapTools\Exception\LdapConnectionException;
18
use LdapTools\LdapManager;
19
use LdapTools\Operation\AuthenticationOperation;
20
use LdapTools\Operation\AuthenticationResponse;
21
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
22
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
23
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
24
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
25
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
26
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
27
use Symfony\Component\Security\Core\User\UserInterface;
28
use Symfony\Component\Security\Core\User\UserProviderInterface;
29
30
/**
31
 * Authenticate a user against LDAP.
32
 *
33
 * @author Chad Sikorra <[email protected]>
34
 */
35
class LdapAuthenticationProvider implements AuthenticationProviderInterface
36
{
37
    use LdapAuthenticationTrait;
38
39
    /**
40
     * @var UserProviderInterface
41
     */
42
    protected $userProvider;
43
44
    /**
45
     * @var bool
46
     */
47
    protected $hideUserNotFoundExceptions;
48
49
    /**
50
     * @var string
51
     */
52
    protected $providerKey;
53
54
    /**
55
     * @var LdapUserChecker
56
     */
57
    protected $userChecker;
58
59
    /**
60
     * @var EventDispatcherInterface
61
     */
62
    protected $dispatcher;
63
64
    /**
65
     * @var array
66
     */
67
    protected $options = [
68
        'login_query_attribute' => null,
69
    ];
70
71
    /**
72
     * @param string $providerKey
73
     * @param bool $hideUserNotFoundExceptions
74
     * @param UserProviderInterface $userProvider
75
     * @param LdapUserChecker $userChecker
76
     * @param LdapManager $ldap
77
     * @param EventDispatcherInterface $dispatcher
78
     * @param LdapUserProvider $ldapUserProvider
79
     * @param array $options
80
     */
81
    public function __construct(
82
        $providerKey,
83
        $hideUserNotFoundExceptions = true,
84
        UserProviderInterface $userProvider,
85
        LdapUserChecker $userChecker,
86
        LdapManager $ldap,
87
        EventDispatcherInterface $dispatcher,
88
        LdapUserProvider $ldapUserProvider,
89
        array $options
90
    ) {
91
        $this->userProvider = $userProvider;
92
        $this->ldap = $ldap;
93
        $this->hideUserNotFoundExceptions = $hideUserNotFoundExceptions;
94
        $this->providerKey = $providerKey;
95
        $this->userChecker = $userChecker;
96
        $this->dispatcher = $dispatcher;
97
        $this->ldapUserProvider = $ldapUserProvider;
98
        $this->options = array_merge($this->options, $options);
99
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104
    public function authenticate(TokenInterface $token)
105
    {
106
        $domain = $this->ldap->getDomainContext();
107
108
        try {
109
            $this->switchDomainIfNeeded($this->getDomainFromToken($token));
110
            $this->setLdapCredentialsIfNeeded($token->getUsername(), $token->getCredentials(), $this->userProvider);
111
            $user = $this->userProvider->loadUserByUsername($token->getUsername());
112
            $this->userChecker->checkPreAuth($user);
113
            $token = $this->doAuthentication($user, $token);
114
            $this->userChecker->checkPostAuth($user);
115
        } catch (UsernameNotFoundException $e) {
116
            $this->hideOrThrow($e, $this->hideUserNotFoundExceptions);
117
        } catch (BadCredentialsException $e) {
118
            $this->hideOrThrow($e, $this->hideUserNotFoundExceptions);
119
        } catch (LdapConnectionException $e) {
120
            $this->hideOrThrow($e, $this->hideUserNotFoundExceptions);
121
        } finally {
122
            $this->switchDomainBackIfNeeded($domain);
123
        }
124
125
        return $token;
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    public function supports(TokenInterface $token)
132
    {
133
        return ($token instanceof UsernamePasswordToken);
134
    }
135
136
    /**
137
     * @param UserInterface $user
138
     * @param TokenInterface $token
139
     * @return UsernamePasswordToken
140
     */
141
    protected function doAuthentication(UserInterface $user, TokenInterface $token)
142
    {
143
        $auth = new AuthenticationOperation(
144
            $this->getBindUsername($user, $this->options['login_query_attribute']),
145
            $token->getCredentials()
146
        );
147
        /** @var AuthenticationResponse $response */
148
        $response = $this->ldap->getConnection()->execute($auth);
149
150 View Code Duplication
        if (!$response->isAuthenticated()) {
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...
151
            $this->userChecker->checkLdapErrorCode(
152
                $user,
153
                $response->getErrorCode(),
154
                $this->ldap->getConnection()->getConfig()->getLdapType()
155
            );
156
157
            throw new BadCredentialsException($response->getErrorMessage(), $response->getErrorCode());
158
        }
159
        $this->dispatcher->dispatch(LdapLoginEvent::SUCCESS, new LdapLoginEvent($user, $token));
160
161
        $newToken = new UsernamePasswordToken($user, null, $this->providerKey, $user->getRoles());
162
        $newToken->setAttributes($token->getAttributes());
163
164
        return $newToken;
165
    }
166
167
    /**
168
     * @param TokenInterface $token
169
     * @return string
170
     */
171
    protected function getDomainFromToken(TokenInterface $token)
172
    {
173
        return $token->hasAttribute('ldap_domain') ? $token->getAttribute('ldap_domain') : '';
174
    }
175
}
176