Completed
Push — master ( 232009...3c190c )
by Robbie
14s
created

LDAPService::updateMemberGroups()   C

Complexity

Conditions 19
Paths 15

Size

Total Lines 72
Code Lines 38

Duplication

Lines 18
Ratio 25 %

Importance

Changes 0
Metric Value
dl 18
loc 72
rs 5.4418
c 0
b 0
f 0
cc 19
eloc 38
nc 15
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Config\Configurable;
14
use SilverStripe\Core\Flushable;
15
use SilverStripe\Core\Extensible;
16
use SilverStripe\Core\Injector\Injector;
17
use SilverStripe\Core\Injector\Injectable;
18
use SilverStripe\ORM\DB;
19
use SilverStripe\ORM\FieldType\DBDatetime;
20
use SilverStripe\ORM\ValidationException;
21
use SilverStripe\ORM\ValidationResult;
22
use SilverStripe\Security\Group;
23
use SilverStripe\Security\Member;
24
use SilverStripe\Security\RandomGenerator;
25
use Zend\Ldap\Ldap;
26
27
/**
28
 * Class LDAPService
29
 *
30
 * Provides LDAP operations expressed in terms of the SilverStripe domain.
31
 * All other modules should access LDAP through this class.
32
 *
33
 * This class builds on top of LDAPGateway's detailed code by adding:
34
 * - caching
35
 * - data aggregation and restructuring from multiple lower-level calls
36
 * - error handling
37
 *
38
 * LDAPService relies on Zend LDAP module's data structures for some parameters and some return values.
39
 *
40
 * @package activedirectory
41
 */
42
class LDAPService implements Flushable
43
{
44
    use Injectable;
45
    use Extensible;
46
    use Configurable;
47
48
    /**
49
     * @var array
50
     */
51
    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...
52
        'gateway' => '%$' . LDAPGateway::class
53
    ];
54
55
    /**
56
     * If configured, only user objects within these locations will be exposed to this service.
57
     *
58
     * @var array
59
     * @config
60
     */
61
    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...
62
63
    /**
64
     * If configured, only group objects within these locations will be exposed to this service.
65
     * @var array
66
     *
67
     * @config
68
     */
69
    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...
70
71
    /**
72
     * Location to create new users in (distinguished name).
73
     * @var string
74
     *
75
     * @config
76
     */
77
    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...
78
79
    /**
80
     * Location to create new groups in (distinguished name).
81
     * @var string
82
     *
83
     * @config
84
     */
85
    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...
86
87
    /**
88
     * @var array
89
     */
90
    private static $_cache_nested_groups = [];
91
92
    /**
93
     * If this is configured to a "Code" value of a {@link Group} in SilverStripe, the user will always
94
     * be added to this group's membership when imported, regardless of any sort of group mappings.
95
     *
96
     * @var string
97
     * @config
98
     */
99
    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...
100
101
    /**
102
     * For samba4 directory, there is no way to enforce password history on password resets.
103
     * This only happens with changePassword (which requires the old password).
104
     * This works around it by making the old password up and setting it administratively.
105
     *
106
     * A cleaner fix would be to use the LDAP_SERVER_POLICY_HINTS_OID connection flag,
107
     * but it's not implemented in samba https://bugzilla.samba.org/show_bug.cgi?id=12020
108
     *
109
     * @var bool
110
     */
111
    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...
112
113
    /**
114
     * Get the cache object used for LDAP results. Note that the default lifetime set here
115
     * is 8 hours, but you can change that by adding configuration:
116
     *
117
     * <code>
118
     * SilverStripe\Core\Injector\Injector:
119
     *   Psr\SimpleCache\CacheInterface.ldap:
120
     *     constructor:
121
     *       defaultLifetime: 3600 # time in seconds
122
     * </code>
123
     *
124
     * @return Psr\SimpleCache\CacheInterface
125
     */
126
    public static function get_cache()
127
    {
128
        return Injector::inst()->get(CacheInterface::class . '.ldap');
129
    }
130
131
    /**
132
     * Flushes out the LDAP results cache when flush=1 is called.
133
     */
134
    public static function flush()
135
    {
136
        /** @var CacheInterface $cache */
137
        $cache = self::get_cache();
138
        $cache->clear();
139
    }
140
141
    /**
142
     * @var LDAPGateway
143
     */
144
    public $gateway;
145
146
    public function __construct()
147
    {
148
        $this->constructExtensions();
0 ignored issues
show
Deprecated Code introduced by
The method SilverStripe\Core\Extens...::constructExtensions() has been deprecated with message: 4.0..5.0 Extensions and methods are now lazy-loaded

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
149
    }
