Completed
Push — master ( b9ba69...95d823 )
by Chad
02:04
created

LdapUserProvider::setAttributes()   A

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\User;
12
13
use LdapTools\BatchModify\BatchCollection;
14
use LdapTools\Bundle\LdapToolsBundle\Event\LoadUserEvent;
15
use LdapTools\Exception\EmptyResultException;
16
use LdapTools\Exception\MultiResultException;
17
use LdapTools\LdapManager;
18
use LdapTools\Object\LdapObject;
19
use LdapTools\Object\LdapObjectType;
20
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
21
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
22
use Symfony\Component\Security\Core\User\UserInterface;
23
use Symfony\Component\Security\Core\User\UserProviderInterface;
24
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
25
26
/**
27
 * Loads a user from LDAP.
28
 *
29
 * @author Chad Sikorra <[email protected]>
30
 */
31
class LdapUserProvider implements UserProviderInterface
32
{
33
    /**
34
     * @var LdapManager
35
     */
36
    protected $ldap;
37
38
    /**
39
     * @var EventDispatcherInterface
40
     */
41
    protected $dispatcher;
42
43
    /**
44
     * @var LdapRoleMapper
45
     */
46
    protected $roleMapper;
47
48
    /**
49
     * @var array Default attributes selected for the Advanced User Interface.
50
     */
51
    protected $defaultAttributes = [
52
        'username',
53
        'guid',
54
        'accountExpirationDate',
55
        'enabled',
56
        'groups',
57
        'locked',
58
        'passwordMustChange',
59
    ];
60
61
    /**
62
     * @var array Any additional LDAP attributes to select.
63
     */
64
    protected $additionalAttributes = [];
65
66
    /**
67
     * @var string
68
     */
69
    protected $userClass = LdapUser::class;
70
71
    /**
72
     * @var string The object type to search LDAP for.
73
     */
74
    protected $ldapObjectType = LdapObjectType::USER;
75
    
76
    /**
77
     * @var string The container/OU to search for the user under.
78
     */
79
    protected $searchBase;
80
81
    /**
82
     * @var bool Whether or not user attributes should be re-queried on a refresh.
83
     */
84
    protected $refreshAttributes = true;
85
86
    /**
87
     * @var bool Whether or not user roles should be re-queried on a refresh.
88
     */
89
    protected $refreshRoles = true;
90
91
    /**
92
     * @param LdapManager $ldap
93
     * @param EventDispatcherInterface $dispatcher
94
     * @param LdapRoleMapper $roleMapper
95
     */
96
    public function __construct(LdapManager $ldap, EventDispatcherInterface $dispatcher, LdapRoleMapper $roleMapper)
97
    {
98
        $this->ldap = $ldap;
99
        $this->dispatcher = $dispatcher;
100
        $this->roleMapper = $roleMapper;
101
    }
102
103
    /**
104
     * Set the user class to be instantiated and returned from the LDAP provider.
105
     *
106
     * @param string $class
107
     */
108
    public function setUserClass($class)
109
    {
110
        if (!$this->supportsClass($class)) {
111
            throw new UnsupportedUserException(sprintf(
112
                'The LDAP user provider class "%s" must implement "%s".',
113
                $class,
114
                LdapUserInterface::class
115
            ));
116
        }
117
118
        $this->userClass = $class;
119
    }
120
121
    /**
122
     * Set any additional attributes to be selected for the LDAP user.
123
     *
124
     * @param array $attributes
125
     */
126
    public function setAttributes(array $attributes)
127
    {
128
        $this->additionalAttributes = $attributes;
129
    }
130
131
    /**
132
     * Set the LDAP object type that will be searched for.
133
     *
134
     * @param string $type
135
     */
136
    public function setLdapObjectType($type)
137
    {
138
        $this->ldapObjectType = $type;
139
    }
140
141
    /**
142
     * @param string $searchBase
143
     */
144
    public function setSearchBase($searchBase)
145
    {
146
        $this->searchBase = $searchBase;
147
    }
148
149
    /**
150
     * @param bool $refreshRoles
151
     */
152
    public function setRefreshRoles($refreshRoles)
153
    {
154
        $this->refreshRoles = $refreshRoles;
155
    }
156
157
    /**
158
     * @param bool $refreshAttributes
159
     */
160
    public function setRefreshAttributes($refreshAttributes)
161
    {
162
        $this->refreshAttributes = $refreshAttributes;
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function loadUserByUsername($username)
169
    {
170
        $this->dispatcher->dispatch(LoadUserEvent::BEFORE, new LoadUserEvent($username, $this->ldap->getDomainContext()));
171
        $ldapUser = $this->getLdapUser('username', $username);
172
        $user = $this->constructUserClass($ldapUser);
173
        $this->roleMapper->setRoles($user);
174
        $this->dispatcher->dispatch(LoadUserEvent::AFTER, new LoadUserEvent($username, $this->ldap->getDomainContext(), $user, $ldapUser));
0 ignored issues
show
Documentation introduced by
$user is of type object<LdapTools\Bundle\...User\LdapUserInterface>, but the function expects a null|object<Symfony\Comp...ore\User\UserInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
175
176
        return $user;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $user; (LdapTools\Bundle\LdapToo...\User\LdapUserInterface) is incompatible with the return type declared by the interface Symfony\Component\Securi...ace::loadUserByUsername of type Symfony\Component\Security\Core\User\UserInterface.

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...
177
    }
178
179
    /**
180
     * {@inheritdoc}
181
     */
182
    public function refreshUser(UserInterface $user)
183
    {
184
        if (!$user instanceof LdapUserInterface) {
185
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
186
        }
187
        $roles = $user->getRoles();
188
189
        if ($this->refreshAttributes) {
190
            $user = $this->constructUserClass($this->getLdapUser('guid', $user->getLdapGuid()));
191
        }
192
        if ($this->refreshRoles) {
193
            $this->roleMapper->setRoles($user);
194
        } else {
195
            $user->setRoles($roles);
196
        }
197
198
        return $user;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $user; (LdapTools\Bundle\LdapToo...\User\LdapUserInterface) is incompatible with the return type declared by the interface Symfony\Component\Securi...rInterface::refreshUser of type Symfony\Component\Security\Core\User\UserInterface.

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...
199
    }
200
201
    /**
202
     * {@inheritdoc}
203
     */
204
    public function supportsClass($class)
205
    {
206
        return is_subclass_of($class, LdapUserInterface::class);
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \LdapTools\Bundle\LdapTo...dapUserInterface::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
207
    }
208
209
    /**
210
     * Search for, and return, the LDAP user by a specific attribute.
211
     *
212
     * @param string $attribute
213
     * @param string $value
214
     * @return LdapObject
215
     */
216
    protected function getLdapUser($attribute, $value)
217
    {
218
        try {
219
            $query = $this->ldap->buildLdapQuery()
220
                ->select($this->getAttributesToSelect())
221
                ->from($this->ldapObjectType)
222
                ->where([$attribute => $value]);
223
            if (!is_null($this->searchBase)) {
224
                $query->setBaseDn($this->searchBase);
225
            }
226
            return $query->getLdapQuery()->getSingleResult();
0 ignored issues
show
Bug Compatibility introduced by
The expression $query->getLdapQuery()->getSingleResult(); of type array|LdapTools\Object\LdapObject adds the type array to the return on line 226 which is incompatible with the return type documented by LdapTools\Bundle\LdapToo...erProvider::getLdapUser of type LdapTools\Object\LdapObject.
Loading history...
227
        } catch (EmptyResultException $e) {
228
            throw new UsernameNotFoundException(sprintf('Username "%s" was not found.', $value));
229
        } catch (MultiResultException $e) {
230
            throw new UsernameNotFoundException(sprintf('Multiple results for "%s" were found.', $value));
231
        }
232
    }
233
234
    /**
235
     * Get all the attributes that should be selected for when querying LDAP.
236
     *
237
     * @return array
238
     */
239
    protected function getAttributesToSelect()
240
    {
241
        return array_values(array_unique(array_filter(array_merge(
242
            $this->defaultAttributes,
243
            $this->additionalAttributes
244
        ))));
245
    }
246
247
    /**
248
     * @param LdapObject $ldapObject
249
     * @return LdapUserInterface
250
     */
251
    protected function constructUserClass(LdapObject $ldapObject)
252
    {
253
        $errorMessage = 'Unable to instantiate user class "%s". Error was: %s';
254
255
        try {
256
            /** @var LdapUserInterface $user */
257
            $user = new $this->userClass();
258
            $user->setUsername($ldapObject->get('username'));
259
            $user->setLdapGuid($ldapObject->get('guid'));
260
        } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
261
            throw new UnsupportedUserException(sprintf($errorMessage, $this->userClass, $e->getMessage()));
262
        // Unlikely to help much in PHP 5.6, but oh well...
263
        } catch (\Exception $e) {
264
            throw new UnsupportedUserException(sprintf($errorMessage, $this->userClass, $e->getMessage()));
265
        }
266
        // If the class also happens to extends the LdapTools LdapObject class, then set the attributes and type...
267
        if ($user instanceof LdapObject) {
268
            $user->setBatchCollection(new BatchCollection($ldapObject->get('dn')));
269
            $user->refresh($ldapObject->toArray());
270
            // This is to avoid the constructor
271
            $refObject = new \ReflectionObject($user);
272
            $refProperty = $refObject->getProperty('type');
273
            $refProperty->setAccessible(true);
274
            $refProperty->setValue($user, $this->ldapObjectType);
275
        }
276
277
        return $user;
278
    }
279
}
280