Completed
Pull Request — master (#100)
by Robbie
08:07
created

LDAPService::getGroups()   D

Complexity

Conditions 9
Paths 8

Size

Total Lines 29
Code Lines 17

Duplication

Lines 10
Ratio 34.48 %

Importance

Changes 0
Metric Value
dl 10
loc 29
rs 4.909
c 0
b 0
f 0
cc 9
eloc 17
nc 8
nop 3
1
<?php
2
3
namespace SilverStripe\ActiveDirectory\Services;
4
5
use Exception;
6
use Psr\Log\LoggerInterface;
7
use Psr\SimpleCache\CacheInterface;
8
use SilverStripe\ActiveDirectory\Model\LDAPGateway;
9
use SilverStripe\ActiveDirectory\Model\LDAPGroupMapping;
10
use SilverStripe\Assets\Image;
11
use SilverStripe\Assets\Filesystem;
12
use SilverStripe\Core\Config\Config;
13
use SilverStripe\Core\Flushable;
14
use SilverStripe\Core\Injector\Injector;
15
use SilverStripe\Core\Object;
16
use SilverStripe\ORM\DB;
17
use SilverStripe\ORM\FieldType\DBDatetime;
18
use SilverStripe\ORM\ValidationException;
19
use SilverStripe\ORM\ValidationResult;
20
use SilverStripe\Security\Group;
21
use SilverStripe\Security\Member;
22
use SilverStripe\Security\RandomGenerator;
23
use Zend\Ldap\Ldap;
24
25
/**
26
 * Class LDAPService
27
 *
28
 * Provides LDAP operations expressed in terms of the SilverStripe domain.
29
 * All other modules should access LDAP through this class.
30
 *
31
 * This class builds on top of LDAPGateway's detailed code by adding:
32
 * - caching
33
 * - data aggregation and restructuring from multiple lower-level calls
34
 * - error handling
35
 *
36
 * LDAPService relies on Zend LDAP module's data structures for some parameters and some return values.
37
 *
38
 * @package activedirectory
39
 */
40
class LDAPService extends Object implements Flushable
41
{
42
    /**
43
     * @var array
44
     */
45
    private static $dependencies = [
0 ignored issues
show
Unused Code introduced by
The property $dependencies is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
46
        'gateway' => '%$' . LDAPGateway::class
47
    ];
48
49
    /**
50
     * If configured, only user objects within these locations will be exposed to this service.
51
     *
52
     * @var array
53
     * @config
54
     */
55
    private static $users_search_locations = [];
0 ignored issues
show
Unused Code introduced by
The property $users_search_locations is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
56
57
    /**
58
     * If configured, only group objects within these locations will be exposed to this service.
59
     * @var array
60
     *
61
     * @config
62
     */
63
    private static $groups_search_locations = [];
0 ignored issues
show
Unused Code introduced by
The property $groups_search_locations is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
64
65
    /**
66
     * Location to create new users in (distinguished name).
67
     * @var string
68
     *
69
     * @config
70
     */
71
    private static $new_users_dn;
0 ignored issues
show
Unused Code introduced by
The property $new_users_dn is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
72
73
    /**
74
     * Location to create new groups in (distinguished name).
75
     * @var string
76
     *
77
     * @config
78
     */
79
    private static $new_groups_dn;
0 ignored issues
show
Unused Code introduced by
The property $new_groups_dn is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
80
81
    /**
82
     * @var array
83
     */
84
    private static $_cache_nested_groups = [];
85
86
    /**
87
     * If this is configured to a "Code" value of a {@link Group} in SilverStripe, the user will always
88
     * be added to this group's membership when imported, regardless of any sort of group mappings.
89
     *
90
     * @var string
91
     * @config
92
     */
93
    private static $default_group;
0 ignored issues
show
Unused Code introduced by
The property $default_group is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
94
95
    /**
96
     * For samba4 directory, there is no way to enforce password history on password resets.
97
     * This only happens with changePassword (which requires the old password).
98
     * This works around it by making the old password up and setting it administratively.
99
     *
100
     * A cleaner fix would be to use the LDAP_SERVER_POLICY_HINTS_OID connection flag,
101
     * but it's not implemented in samba https://bugzilla.samba.org/show_bug.cgi?id=12020
102
     *
103
     * @var bool
104
     */
105
    private static $password_history_workaround = false;
0 ignored issues
show
Unused Code introduced by
The property $password_history_workaround is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
106
107
    /**
108
     * Get the cache object used for LDAP results. Note that the default lifetime set here
109
     * is 8 hours, but you can change that by adding configuration:
110
     *
111
     * <code>
112
     * SilverStripe\Core\Injector\Injector:
113
     *   Psr\SimpleCache\CacheInterface.ldap:
114
     *     constructor:
115
     *       defaultLifetime: 3600 # time in seconds
116
     * </code>
117
     *
118
     * @return Psr\SimpleCache\CacheInterface
119
     */
120
    public static function get_cache()
121
    {
122
        return Injector::inst()->get(CacheInterface::class . '.ldap');
123
    }
124
125
    /**
126
     * Flushes out the LDAP results cache when flush=1 is called.
127
     */
128
    public static function flush()
129
    {
130
        /** @var CacheInterface $cache */
131
        $cache = self::get_cache();
132
        $cache->clear();
133
    }
134
135
    /**
136
     * @var LDAPGateway
137
     */
138
    public $gateway;
139
140
    /**
141
     * Setter for gateway. Useful for overriding the gateway with a fake for testing.
142
     * @var LDAPGateway
143
     */
144
    public function setGateway($gateway)
145
    {
146
        $this->gateway = $gateway;
147
    }
148
149
    /**
150
     * Checkes whether or not the service is enabled.
151
     *
152
     * @return bool
153
     */
154
    public function enabled()
155
    {
156
        $options = Config::inst()->get(LDAPGateway::class, 'options');
157
        return !empty($options);
158
    }
159
160
    /**
161
     * Authenticate the given username and password with LDAP.
162
     *
163
     * @param string $username
164
     * @param string $password
165
     *
166
     * @return array
167
     */
168
    public function authenticate($username, $password)
169
    {
170
        $result = $this->gateway->authenticate($username, $password);
171
        $messages = $result->getMessages();
172
173
        // all messages beyond the first one are for debugging and
174
        // not suitable to display to the user.
175
        foreach ($messages as $i => $message) {
176
            if ($i > 0) {
177
                $this->getLogger()->debug(str_replace("\n", "\n  ", $message));
178
            }
179
        }
180
181
        $message = $messages[0]; // first message is user readable, suitable for showing on login form
182
183
        // show better errors than the defaults for various status codes returned by LDAP
184 View Code Duplication
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_ACCOUNT_LOCKED_OUT') !== false) {
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...
185
            $message = _t(
186
                'LDAPService.ACCOUNTLOCKEDOUT',
187
                'Your account has been temporarily locked because of too many failed login attempts. ' .
188
                'Please try again later.'
189
            );
190
        }
191 View Code Duplication
        if (!empty($messages[1]) && strpos($messages[1], 'NT_STATUS_LOGON_FAILURE') !== false) {
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...
192
            $message = _t(
193
                'LDAPService.INVALIDCREDENTIALS',
194
                'The provided details don\'t seem to be correct. Please try again.'
195
            );
196
        }
197
198
        return [
199
            'success' => $result->getCode() === 1,
200
            'identity' => $result->getIdentity(),
201
            'message' => $message
202
        ];
203
    }
204
205
    /**
206
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
207
     *
208
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
209
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
210
     * @return array
211
     */
212
    public function getNodes($cached = true, $attributes = [])
213
    {
214
        $cache = self::get_cache();
215
        $cacheKey = 'nodes' . md5(implode('', $attributes));
216
        $results = $cache->has($cacheKey);
217
218
        if (!$results || !$cached) {
219
            $results = [];
220
            $records = $this->gateway->getNodes(null, Ldap::SEARCH_SCOPE_SUB, $attributes);
221
            foreach ($records as $record) {
222
                $results[$record['dn']] = $record;
223
            }
224
225
            $cache->set($cacheKey, $results);
226
        }
227
228
        return $results;
229
    }
230
231
    /**
232
     * Return all AD groups in configured search locations, including all nested groups.
233
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
234
     * to use the default baseDn defined in the connection.
235
     *
236
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
237
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
238
     * @param string $indexBy Attribute to use as an index.
239
     * @return array
240
     */
241
    public function getGroups($cached = true, $attributes = [], $indexBy = 'dn')
242
    {
243
        $searchLocations = $this->config()->groups_search_locations ?: [null];
244
        $cache = self::get_cache();
245
        $cacheKey = 'groups' . md5(implode('', array_merge($searchLocations, $attributes)));
246
        $results = $cache->has($cacheKey);
247
248
        if (!$results || !$cached) {
249
            $results = [];
250 View Code Duplication
            foreach ($searchLocations as $searchLocation) {
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...
251
                $records = $this->gateway->getGroups($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
252
                if (!$records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
253
                    continue;
254
                }
255
256
                foreach ($records as $record) {
257
                    $results[$record[$indexBy]] = $record;
258
                }
259
            }
260
261
            $cache->set($cacheKey, $results);
262
        }
263
264
        if ($cached && $results === true) {
265
            $results = $cache->get($cacheKey);
266
        }
267
268
        return $results;
269
    }
270
271
    /**
272
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
273
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
274
     *
275
     * @param string $dn
276
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
277
     * @return array
278
     */
279
    public function getNestedGroups($dn, $attributes = [])
280
    {
281
        if (isset(self::$_cache_nested_groups[$dn])) {
282
            return self::$_cache_nested_groups[$dn];
283
        }
284
285
        $searchLocations = $this->config()->groups_search_locations ?: [null];
286
        $results = [];
287 View Code Duplication
        foreach ($searchLocations as $searchLocation) {
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...
288
            $records = $this->gateway->getNestedGroups($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
289
            foreach ($records as $record) {
290
                $results[$record['dn']] = $record;
291
            }
292
        }
293
294
        self::$_cache_nested_groups[$dn] = $results;
295
        return $results;
296
    }
297
298
    /**
299
     * Get a particular AD group's data given a GUID.
300
     *
301
     * @param string $guid
302
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
303
     * @return array
304
     */
305 View Code Duplication
    public function getGroupByGUID($guid, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
306
    {
307
        $searchLocations = $this->config()->groups_search_locations ?: [null];
308
        foreach ($searchLocations as $searchLocation) {
309
            $records = $this->gateway->getGroupByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
310
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
311
                return $records[0];
312
            }
313
        }
314
    }
315
316
    /**
317
     * Get a particular AD group's data given a DN.
318
     *
319
     * @param string $dn
320
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
321
     * @return array
322
     */
323 View Code Duplication
    public function getGroupByDN($dn, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
324
    {
325
        $searchLocations = $this->config()->groups_search_locations ?: [null];
326
        foreach ($searchLocations as $searchLocation) {
327
            $records = $this->gateway->getGroupByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
328
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
329
                return $records[0];
330
            }
331
        }
332
    }
333
334
    /**
335
     * Return all AD users in configured search locations, including all users in nested groups.
336
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
337
     * to use the default baseDn defined in the connection.
338
     *
339
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
340
     * @return array
341
     */
342
    public function getUsers($attributes = [])
343
    {
344
        $searchLocations = $this->config()->users_search_locations ?: [null];
345
        $results = [];
346
347 View Code Duplication
        foreach ($searchLocations as $searchLocation) {
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...
348
            $records = $this->gateway->getUsers($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
349
            if (!$records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
350
                continue;
351
            }
352
353
            foreach ($records as $record) {
354
                $results[$record['objectguid']] = $record;
355
            }
356
        }
357
358
        return $results;
359
    }
360
361
    /**
362
     * Get a specific AD user's data given a GUID.
363
     *
364
     * @param string $guid
365
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
366
     * @return array
367
     */
368 View Code Duplication
    public function getUserByGUID($guid, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
369
    {
370
        $searchLocations = $this->config()->users_search_locations ?: [null];
371
        foreach ($searchLocations as $searchLocation) {
372
            $records = $this->gateway->getUserByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
373
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
374
                return $records[0];
375
            }
376
        }
377
    }
378
379
    /**
380
     * Get a specific AD user's data given a DN.
381
     *
382
     * @param string $dn
383
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
384
     *
385
     * @return array
386
     */
387 View Code Duplication
    public function getUserByDN($dn, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
388
    {
389
        $searchLocations = $this->config()->users_search_locations ?: [null];
390
        foreach ($searchLocations as $searchLocation) {
391
            $records = $this->gateway->getUserByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
392
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
393
                return $records[0];
394
            }
395
        }
396
    }
397
398
    /**
399
     * Get a specific user's data given an email.
400
     *
401
     * @param string $email
402
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
403
     * @return array
404
     */
405 View Code Duplication
    public function getUserByEmail($email, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
406
    {
407
        $searchLocations = $this->config()->users_search_locations ?: [null];
408
        foreach ($searchLocations as $searchLocation) {
409
            $records = $this->gateway->getUserByEmail($email, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
410
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
411
                return $records[0];
412
            }
413
        }
414
    }
415
416
    /**
417
     * Get a specific user's data given a username.
418
     *
419
     * @param string $username
420
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
421
     * @return array
422
     */
423 View Code Duplication
    public function getUserByUsername($username, $attributes = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
424
    {
425
        $searchLocations = $this->config()->users_search_locations ?: [null];
426
        foreach ($searchLocations as $searchLocation) {
427
            $records = $this->gateway->getUserByUsername($username, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
428
            if ($records) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $records of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
429
                return $records[0];
430
            }
431
        }
432
    }
433
434
    /**
435
     * Get a username for an email.
436
     *
437
     * @param string $email
438
     * @return string|null
439
     */
440
    public function getUsernameByEmail($email)
441
    {
442
        $data = $this->getUserByEmail($email);
443
        if (empty($data)) {
444
            return null;
445
        }
446
447
        return $this->gateway->getCanonicalUsername($data);
448
    }
449
450
    /**
451
     * Given a group DN, get the group membership data in LDAP.
452
     *
453
     * @param string $dn
454
     * @return array
455
     */
456
    public function getLDAPGroupMembers($dn)
457
    {
458
        $groupObj = Group::get()->filter('DN', $dn)->first();
459
        $groupData = $this->getGroupByGUID($groupObj->GUID);
460
        $members = !empty($groupData['member']) ? $groupData['member'] : [];
461
        // If a user belongs to a single group, this comes through as a string.
462
        // Normalise to a array so it's consistent.
463
        if ($members && is_string($members)) {
464
            $members = [$members];
465
        }
466
467
        return $members;
468
    }
469
470
    /**
471
     * Update the current Member record with data from LDAP.
472
     *
473
     * Constraints:
474
     * - Member *must* be in the database before calling this as it will need the ID to be mapped to a {@link Group}.
475
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
476
     *
477
     * @param Member
478
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
479
     *            If not given, the data will be looked up by the user's GUID.
480
     * @return bool
481
     */
482
    public function updateMemberFromLDAP(Member $member, $data = null)
483
    {
484
        if (!$this->enabled()) {
485
            return false;
486
        }
487
488
        if (!$member->GUID) {
489
            $this->getLogger()->warn(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method warn() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
490
            return false;
491
        }
492
493
        if (!$data) {
494
            $data = $this->getUserByGUID($member->GUID);
495
            if (!$data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
496
                $this->getLogger()->warn(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method warn() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
497
                return false;
498
            }
499
        }
500
501
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
502
        $member->LastSynced = (string)DBDatetime::now();
503
504
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
505
            if (!isset($data[$attribute])) {
506
                $this->getLogger()->notice(
507
                    sprintf(
508
                        'Attribute %s configured in Member.ldap_field_mappings, but no available attribute in AD data (GUID: %s, Member ID: %s)',
509
                        $attribute,
510
                        $data['objectguid'],
511
                        $member->ID
512
                    )
513
                );
514
515
                continue;
516
            }
517
518
            if ($attribute == 'thumbnailphoto') {
519
                $imageClass = $member->getRelationClass($field);
520
                if ($imageClass !== Image::class
521
                    && !is_subclass_of($imageClass, Image::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 \SilverStripe\Assets\Image::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
522
                ) {
523
                    $this->getLogger()->warn(
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method warn() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
524
                        sprintf(
525
                            'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an Image class',
526
                            $field
527
                        )
528
                    );
529
530
                    continue;
531
                }
532
533
                $filename = sprintf('thumbnailphoto-%s.jpg', $data['samaccountname']);
534
                $path = ASSETS_DIR . '/' . $member->config()->ldap_thumbnail_path;
535
                $absPath = BASE_PATH . '/' . $path;
536
                if (!file_exists($absPath)) {
537
                    Filesystem::makeFolder($absPath);
538
                }
539
540
                // remove existing record if it exists
541
                $existingObj = $member->getComponent($field);
542
                if ($existingObj && $existingObj->exists()) {
543
                    $existingObj->delete();
544
                }
545
546
                // The image data is provided in raw binary.
547
                file_put_contents($absPath . '/' . $filename, $data[$attribute]);
548
                $record = new $imageClass();
549
                $record->Name = $filename;
550
                $record->Filename = $path . '/' . $filename;
551
                $record->write();
552
553
                $relationField = $field . 'ID';
554
                $member->{$relationField} = $record->ID;
555
            } else {
556
                $member->$field = $data[$attribute];
557
            }
558
        }
559
560
        // if a default group was configured, ensure the user is in that group
561
        if ($this->config()->default_group) {
562
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
563
            if (!($group && $group->exists())) {
564
                $this->getLogger()->warn(
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method warn() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
565
                    sprintf(
566
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
567
                        $this->config()->default_group
568
                    )
569
                );
570
            } else {
571
                $group->Members()->add($member, [
572
                    'IsImportedFromLDAP' => '1'
573
                ]);
574
            }
575
        }
576
577
        // this is to keep track of which groups the user gets mapped to
578
        // and we'll use that later to remove them from any groups that they're no longer mapped to
579
        $mappedGroupIDs = [];
580
581
        // ensure the user is in any mapped groups
582
        if (isset($data['memberof'])) {
583
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : [$data['memberof']];
584
            foreach ($ldapGroups as $groupDN) {
585
                foreach (LDAPGroupMapping::get() as $mapping) {
586
                    if (!$mapping->DN) {
587
                        $this->getLogger()->warn(
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method warn() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
588
                            sprintf(
589
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
590
                                $mapping->ID
591
                            )
592
                        );
593
                        continue;
594
                    }
595
596
                    // the user is a direct member of group with a mapping, add them to the SS group.
597 View Code Duplication
                    if ($mapping->DN == $groupDN) {
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...
598
                        $group = $mapping->Group();
599
                        if ($group && $group->exists()) {
600
                            $group->Members()->add($member, [
601
                                'IsImportedFromLDAP' => '1'
602
                            ]);
603
                            $mappedGroupIDs[] = $mapping->GroupID;
604
                        }
605
                    }
606
607
                    // the user *might* be a member of a nested group provided the scope of the mapping
608
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
609
                    // to see if they are a member of one of those. If they are, add them to the SS group
610
                    if ($mapping->Scope == 'Subtree') {
611
                        $childGroups = $this->getNestedGroups($mapping->DN, ['dn']);
612
                        if (!$childGroups) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $childGroups of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
613
                            continue;
614
                        }
615
616
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
617 View Code Duplication
                            if ($childGroupDN == $groupDN) {
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...
618
                                $group = $mapping->Group();
619
                                if ($group && $group->exists()) {
620
                                    $group->Members()->add($member, [
621
                                        'IsImportedFromLDAP' => '1'
622
                                    ]);
623
                                    $mappedGroupIDs[] = $mapping->GroupID;
624
                                }
625
                            }
626
                        }
627
                    }
628
                }
629
            }
630
        }
631
632
        // remove the user from any previously mapped groups, where the mapping has since been removed
633
        $groupRecords = DB::query(
634
            sprintf(
635
                'SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s',
636
                $member->ID
637
            )
638
        );
639
640
        foreach ($groupRecords as $groupRecord) {
641
            if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
642
                $group = Group::get()->byId($groupRecord['GroupID']);
643
                // Some groups may no longer exist. SilverStripe does not clean up join tables.
644
                if ($group) {
645
                    $group->Members()->remove($member);
646
                }
647
            }
648
        }
649
        // This will throw an exception if there are two distinct GUIDs with the same email address.
650
        // We are happy with a raw 500 here at this stage.
651
        $member->write();
652
    }
653
654
    /**
655
     * Sync a specific Group by updating it with LDAP data.
656
     *
657
     * @param Group $group An existing Group or a new Group object
658
     * @param array $data LDAP group object data
659
     *
660
     * @return bool
661
     */
662
    public function updateGroupFromLDAP(Group $group, $data)
663
    {
664
        if (!$this->enabled()) {
665
            return false;
666
        }
667
668
        // Synchronise specific guaranteed fields.
669
        $group->Code = $data['samaccountname'];
670
        $group->Title = $data['samaccountname'];
671
        if (!empty($data['description'])) {
672
            $group->Description = $data['description'];
673
        }
674
        $group->DN = $data['dn'];
675
        $group->LastSynced = (string)DBDatetime::now();
676
        $group->write();
677
678
        // Mappings on this group are automatically maintained to contain just the group's DN.
679
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
680
        $hasCorrectMapping = false;
681
        foreach ($group->LDAPGroupMappings() as $mapping) {
682
            if ($mapping->DN === $data['dn']) {
683
                // This is the correct mapping we want to retain.
684
                $hasCorrectMapping = true;
685
            } else {
686
                $mapping->delete();
687
            }
688
        }
689
690
        // Second, if the main mapping was not found, add it in.
691
        if (!$hasCorrectMapping) {
692
            $mapping = new LDAPGroupMapping();
693
            $mapping->DN = $data['dn'];
0 ignored issues
show
Documentation introduced by
The property DN does not exist on object<SilverStripe\Acti...Model\LDAPGroupMapping>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
694
            $mapping->write();
695
            $group->LDAPGroupMappings()->add($mapping);
696
        }
697
    }
698
699
    /**
700
     * Creates a new LDAP user from the passed Member record.
701
     * Note that the Member record must have a non-empty Username field for this to work.
702
     *
703
     * @param Member $member
704
     * @throws ValidationException
705
     * @throws Exception
706
     */
707
    public function createLDAPUser(Member $member)
708
    {
709
        if (!$this->enabled()) {
710
            return;
711
        }
712
        if (empty($member->Username)) {
713
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
714
        }
715
        if (!$this->config()->new_users_dn) {
716
            throw new Exception('LDAPService::new_users_dn must be configured to create LDAP users');
717
        }
718
719
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
720
        $member->Username = strtolower($member->Username);
721
722
        // Create user in LDAP using available information.
723
        $dn = sprintf('CN=%s,%s', $member->Username, $this->config()->new_users_dn);
724
725
        try {
726
            $this->add($dn, [
727
                'objectclass' => 'user',
728
                'cn' => $member->Username,
729
                'accountexpires' => '9223372036854775807',
730
                'useraccountcontrol' => '66048',
731
                'userprincipalname' => sprintf(
732
                    '%s@%s',
733
                    $member->Username,
734
                    $this->gateway->config()->options['accountDomainName']
735
                ),
736
            ]);
737
        } catch (Exception $e) {
738
            throw new ValidationException('LDAP synchronisation failure: ' . $e->getMessage());
739
        }
740
741
        $user = $this->getUserByUsername($member->Username);
742
        if (empty($user['objectguid'])) {
743
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
744
        }
745
746
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
747
        $member->GUID = $user['objectguid'];
748
    }
749
750
    /**
751
     * Creates a new LDAP group from the passed Group record.
752
     *
753
     * @param Group $group
754
     * @throws ValidationException
755
     */
756
    public function createLDAPGroup(Group $group)
757
    {
758
        if (!$this->enabled()) {
759
            return;
760
        }
761
        if (empty($group->Title)) {
762
            throw new ValidationException('Group missing Title. Cannot create LDAP group');
763
        }
764
        if (!$this->config()->new_groups_dn) {
765
            throw new Exception('LDAPService::new_groups_dn must be configured to create LDAP groups');
766
        }
767
768
        // LDAP isn't really meant to distinguish between a Title and Code. Squash them.
769
        $group->Code = $group->Title;
770
771
        $dn = sprintf('CN=%s,%s', $group->Title, $this->config()->new_groups_dn);
772
        try {
773
            $this->add($dn, [
774
                'objectclass' => 'group',
775
                'cn' => $group->Title,
776
                'name' => $group->Title,
777
                'samaccountname' => $group->Title,
778
                'description' => $group->Description,
779
                'distinguishedname' => $dn
780
            ]);
781
        } catch (Exception $e) {
782
            throw new ValidationException('LDAP group creation failure: ' . $e->getMessage());
783
        }
784
785
        $data = $this->getGroupByDN($dn);
786
        if (empty($data['objectguid'])) {
787
            throw new ValidationException(
788
                new ValidationResult(
789
                    false,
790
                    'LDAP group creation failure: group might have been created in LDAP. GUID is missing.'
791
                )
792
            );
793
        }
794
795
        // Creation was successful, mark the group as LDAP managed by setting the GUID.
796
        $group->GUID = $data['objectguid'];
797
        $group->DN = $data['dn'];
798
    }
799
800
    /**
801
     * Update the Member data back to the corresponding LDAP user object.
802
     *
803
     * @param Member $member
804
     * @throws ValidationException
805
     */
806
    public function updateLDAPFromMember(Member $member)
807
    {
808
        if (!$this->enabled()) {
809
            return;
810
        }
811
        if (!$member->GUID) {
812
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
813
        }
814
815
        $data = $this->getUserByGUID($member->GUID);
816
        if (empty($data['objectguid'])) {
817
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
818
        }
819
820
        if (empty($member->Username)) {
821
            throw new ValidationException('Member missing Username. Cannot update LDAP user');
822
        }
823
824
        $dn = $data['distinguishedname'];
825
826
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
827
        $member->Username = strtolower($member->Username);
828
829
        try {
830
            // If the common name (cn) has changed, we need to ensure they've been moved
831
            // to the new DN, to avoid any clashes between user objects.
832
            if ($data['cn'] != $member->Username) {
833
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
834
                $this->move($dn, $newDn);
835
                $dn = $newDn;
836
            }
837
        } catch (Exception $e) {
838
            throw new ValidationException('LDAP move failure: '.$e->getMessage());
839
        }
840
841
        try {
842
            $attributes = [
843
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
844
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
845
                'userprincipalname' => sprintf(
846
                    '%s@%s',
847
                    $member->Username,
848
                    $this->gateway->config()->options['accountDomainName']
849
                ),
850
            ];
851
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
852
                $relationClass = $member->getRelationClass($field);
853
                if ($relationClass) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
854
                    // todo no support for writing back relations yet.
855
                } else {
856
                    $attributes[$attribute] = $member->$field;
857
                }
858
            }
859
860
            $this->update($dn, $attributes);
861
        } catch (Exception $e) {
862
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
863
        }
864
    }
865
866
    /**
867
     * Ensure the user belongs to the correct groups in LDAP from their membership
868
     * to local LDAP mapped SilverStripe groups.
869
     *
870
     * This also removes them from LDAP groups if they've been taken out of one.
871
     * It will not affect group membership of non-mapped groups, so it will
872
     * not touch such internal AD groups like "Domain Users".
873
     *
874
     * @param Member $member
875
     * @throws ValidationException
876
     */
877
    public function updateLDAPGroupsForMember(Member $member)
878
    {
879
        if (!$this->enabled()) {
880
            return;
881
        }
882
        if (!$member->GUID) {
883
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
884
        }
885
886
        $addGroups = [];
887
        $removeGroups = [];
888
889
        $user = $this->getUserByGUID($member->GUID);
890
        if (empty($user['objectguid'])) {
891
            throw new ValidationException('LDAP update failure: user missing GUID');
892
        }
893
894
        // If a user belongs to a single group, this comes through as a string.
895
        // Normalise to a array so it's consistent.
896
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : [];
897
        if ($existingGroups && is_string($existingGroups)) {
898
            $existingGroups = [$existingGroups];
899
        }
900
901
        foreach ($member->Groups() as $group) {
902
            if (!$group->GUID) {
903
                continue;
904
            }
905
906
            // mark this group as something we need to ensure the user belongs to in LDAP.
907
            $addGroups[] = $group->DN;
908
        }
909
910
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
911
        // see if the user should be removed from any of them.
912
        $remainingGroups = array_diff($existingGroups, $addGroups);
913
914
        foreach ($remainingGroups as $groupDn) {
915
            // We only want to be removing groups we have a local Group mapped to. Removing
916
            // membership for anything else would be bad!
917
            $group = Group::get()->filter('DN', $groupDn)->first();
918
            if (!$group || !$group->exists()) {
919
                continue;
920
            }
921
922
            // this group should be removed from the user's memberof attribute, as it's been removed.
923
            $removeGroups[] = $groupDn;
924
        }
925
926
        // go through the groups we want the user to be in and ensure they're in them.
927
        foreach ($addGroups as $groupDn) {
928
            $this->addLDAPUserToGroup($user['distinguishedname'], $groupDn);
929
        }
930
931
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
932
        foreach ($removeGroups as $groupDn) {
933
            $members = $this->getLDAPGroupMembers($groupDn);
934
935
            // remove the user from the members data.
936
            if (in_array($user['distinguishedname'], $members)) {
937
                foreach ($members as $i => $dn) {
938
                    if ($dn == $user['distinguishedname']) {
939
                        unset($members[$i]);
940
                    }
941
                }
942
            }
943
944
            try {
945
                $this->update($groupDn, ['member' => $members]);
946
            } catch (Exception $e) {
947
                throw new ValidationException('LDAP group membership remove failure: ' . $e->getMessage());
948
            }
949
        }
950
    }
951
952
    /**
953
     * Add LDAP user by DN to LDAP group.
954
     *
955
     * @param string $userDn
956
     * @param string $groupDn
957
     * @throws Exception
958
     */
959
    public function addLDAPUserToGroup($userDn, $groupDn)
960
    {
961
        $members = $this->getLDAPGroupMembers($groupDn);
962
963
        // this user is already in the group, no need to do anything.
964
        if (in_array($userDn, $members)) {
965
            return;
966
        }
967
968
        $members[] = $userDn;
969
970
        try {
971
            $this->update($groupDn, ['member' => $members]);
972
        } catch (Exception $e) {
973
            throw new ValidationException('LDAP group membership add failure: ' . $e->getMessage());
974
        }
975
    }
976
977
    /**
978
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
979
     * password in the `unicodePwd` attribute.
980
     *
981
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
982
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
983
     *
984
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
985
     *
986
     * @param Member $member
987
     * @param string $password
988
     * @param string|null $oldPassword Supply old password to perform a password change (as opposed to password reset)
989
     * @return ValidationResult
990
     */
991
    public function setPassword(Member $member, $password, $oldPassword = null)
992
    {
993
        $validationResult = ValidationResult::create();
994
995
        $this->extend('onBeforeSetPassword', $member, $password, $validationResult);
996
997
        if (!$member->GUID) {
998
            $this->getLogger()->warn(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method warn() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
999
            $validationResult->addError(
1000
                _t(
1001
                    'LDAPAuthenticator.NOUSER',
1002
                    'Your account hasn\'t been setup properly, please contact an administrator.'
1003
                )
1004
            );
1005
            return $validationResult;
1006
        }
1007
1008
        $userData = $this->getUserByGUID($member->GUID);
1009
        if (empty($userData['distinguishedname'])) {
1010
            $validationResult->addError(
1011
                _t(
1012
                    'LDAPAuthenticator.NOUSER',
1013
                    'Your account hasn\'t been setup properly, please contact an administrator.'
1014
                )
1015
            );
1016
            return $validationResult;
1017
        }
1018
1019
        try {
1020
            if (!empty($oldPassword)) {
1021
                $this->gateway->changePassword($userData['distinguishedname'], $password, $oldPassword);
1022
            } elseif ($this->config()->password_history_workaround) {
1023
                $this->passwordHistoryWorkaround($userData['distinguishedname'], $password);
1024
            } else {
1025
                $this->gateway->resetPassword($userData['distinguishedname'], $password);
1026
            }
1027
            $this->extend('onAfterSetPassword', $member, $password, $validationResult);
1028
        } catch (Exception $e) {
1029
            $validationResult->addError($e->getMessage());
1030
        }
1031
1032
        return $validationResult;
1033
    }
1034
1035
    /**
1036
     * Delete an LDAP user mapped to the Member record
1037
     * @param Member $member
1038
     * @throws ValidationException
1039
     */
1040
    public function deleteLDAPMember(Member $member)
1041
    {
1042
        if (!$this->enabled()) {
1043
            return;
1044
        }
1045
        if (!$member->GUID) {
1046
            throw new ValidationException('Member missing GUID. Cannot delete LDAP user');
1047
        }
1048
        $data = $this->getUserByGUID($member->GUID);
1049
        if (empty($data['distinguishedname'])) {
1050
            throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute');
1051
        }
1052
1053
        try {
1054
            $this->delete($data['distinguishedname']);
1055
        } catch (Exception $e) {
1056
            throw new ValidationException('LDAP delete user failed: ' . $e->getMessage());
1057
        }
1058
    }
1059
1060
    /**
1061
     * A simple proxy to LDAP update operation.
1062
     *
1063
     * @param string $dn Location to add the entry at.
1064
     * @param array $attributes A simple associative array of attributes.
1065
     */
1066
    public function update($dn, array $attributes)
1067
    {
1068
        $this->gateway->update($dn, $attributes);
1069
    }
1070
1071
    /**
1072
     * A simple proxy to LDAP delete operation.
1073
     *
1074
     * @param string $dn Location of object to delete
1075
     * @param bool $recursively Recursively delete nested objects?
1076
     */
1077
    public function delete($dn, $recursively = false)
1078
    {
1079
        $this->gateway->delete($dn, $recursively);
1080
    }
1081
1082
    /**
1083
     * A simple proxy to LDAP copy/delete operation.
1084
     *
1085
     * @param string $fromDn
1086
     * @param string $toDn
1087
     * @param bool $recursively Recursively move nested objects?
1088
     */
1089
    public function move($fromDn, $toDn, $recursively = false)
1090
    {
1091
        $this->gateway->move($fromDn, $toDn, $recursively);
1092
    }
1093
1094
    /**
1095
     * A simple proxy to LDAP add operation.
1096
     *
1097
     * @param string $dn Location to add the entry at.
1098
     * @param array $attributes A simple associative array of attributes.
1099
     */
1100
    public function add($dn, array $attributes)
1101
    {
1102
        $this->gateway->add($dn, $attributes);
1103
    }
1104
1105
    /**
1106
     * @param string $dn Distinguished name of the user
1107
     * @param string $password New password.
1108
     * @throws Exception
1109
     */
1110
    private function passwordHistoryWorkaround($dn, $password)
1111
    {
1112
        $generator = new RandomGenerator();
1113
        // 'Aa1' is there to satisfy the complexity criterion.
1114
        $tempPassword = sprintf('Aa1%s', substr($generator->randomToken('sha1'), 0, 21));
1115
        $this->gateway->resetPassword($dn, $tempPassword);
1116
        $this->gateway->changePassword($dn, $password, $tempPassword);
1117
    }
1118
1119
    /**
1120
     * Get a logger
1121
     *
1122
     * @return LoggerInterface
1123
     */
1124
    public function getLogger()
1125
    {
1126
        return Injector::inst()->get(LoggerInterface::class);
1127
    }
1128
}
1129