150
151
    /**
152
     * Setter for gateway. Useful for overriding the gateway with a fake for testing.
153
     * @var LDAPGateway
154
     */
155
    public function setGateway($gateway)
156
    {
157
        $this->gateway = $gateway;
158
    }
159
160
    /**
161
     * Checkes whether or not the service is enabled.
162
     *
163
     * @return bool
164
     */
165
    public function enabled()
166
    {
167
        $options = Config::inst()->get(LDAPGateway::class, 'options');
168
        return !empty($options);
169
    }
170
171
    /**
172
     * Authenticate the given username and password with LDAP.
173
     *
174
     * @param string $username
175
     * @param string $password
176
     *
177
     * @return array
178
     */
179
    public function authenticate($username, $password)
180
    {
181
        $result = $this->gateway->authenticate($username, $password);
182
        $messages = $result->getMessages();
183
184
        // all messages beyond the first one are for debugging and
185
        // not suitable to display to the user.
186
        foreach ($messages as $i => $message) {
187
            if ($i > 0) {
188
                $this->getLogger()->debug(str_replace("\n", "\n  ", $message));
189
            }
190
        }
191
192
        $message = $messages[0]; // first message is user readable, suitable for showing on login form
193
194
        // show better errors than the defaults for various status codes returned by LDAP
195 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...
196
            $message = _t(
197
                __CLASS__ . '.ACCOUNTLOCKEDOUT',
198
                'Your account has been temporarily locked because of too many failed login attempts. ' .
199
                'Please try again later.'
200
            );
201
        }
202 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...
203
            $message = _t(
204
                __CLASS__ . '.INVALIDCREDENTIALS',
205
                'The provided details don\'t seem to be correct. Please try again.'
206
            );
207
        }
208
209
        return [
210
            'success' => $result->getCode() === 1,
211
            'identity' => $result->getIdentity(),
212
            'message' => $message,
213
            'code' => $result->getCode()
214
        ];
215
    }
216
217
    /**
218
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
219
     *
220
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
221
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
222
     * @return array
223
     */
224
    public function getNodes($cached = true, $attributes = [])
225
    {
226
        $cache = self::get_cache();
227
        $cacheKey = 'nodes' . md5(implode('', $attributes));
228
        $results = $cache->has($cacheKey);
229
230
        if (!$results || !$cached) {
231
            $results = [];
232
            $records = $this->gateway->getNodes(null, Ldap::SEARCH_SCOPE_SUB, $attributes);
233
            foreach ($records as $record) {
234
                $results[$record['dn']] = $record;
235
            }
236
237
            $cache->set($cacheKey, $results);
238
        }
239
240
        return $results;
241
    }
242
243
    /**
244
     * Return all AD groups in configured search locations, including all nested groups.
245
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
246
     * to use the default baseDn defined in the connection.
247
     *
248
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
249
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
250
     * @param string $indexBy Attribute to use as an index.
251
     * @return array
252
     */
253
    public function getGroups($cached = true, $attributes = [], $indexBy = 'dn')
254
    {
255
        $searchLocations = $this->config()->groups_search_locations ?: [null];
256
        $cache = self::get_cache();
257
        $cacheKey = 'groups' . md5(implode('', array_merge($searchLocations, $attributes)));
258
        $results = $cache->has($cacheKey);
259
260
        if (!$results || !$cached) {
261
            $results = [];
262 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...
263
                $records = $this->gateway->getGroups($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
264
                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...
265
                    continue;
266
                }
267
268
                foreach ($records as $record) {
269
                    $results[$record[$indexBy]] = $record;
270
                }
271
            }
272
273
            $cache->set($cacheKey, $results);
274
        }
275
276
        if ($cached && $results === true) {
277
            $results = $cache->get($cacheKey);
278
        }
279
280
        return $results;
281
    }
282
283
    /**
284
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
285
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
286
     *
287
     * @param string $dn
288
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
289
     * @return array
290
     */
291
    public function getNestedGroups($dn, $attributes = [])
292
    {
293
        if (isset(self::$_cache_nested_groups[$dn])) {
294
            return self::$_cache_nested_groups[$dn];
295
        }
296
297
        $searchLocations = $this->config()->groups_search_locations ?: [null];
298
        $results = [];
299 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...
300
            $records = $this->gateway->getNestedGroups($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
301
            foreach ($records as $record) {
302
                $results[$record['dn']] = $record;
303
            }
304
        }
305
306
        self::$_cache_nested_groups[$dn] = $results;
307
        return $results;
308
    }
