Completed
Pull Request — master (#116)
by Franco
01:39
created

LDAPService::getUserByDN()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 10
Code Lines 6

Duplication

Lines 10
Ratio 100 %

Importance

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