309
310
    /**
311
     * Get a particular AD group's data given a GUID.
312
     *
313
     * @param string $guid
314
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
315
     * @return array
316
     */
317 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...
318
    {
319
        $searchLocations = $this->config()->groups_search_locations ?: [null];
320
        foreach ($searchLocations as $searchLocation) {
321
            $records = $this->gateway->getGroupByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
322
            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...
323
                return $records[0];
324
            }
325
        }
326
    }
327
328
    /**
329
     * Get a particular AD group's data given a DN.
330
     *
331
     * @param string $dn
332
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
333
     * @return array
334
     */
335 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...
336
    {
337
        $searchLocations = $this->config()->groups_search_locations ?: [null];
338
        foreach ($searchLocations as $searchLocation) {
339
            $records = $this->gateway->getGroupByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
340
            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...
341
                return $records[0];
342
            }
343
        }
344
    }
345
346
    /**
347
     * Return all AD users in configured search locations, including all users in nested groups.
348
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
349
     * to use the default baseDn defined in the connection.
350
     *
351
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
352
     * @return array
353
     */
354
    public function getUsers($attributes = [])
355
    {
356
        $searchLocations = $this->config()->users_search_locations ?: [null];
357
        $results = [];
358
359 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...
360
            $records = $this->gateway->getUsers($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
361
            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...
362
                continue;
363
            }
364
365
            foreach ($records as $record) {
366
                $results[$record['objectguid']] = $record;
367
            }
368
        }
369
370
        return $results;
371
    }
372
373
    /**
374
     * Get a specific AD user's data given a GUID.
375
     *
376
     * @param string $guid
377
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
378
     * @return array
379
     */
380 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...
381
    {
382
        $searchLocations = $this->config()->users_search_locations ?: [null];
383
        foreach ($searchLocations as $searchLocation) {
384
            $records = $this->gateway->getUserByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
385
            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...
386
                return $records[0];
387
            }
388
        }
389
    }
390
391
    /**
392
     * Get a specific AD user's data given a DN.
393
     *
394
     * @param string $dn
395
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
396
     *
397
     * @return array
398
     */
399 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...
400
    {
401
        $searchLocations = $this->config()->users_search_locations ?: [null];
402
        foreach ($searchLocations as $searchLocation) {
403
            $records = $this->gateway->getUserByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
404
            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...
405
                return $records[0];
406
            }
407
        }
408
    }
409
410
    /**
411
     * Get a specific user's data given an email.
412
     *
413
     * @param string $email
414
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
415
     * @return array
416
     */
417 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...
418
    {
419
        $searchLocations = $this->config()->users_search_locations ?: [null];
420
        foreach ($searchLocations as $searchLocation) {
421
            $records = $this->gateway->getUserByEmail($email, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
422
            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...
423
                return $records[0];
424
            }
425
        }
426
    }
427
428
    /**
429
     * Get a specific user's data given a username.
430
     *
431
     * @param string $username
432
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
433
     * @return array
434
     */
435 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...
436
    {
437
        $searchLocations = $this->config()->users_search_locations ?: [null];
438
        foreach ($searchLocations as $searchLocation) {
439
            $records = $this->gateway->getUserByUsername(
440
                $username,
441
                $searchLocation,
442
                Ldap::SEARCH_SCOPE_SUB,
443
                $attributes
444
            );
445
            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...
446
                return $records[0];
447
            }
448
        }
449
    }
450
451
    /**
452
     * Get a username for an email.
453
     *
454
     * @param string $email
455
     * @return string|null
456
     */
457
    public function getUsernameByEmail($email)
458
    {
459
        $data = $this->getUserByEmail($email);
460
        if (empty($data)) {
461
            return null;
462
        }
463
464
        return $this->gateway->getCanonicalUsername($data);
465
    }
466
467
    /**
468
     * Given a group DN, get the group membership data in LDAP.
469
     *
470
     * @param string $dn
471
     * @return array
472
     */
473
    public function getLDAPGroupMembers($dn)
474
    {
475
        $groupObj = Group::get()->filter('DN', $dn)->first();
476
        $groupData = $this->getGroupByGUID($groupObj->GUID);
477
        $members = !empty($groupData['member']) ? $groupData['member'] : [];
478
        // If a user belongs to a single group, this comes through as a string.
479
        // Normalise to a array so it's consistent.
480
        if ($members && is_string($members)) {
481
            $members = [$members];
482
        }
483
484
        return $members;
485
    }
486
487
    /**
488
     * Update the current Member record with data from LDAP.
489
     *
490
     * It's allowed to pass an unwritten Member record here, because it's not always possible to satisfy
491
     * field constraints without importing data from LDAP (for example if the application requires Username
492
     * through a Validator). Even though unwritten, it still must have the GUID set.
493
     *
494
     * Constraints:
495
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
496
     *
497
     * @param Member $member
498
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
499
     *            If not given, the data will be looked up by the user's GUID.
500
     * @param bool $updateGroups controls whether to run the resource-intensive group update function as well. This is
501
     *                          skipped during login to reduce load.
502
     * @return bool
503
     * @internal param $Member
504
     */
505
    public function updateMemberFromLDAP(Member $member, $data = null, $updateGroups = true)
506
    {
507
        if (!$this->enabled()) {
508
            return false;
509
        }
510
511
        if (!$member->GUID) {
512
            $this->getLogger()->warning(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
513
            return false;
514
        }
515
516
        if (!$data) {
517
            $data = $this->getUserByGUID($member->GUID);
518
            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...
519
                $this->getLogger()->warning(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID));
520
                return false;
521
            }
522
        }
523
524
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
525
        $member->LastSynced = (string)DBDatetime::now();
526
527
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
528
            if (!isset($data[$attribute])) {
529
                $this->getLogger()->notice(
530
                    sprintf(
531
                        'Attribute %s configured in Member.ldap_field_mappings, ' .
532
                                'but no available attribute in AD data (GUID: %s, Member ID: %s)',
533
                        $attribute,
534
                        $data['objectguid'],
535
                        $member->ID
536
                    )
537
                );
538
539
                continue;
540
            }
541
542
            if ($attribute == 'thumbnailphoto') {
543
                $imageClass = $member->getRelationClass($field);
544
                if ($imageClass !== Image::class
545
                    && !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...
546
                ) {
547
                    $this->getLogger()->warning(
548
                        sprintf(
549
                            'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a ' .
550
                            'valid relation to an Image class',
551
                            $field
552
                        )
553
                    );
554
555
                    continue;
556
                }
557
558
                $filename = sprintf('thumbnailphoto-%s.jpg', $data['samaccountname']);
559
                $path = ASSETS_DIR . '/' . $member->config()->ldap_thumbnail_path;
560
                $absPath = BASE_PATH . '/' . $path;
561
                if (!file_exists($absPath)) {
562
                    Filesystem::makeFolder($absPath);
563
                }
564
565
                // remove existing record if it exists
566
                $existingObj = $member->getComponent($field);
567
                if ($existingObj && $existingObj->exists()) {
568
                    $existingObj->delete();
569
                }
570
571
                // The image data is provided in raw binary.
572
                file_put_contents($absPath . '/' . $filename, $data[$attribute]);
573
                $record = new $imageClass();
574
                $record->Name = $filename;
575
                $record->Filename = $path . '/' . $filename;
576
                $record->write();
577
578
                $relationField = $field . 'ID';
579
                $member->{$relationField} = $record->ID;
580
            } else {
581
                $member->$field = $data[$attribute];
582
            }
583
        }
584
585
        // if a default group was configured, ensure the user is in that group
586
        if ($this->config()->default_group) {
587
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
588
            if (!($group && $group->exists())) {
589
                $this->getLogger()->warning(
590
                    sprintf(
591
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
592
                        $this->config()->default_group
593
                    )
594
                );
595
            } else {
596
                $group->Members()->add($member, [
597
                    'IsImportedFromLDAP' => '1'
598
                ]);
599
            }
600
        }
601
602
        // this is to keep track of which groups the user gets mapped to
603
        // and we'll use that later to remove them from any groups that they're no longer mapped to
604
        $mappedGroupIDs = [];
0 ignored issues
show
Unused Code introduced by
$mappedGroupIDs is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
605
606
        // Member must have an ID before manipulating Groups, otherwise they will not be added correctly.
607
        // However we cannot do a full ->write before the groups are associated, because this will upsync
608
        // the Member, in effect deleting all their LDAP group associations!
609
        $member->writeWithoutSync();
610
611
        if ($updateGroups) {
612
            $this->updateMemberGroups($data, $member);
613
        }
614
615
        // This will throw an exception if there are two distinct GUIDs with the same email address.
616
        // We are happy with a raw 500 here at this stage.
617
        $member->write();
618
    }
619
620
    /**
621
     * Ensure the user is mapped to any applicable groups.
622
     * @param array $data
623
     * @param Member $member
624
     */
625
    public function updateMemberGroups($data, Member $member)
626
    {
627
        if (isset($data['memberof'])) {
628
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : [$data['memberof']];
629
            foreach ($ldapGroups as $groupDN) {
630
                foreach (LDAPGroupMapping::get() as $mapping) {
631
                    if (!$mapping->DN) {
632
                        $this->getLogger()->warning(
633
                            sprintf(
634
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
635
                                $mapping->ID
636
                            )
637
                        );
638
                        continue;
639
                    }
640
641
                    // the user is a direct member of group with a mapping, add them to the SS group.
642 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...
643
                        $group = $mapping->Group();
644
                        if ($group && $group->exists()) {
645
                            $group->Members()->add($member, [
646
                                'IsImportedFromLDAP' => '1'
647
                            ]);
648
                            $mappedGroupIDs[] = $mapping->GroupID;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$mappedGroupIDs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $mappedGroupIDs = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
649
                        }
650
                    }
651
652
                    // the user *might* be a member of a nested group provided the scope of the mapping
653
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
654
                    // to see if they are a member of one of those. If they are, add them to the SS group
655
                    if ($mapping->Scope == 'Subtree') {
656
                        $childGroups = $this->getNestedGroups($mapping->DN, ['dn']);
657
                        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...
658
                            continue;
659
                        }
660
661
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
662 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...
663
                                $group = $mapping->Group();
664
                                if ($group && $group->exists()) {
665
                                    $group->Members()->add($member, [
666
                                        'IsImportedFromLDAP' => '1'
667
                                    ]);
668
                                    $mappedGroupIDs[] = $mapping->GroupID;
0 ignored issues
show
Bug introduced by
The variable $mappedGroupIDs does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
669
                                }
670
                            }
671
                        }
672
                    }
673
                }
674
            }
675
        }
676
677
        // remove the user from any previously mapped groups, where the mapping has since been removed
678
        $groupRecords = DB::query(
679
            sprintf(
680
                'SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s',
681
                $member->ID
682
            )
683
        );
684
685
        if (!empty($mappedGroupIDs)) {
686
            foreach ($groupRecords as $groupRecord) {
687
                if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
688
                    $group = Group::get()->byId($groupRecord['GroupID']);
689
                    // Some groups may no longer exist. SilverStripe does not clean up join tables.
690
                    if ($group) {
691
                        $group->Members()->remove($member);
692
                    }
693
                }
694
            }
695
        }
696
    }
697
698
    /**
699
     * Sync a specific Group by updating it with LDAP data.
700
     *
701
     * @param Group $group An existing Group or a new Group object
702
     * @param array $data LDAP group object data
703
     *
704
     * @return bool
705
     */
706
    public function updateGroupFromLDAP(Group $group, $data)
707
    {
708
        if (!$this->enabled()) {
709
            return false;
710
        }
711
712
        // Synchronise specific guaranteed fields.
713
        $group->Code = $data['samaccountname'];
714
        $group->Title = $data['samaccountname'];
715
        if (!empty($data['description'])) {
716
            $group->Description = $data['description'];
717
        }
718
        $group->DN = $data['dn'];
719
        $group->LastSynced = (string)DBDatetime::now();
720
        $group->write();
721
722
        // Mappings on this group are automatically maintained to contain just the group's DN.
723
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
724
        $hasCorrectMapping = false;
725
        foreach ($group->LDAPGroupMappings() as $mapping) {
726
            if ($mapping->DN === $data['dn']) {
727
                // This is the correct mapping we want to retain.
728
                $hasCorrectMapping = true;
729
            } else {
730
                $mapping->delete();
731
            }
732
        }
733
734
        // Second, if the main mapping was not found, add it in.
735
        if (!$hasCorrectMapping) {
736
            $mapping = new LDAPGroupMapping();
737
            $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...
738
            $mapping->write();
739
            $group->LDAPGroupMappings()->add($mapping);
740
        }
741
    }
742
743
    /**
744
     * Creates a new LDAP user from the passed Member record.
745
     * Note that the Member record must have a non-empty Username field for this to work.
746
     *
747
     * @param Member $member
748
     * @throws ValidationException
749
     * @throws Exception
750
     */
751
    public function createLDAPUser(Member $member)
752
    {
753
        if (!$this->enabled()) {
754
            return;
755
        }
756
        if (empty($member->Username)) {
757
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
758
        }
759
        if (!$this->config()->new_users_dn) {
760
            throw new Exception('LDAPService::new_users_dn must be configured to create LDAP users');
761
        }
762
763
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
764
        $member->Username = strtolower($member->Username);
765
766
        // Create user in LDAP using available information.
767
        $dn = sprintf('CN=%s,%s', $member->Username, $this->config()->new_users_dn);
768
769
        try {
770
            $this->add($dn, [
771
                'objectclass' => 'user',
772
                'cn' => $member->Username,
773
                'accountexpires' => '9223372036854775807',
774
                'useraccountcontrol' => '66048',
775
                'userprincipalname' => sprintf(
776
                    '%s@%s',
777
                    $member->Username,
778
                    $this->gateway->config()->options['accountDomainName']
779
                ),
780
            ]);
781
        } catch (Exception $e) {
782
            throw new ValidationException('LDAP synchronisation failure: ' . $e->getMessage());
783
        }
784
785
        $user = $this->getUserByUsername($member->Username);
786
        if (empty($user['objectguid'])) {
787
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
788
        }
789
790
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
791
        $member->GUID = $user['objectguid'];
792
    }
793
794
    /**
795
     * Creates a new LDAP group from the passed Group record.
796
     *
797
     * @param Group $group
798
     * @throws ValidationException
799
     */
800
    public function createLDAPGroup(Group $group)
801
    {
802
        if (!$this->enabled()) {
803
            return;
804
        }
805
        if (empty($group->Title)) {
806
            throw new ValidationException('Group missing Title. Cannot create LDAP group');
807
        }
808
        if (!$this->config()->new_groups_dn) {
809
            throw new Exception('LDAPService::new_groups_dn must be configured to create LDAP groups');
810
        }
811
812
        // LDAP isn't really meant to distinguish between a Title and Code. Squash them.
813
        $group->Code = $group->Title;
814
815
        $dn = sprintf('CN=%s,%s', $group->Title, $this->config()->new_groups_dn);
816
        try {
817
            $this->add($dn, [
818
                'objectclass' => 'group',
819
                'cn' => $group->Title,
820
                'name' => $group->Title,
821
                'samaccountname' => $group->Title,
822
                'description' => $group->Description,
823
                'distinguishedname' => $dn
824
            ]);
825
        } catch (Exception $e) {
826
            throw new ValidationException('LDAP group creation failure: ' . $e->getMessage());
827
        }
828
829
        $data = $this->getGroupByDN($dn);
830
        if (empty($data['objectguid'])) {
831
            throw new ValidationException(
832
                new ValidationResult(
833
                    false,
834
                    'LDAP group creation failure: group might have been created in LDAP. GUID is missing.'
835
                )
836
            );
837
        }
838
839
        // Creation was successful, mark the group as LDAP managed by setting the GUID.
840
        $group->GUID = $data['objectguid'];
841
        $group->DN = $data['dn'];
842
    }
843
844
    /**
845
     * Update the Member data back to the corresponding LDAP user object.
846
     *
847
     * @param Member $member
848
     * @throws ValidationException
849
     */
850
    public function updateLDAPFromMember(Member $member)
851
    {
852
        if (!$this->enabled()) {
853
            return;
854
        }
855
        if (!$member->GUID) {
856
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
857
        }
858
859
        $data = $this->getUserByGUID($member->GUID);
860
        if (empty($data['objectguid'])) {
861
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
862
        }
863
864
        if (empty($member->Username)) {
865
            throw new ValidationException('Member missing Username. Cannot update LDAP user');
866
        }
867
868
        $dn = $data['distinguishedname'];
869
870
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
871
        $member->Username = strtolower($member->Username);
872
873
        try {
874
            // If the common name (cn) has changed, we need to ensure they've been moved
875
            // to the new DN, to avoid any clashes between user objects.
876
            if ($data['cn'] != $member->Username) {
877
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
878
                $this->move($dn, $newDn);
879
                $dn = $newDn;
880
            }
881
        } catch (Exception $e) {
882
            throw new ValidationException('LDAP move failure: '.$e->getMessage());
883
        }
884
885
        try {
886
            $attributes = [
887
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
888
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
889
                'userprincipalname' => sprintf(
890
                    '%s@%s',
891
                    $member->Username,
892
                    $this->gateway->config()->options['accountDomainName']
893
                ),
894
            ];
895
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
896
                $relationClass = $member->getRelationClass($field);
897
                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...
898
                    // todo no support for writing back relations yet.
899
                } else {
900
                    $attributes[$attribute] = $member->$field;
901
                }
902
            }
903
904
            $this->update($dn, $attributes);
905
        } catch (Exception $e) {
906
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
907
        }
908
    }
909
910
    /**
911
     * Ensure the user belongs to the correct groups in LDAP from their membership
912
     * to local LDAP mapped SilverStripe groups.
913
     *
914
     * This also removes them from LDAP groups if they've been taken out of one.
915
     * It will not affect group membership of non-mapped groups, so it will
916
     * not touch such internal AD groups like "Domain Users".
917
     *
918
     * @param Member $member
919
     * @throws ValidationException
920
     */
921
    public function updateLDAPGroupsForMember(Member $member)
922
    {
923
        if (!$this->enabled()) {
924
            return;
925
        }
926
        if (!$member->GUID) {
927
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
928
        }
929
930
        $addGroups = [];
931
        $removeGroups = [];
932
933
        $user = $this->getUserByGUID($member->GUID);
934
        if (empty($user['objectguid'])) {
935
            throw new ValidationException('LDAP update failure: user missing GUID');
936
        }
937
938
        // If a user belongs to a single group, this comes through as a string.
939
        // Normalise to a array so it's consistent.
940
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : [];
941
        if ($existingGroups && is_string($existingGroups)) {
942
            $existingGroups = [$existingGroups];
943
        }
944
945
        foreach ($member->Groups() as $group) {
946
            if (!$group->GUID) {
947
                continue;
948
            }
949
950
            // mark this group as something we need to ensure the user belongs to in LDAP.
951
            $addGroups[] = $group->DN;
952
        }
953
954
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
955
        // see if the user should be removed from any of them.
956
        $remainingGroups = array_diff($existingGroups, $addGroups);
957
958
        foreach ($remainingGroups as $groupDn) {
959
            // We only want to be removing groups we have a local Group mapped to. Removing
960
            // membership for anything else would be bad!
961
            $group = Group::get()->filter('DN', $groupDn)->first();
962
            if (!$group || !$group->exists()) {
963
                continue;
964
            }
965
966
            // this group should be removed from the user's memberof attribute, as it's been removed.
967
            $removeGroups[] = $groupDn;
968
        }
969
970
        // go through the groups we want the user to be in and ensure they're in them.
971
        foreach ($addGroups as $groupDn) {
972
            $this->addLDAPUserToGroup($user['distinguishedname'], $groupDn);
973
        }
974
975
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
976
        foreach ($removeGroups as $groupDn) {
977
            $members = $this->getLDAPGroupMembers($groupDn);
978
979
            // remove the user from the members data.
980
            if (in_array($user['distinguishedname'], $members)) {
981
                foreach ($members as $i => $dn) {
982
                    if ($dn == $user['distinguishedname']) {
983
                        unset($members[$i]);
984
                    }
985
                }
986
            }
987
988
            try {
989
                $this->update($groupDn, ['member' => $members]);
990
            } catch (Exception $e) {
991
                throw new ValidationException('LDAP group membership remove failure: ' . $e->getMessage());
992
            }
993
        }
994
    }
995
996
    /**
997
     * Add LDAP user by DN to LDAP group.
998
     *
999
     * @param string $userDn
1000
     * @param string $groupDn
1001
     * @throws Exception
1002
     */
1003
    public function addLDAPUserToGroup($userDn, $groupDn)
1004
    {
1005
        $members = $this->getLDAPGroupMembers($groupDn);
1006
1007
        // this user is already in the group, no need to do anything.
1008
        if (in_array($userDn, $members)) {
1009
            return;
1010
        }
1011
1012
        $members[] = $userDn;
1013
1014
        try {
1015
            $this->update($groupDn, ['member' => $members]);
1016
        } catch (Exception $e) {
1017
            throw new ValidationException('LDAP group membership add failure: ' . $e->getMessage());
1018
        }
1019
    }
1020
1021
    /**
1022
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
1023
     * password in the `unicodePwd` attribute.
1024
     *
1025
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
1026
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
1027
     *
1028
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
1029
     *
1030
     * @param Member $member
1031
     * @param string $password
1032
     * @param string|null $oldPassword Supply old password to perform a password change (as opposed to password reset)
1033
     * @return ValidationResult
1034
     */
1035
    public function setPassword(Member $member, $password, $oldPassword = null)
1036
    {
1037
        $validationResult = ValidationResult::create();
1038
1039
        $this->extend('onBeforeSetPassword', $member, $password, $validationResult);
1040
1041
        if (!$member->GUID) {
1042
            $this->getLogger()->warning(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
1043
            $validationResult->addError(
1044
                _t(
1045
                    'SilverStripe\\ActiveDirectory\\Authenticators\\LDAPAuthenticator.NOUSER',
1046
                    'Your account hasn\'t been setup properly, please contact an administrator.'
1047
                )
1048
            );
1049
            return $validationResult;
1050
        }
1051
1052
        $userData = $this->getUserByGUID($member->GUID);
1053
        if (empty($userData['distinguishedname'])) {
1054
            $validationResult->addError(
1055
                _t(
1056
                    'SilverStripe\\ActiveDirectory\\Authenticators\\LDAPAuthenticator.NOUSER',
1057
                    'Your account hasn\'t been setup properly, please contact an administrator.'
1058
                )
1059
            );
1060
            return $validationResult;
1061
        }
1062
1063
        try {
1064
            if (!empty($oldPassword)) {
1065
                $this->gateway->changePassword($userData['distinguishedname'], $password, $oldPassword);
1066
            } elseif ($this->config()->password_history_workaround) {
1067
                $this->passwordHistoryWorkaround($userData['distinguishedname'], $password);
1068
            } else {
1069
                $this->gateway->resetPassword($userData['distinguishedname'], $password);
1070
            }
1071
            $this->extend('onAfterSetPassword', $member, $password, $validationResult);
1072
        } catch (Exception $e) {
1073
            $validationResult->addError($e->getMessage());
1074
        }
1075
1076
        return $validationResult;
1077
    }
1078
1079
    /**
1080
     * Delete an LDAP user mapped to the Member record
1081
     * @param Member $member
1082
     * @throws ValidationException
1083
     */
1084
    public function deleteLDAPMember(Member $member)
1085
    {
1086
        if (!$this->enabled()) {
1087
            return;
1088
        }
1089
        if (!$member->GUID) {
1090
            throw new ValidationException('Member missing GUID. Cannot delete LDAP user');
1091
        }
1092
        $data = $this->getUserByGUID($member->GUID);
1093
        if (empty($data['distinguishedname'])) {
1094
            throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute');
1095
        }
1096
1097
        try {
1098
            $this->delete($data['distinguishedname']);
1099
        } catch (Exception $e) {
1100
            throw new ValidationException('LDAP delete user failed: ' . $e->getMessage());
1101
        }
1102
    }
1103
1104
    /**
1105
     * A simple proxy to LDAP update operation.
1106
     *
1107
     * @param string $dn Location to add the entry at.
1108
     * @param array $attributes A simple associative array of attributes.
1109
     */
1110
    public function update($dn, array $attributes)
1111
    {
1112
        $this->gateway->update($dn, $attributes);
1113
    }
1114
1115
    /**
1116
     * A simple proxy to LDAP delete operation.
1117
     *
1118
     * @param string $dn Location of object to delete
1119
     * @param bool $recursively Recursively delete nested objects?
1120
     */
1121
    public function delete($dn, $recursively = false)
1122
    {
1123
        $this->gateway->delete($dn, $recursively);
1124
    }
1125
1126
    /**
1127
     * A simple proxy to LDAP copy/delete operation.
1128
     *
1129
     * @param string $fromDn
1130
     * @param string $toDn
1131
     * @param bool $recursively Recursively move nested objects?
1132
     */
1133
    public function move($fromDn, $toDn, $recursively = false)
1134
    {
1135
        $this->gateway->move($fromDn, $toDn, $recursively);
1136
    }
1137
1138
    /**
1139
     * A simple proxy to LDAP add operation.
1140
     *
1141
     * @param string $dn Location to add the entry at.
1142
     * @param array $attributes A simple associative array of attributes.
1143
     */
1144
    public function add($dn, array $attributes)
1145
    {
1146
        $this->gateway->add($dn, $attributes);
1147
    }
1148
1149
    /**
1150
     * @param string $dn Distinguished name of the user
1151
     * @param string $password New password.
1152
     * @throws Exception
1153
     */
1154
    private function passwordHistoryWorkaround($dn, $password)
1155
    {
1156
        $generator = new RandomGenerator();
1157
        // 'Aa1' is there to satisfy the complexity criterion.
1158
        $tempPassword = sprintf('Aa1%s', substr($generator->randomToken('sha1'), 0, 21));
1159
        $this->gateway->resetPassword($dn, $tempPassword);
1160
        $this->gateway->changePassword($dn, $password, $tempPassword);
1161
    }
1162
1163
    /**
1164
     * Get a logger
1165
     *
1166
     * @return LoggerInterface
1167
     */
1168
    public function getLogger()
1169
    {
1170
        return Injector::inst()->get(LoggerInterface::class);
1171
    }
1172
}
1173