Completed
Push — master ( e799f7...0da2a1 )
by Stig
11s
created

LDAPService::getGroupByDN()   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();
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
                'LDAPService.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
                'LDAPService.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
        ];
214
    }
215
216
    /**
217
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
218
     *
219
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
220
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
221
     * @return array
222
     */
223
    public function getNodes($cached = true, $attributes = [])
224
    {
225
        $cache = self::get_cache();
226
        $cacheKey = 'nodes' . md5(implode('', $attributes));
227
        $results = $cache->has($cacheKey);
228
229
        if (!$results || !$cached) {
230
            $results = [];
231
            $records = $this->gateway->getNodes(null, Ldap::SEARCH_SCOPE_SUB, $attributes);
232
            foreach ($records as $record) {
233
                $results[$record['dn']] = $record;
234
            }
235
236
            $cache->set($cacheKey, $results);
237
        }
238
239
        return $results;
240
    }
241
242
    /**
243
     * Return all AD groups in configured search locations, including all nested groups.
244
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
245
     * to use the default baseDn defined in the connection.
246
     *
247
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
248
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
249
     * @param string $indexBy Attribute to use as an index.
250
     * @return array
251
     */
252
    public function getGroups($cached = true, $attributes = [], $indexBy = 'dn')
253
    {
254
        $searchLocations = $this->config()->groups_search_locations ?: [null];
255
        $cache = self::get_cache();
256
        $cacheKey = 'groups' . md5(implode('', array_merge($searchLocations, $attributes)));
257
        $results = $cache->has($cacheKey);
258
259
        if (!$results || !$cached) {
260
            $results = [];
261 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...
262
                $records = $this->gateway->getGroups($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
263
                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...
264
                    continue;
265
                }
266
267
                foreach ($records as $record) {
268
                    $results[$record[$indexBy]] = $record;
269
                }
270
            }
271
272
            $cache->set($cacheKey, $results);
273
        }
274
275
        if ($cached && $results === true) {
276
            $results = $cache->get($cacheKey);
277
        }
278
279
        return $results;
280
    }
281
282
    /**
283
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
284
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
285
     *
286
     * @param string $dn
287
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
288
     * @return array
289
     */
290
    public function getNestedGroups($dn, $attributes = [])
291
    {
292
        if (isset(self::$_cache_nested_groups[$dn])) {
293
            return self::$_cache_nested_groups[$dn];
294
        }
295
296
        $searchLocations = $this->config()->groups_search_locations ?: [null];
297
        $results = [];
298 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...
299
            $records = $this->gateway->getNestedGroups($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
300
            foreach ($records as $record) {
301
                $results[$record['dn']] = $record;
302
            }
303
        }
304
305
        self::$_cache_nested_groups[$dn] = $results;
306
        return $results;
307
    }
308
309
    /**
310
     * Get a particular AD group's data given a GUID.
311
     *
312
     * @param string $guid
313
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
314
     * @return array
315
     */
316 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...
317
    {
318
        $searchLocations = $this->config()->groups_search_locations ?: [null];
319
        foreach ($searchLocations as $searchLocation) {
320
            $records = $this->gateway->getGroupByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
321
            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...
322
                return $records[0];
323
            }
324
        }
325
    }
326
327
    /**
328
     * Get a particular AD group's data given a DN.
329
     *
330
     * @param string $dn
331
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
332
     * @return array
333
     */
334 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...
335
    {
336
        $searchLocations = $this->config()->groups_search_locations ?: [null];
337
        foreach ($searchLocations as $searchLocation) {
338
            $records = $this->gateway->getGroupByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
339
            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...
340
                return $records[0];
341
            }
342
        }
343
    }
344
345
    /**
346
     * Return all AD users in configured search locations, including all users in nested groups.
347
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
348
     * to use the default baseDn defined in the connection.
349
     *
350
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
351
     * @return array
352
     */
353
    public function getUsers($attributes = [])
354
    {
355
        $searchLocations = $this->config()->users_search_locations ?: [null];
356
        $results = [];
357
358 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...
359
            $records = $this->gateway->getUsers($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
360
            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...
361
                continue;
362
            }
363
364
            foreach ($records as $record) {
365
                $results[$record['objectguid']] = $record;
366
            }
367
        }
368
369
        return $results;
370
    }
371
372
    /**
373
     * Get a specific AD user's data given a GUID.
374
     *
375
     * @param string $guid
376
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
377
     * @return array
378
     */
379 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...
380
    {
381
        $searchLocations = $this->config()->users_search_locations ?: [null];
382
        foreach ($searchLocations as $searchLocation) {
383
            $records = $this->gateway->getUserByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
384
            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...
385
                return $records[0];
386
            }
387
        }
388
    }
389
390
    /**
391
     * Get a specific AD user's data given a DN.
392
     *
393
     * @param string $dn
394
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
395
     *
396
     * @return array
397
     */
398 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...
399
    {
400
        $searchLocations = $this->config()->users_search_locations ?: [null];
401
        foreach ($searchLocations as $searchLocation) {
402
            $records = $this->gateway->getUserByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
403
            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...
404
                return $records[0];
405
            }
406
        }
407
    }
408
409
    /**
410
     * Get a specific user's data given an email.
411
     *
412
     * @param string $email
413
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
414
     * @return array
415
     */
416 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...
417
    {
418
        $searchLocations = $this->config()->users_search_locations ?: [null];
419
        foreach ($searchLocations as $searchLocation) {
420
            $records = $this->gateway->getUserByEmail($email, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
421
            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...
422
                return $records[0];
423
            }
424
        }
425
    }
426
427
    /**
428
     * Get a specific user's data given a username.
429
     *
430
     * @param string $username
431
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
432
     * @return array
433
     */
434 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...
435
    {
436
        $searchLocations = $this->config()->users_search_locations ?: [null];
437
        foreach ($searchLocations as $searchLocation) {
438
            $records = $this->gateway->getUserByUsername($username, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
439
            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...
440
                return $records[0];
441
            }
442
        }
443
    }
444
445
    /**
446
     * Get a username for an email.
447
     *
448
     * @param string $email
449
     * @return string|null
450
     */
451
    public function getUsernameByEmail($email)
452
    {
453
        $data = $this->getUserByEmail($email);
454
        if (empty($data)) {
455
            return null;
456
        }
457
458
        return $this->gateway->getCanonicalUsername($data);
459
    }
460
461
    /**
462
     * Given a group DN, get the group membership data in LDAP.
463
     *
464
     * @param string $dn
465
     * @return array
466
     */
467
    public function getLDAPGroupMembers($dn)
468
    {
469
        $groupObj = Group::get()->filter('DN', $dn)->first();
470
        $groupData = $this->getGroupByGUID($groupObj->GUID);
471
        $members = !empty($groupData['member']) ? $groupData['member'] : [];
472
        // If a user belongs to a single group, this comes through as a string.
473
        // Normalise to a array so it's consistent.
474
        if ($members && is_string($members)) {
475
            $members = [$members];
476
        }
477
478
        return $members;
479
    }
480
481
    /**
482
     * Update the current Member record with data from LDAP.
483
     *
484
     * Constraints:
485
     * - Member *must* be in the database before calling this as it will need the ID to be mapped to a {@link Group}.
486
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
487
     *
488
     * @param Member
489
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
490
     *            If not given, the data will be looked up by the user's GUID.
491
     * @return bool
492
     */
493
    public function updateMemberFromLDAP(Member $member, $data = null)
494
    {
495
        if (!$this->enabled()) {
496
            return false;
497
        }
498
499
        if (!$member->GUID) {
500
            $this->getLogger()->warn(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method warn() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

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

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

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

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

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

Available Fixes

  1. Change the type-hint for the parameter:

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

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

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
501
            return false;
502
        }
503
504
        if (!$data) {
505
            $data = $this->getUserByGUID($member->GUID);
506
            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...
507
                $this->getLogger()->warn(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method warn() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

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

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

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

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

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

Available Fixes

  1. Change the type-hint for the parameter:

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

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

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
508
                return false;
509
            }
510
        }
511
512
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
513
        $member->LastSynced = (string)DBDatetime::now();
514
515
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
516
            if (!isset($data[$attribute])) {
517
                $this->getLogger()->notice(
518
                    sprintf(
519
                        'Attribute %s configured in Member.ldap_field_mappings, but no available attribute in AD data (GUID: %s, Member ID: %s)',
520
                        $attribute,
521
                        $data['objectguid'],
522
                        $member->ID
523
                    )
524
                );
525
526
                continue;
527
            }
528
529
            if ($attribute == 'thumbnailphoto') {
530
                $imageClass = $member->getRelationClass($field);
531
                if ($imageClass !== Image::class
532
                    && !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...
533
                ) {
534
                    $this->getLogger()->warn(
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method warn() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

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

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

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

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

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

Available Fixes

  1. Change the type-hint for the parameter:

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

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

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

Let’s take a look at an example:

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

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

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

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

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

Available Fixes

  1. Change the type-hint for the parameter:

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

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

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

Let’s take a look at an example:

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

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

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

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

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

Available Fixes

  1. Change the type-hint for the parameter:

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

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

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
599
                            sprintf(
600
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
601
                                $mapping->ID
602
                            )
603
                        );
604
                        continue;
605
                    }
606
607
                    // the user is a direct member of group with a mapping, add them to the SS group.
608 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...
609
                        $group = $mapping->Group();
610
                        if ($group && $group->exists()) {
611
                            $group->Members()->add($member, [
612
                                'IsImportedFromLDAP' => '1'
613
                            ]);
614
                            $mappedGroupIDs[] = $mapping->GroupID;
615
                        }
616
                    }
617
618
                    // the user *might* be a member of a nested group provided the scope of the mapping
619
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
620
                    // to see if they are a member of one of those. If they are, add them to the SS group
621
                    if ($mapping->Scope == 'Subtree') {
622
                        $childGroups = $this->getNestedGroups($mapping->DN, ['dn']);
623
                        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...
624
                            continue;
625
                        }
626
627
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
628 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...
629
                                $group = $mapping->Group();
630
                                if ($group && $group->exists()) {
631
                                    $group->Members()->add($member, [
632
                                        'IsImportedFromLDAP' => '1'
633
                                    ]);
634
                                    $mappedGroupIDs[] = $mapping->GroupID;
635
                                }
636
                            }
637
                        }
638
                    }
639
                }
640
            }
641
        }
642
643
        // remove the user from any previously mapped groups, where the mapping has since been removed
644
        $groupRecords = DB::query(
645
            sprintf(
646
                'SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s',
647
                $member->ID
648
            )
649
        );
650
651
        foreach ($groupRecords as $groupRecord) {
652
            if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
653
                $group = Group::get()->byId($groupRecord['GroupID']);
654
                // Some groups may no longer exist. SilverStripe does not clean up join tables.
655
                if ($group) {
656
                    $group->Members()->remove($member);
657
                }
658
            }
659
        }
660
        // This will throw an exception if there are two distinct GUIDs with the same email address.
661
        // We are happy with a raw 500 here at this stage.
662
        $member->write();
663
    }
664
665
    /**
666
     * Sync a specific Group by updating it with LDAP data.
667
     *
668
     * @param Group $group An existing Group or a new Group object
669
     * @param array $data LDAP group object data
670
     *
671
     * @return bool
672
     */
673
    public function updateGroupFromLDAP(Group $group, $data)
674
    {
675
        if (!$this->enabled()) {
676
            return false;
677
        }
678
679
        // Synchronise specific guaranteed fields.
680
        $group->Code = $data['samaccountname'];
681
        $group->Title = $data['samaccountname'];
682
        if (!empty($data['description'])) {
683
            $group->Description = $data['description'];
684
        }
685
        $group->DN = $data['dn'];
686
        $group->LastSynced = (string)DBDatetime::now();
687
        $group->write();
688
689
        // Mappings on this group are automatically maintained to contain just the group's DN.
690
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
691
        $hasCorrectMapping = false;
692
        foreach ($group->LDAPGroupMappings() as $mapping) {
693
            if ($mapping->DN === $data['dn']) {
694
                // This is the correct mapping we want to retain.
695
                $hasCorrectMapping = true;
696
            } else {
697
                $mapping->delete();
698
            }
699
        }
700
701
        // Second, if the main mapping was not found, add it in.
702
        if (!$hasCorrectMapping) {
703
            $mapping = new LDAPGroupMapping();
704
            $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...
705
            $mapping->write();
706
            $group->LDAPGroupMappings()->add($mapping);
707
        }
708
    }
709
710
    /**
711
     * Creates a new LDAP user from the passed Member record.
712
     * Note that the Member record must have a non-empty Username field for this to work.
713
     *
714
     * @param Member $member
715
     * @throws ValidationException
716
     * @throws Exception
717
     */
718
    public function createLDAPUser(Member $member)
719
    {
720
        if (!$this->enabled()) {
721
            return;
722
        }
723
        if (empty($member->Username)) {
724
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
725
        }
726
        if (!$this->config()->new_users_dn) {
727
            throw new Exception('LDAPService::new_users_dn must be configured to create LDAP users');
728
        }
729
730
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
731
        $member->Username = strtolower($member->Username);
732
733
        // Create user in LDAP using available information.
734
        $dn = sprintf('CN=%s,%s', $member->Username, $this->config()->new_users_dn);
735
736
        try {
737
            $this->add($dn, [
738
                'objectclass' => 'user',
739
                'cn' => $member->Username,
740
                'accountexpires' => '9223372036854775807',
741
                'useraccountcontrol' => '66048',
742
                'userprincipalname' => sprintf(
743
                    '%s@%s',
744
                    $member->Username,
745
                    $this->gateway->config()->options['accountDomainName']
746
                ),
747
            ]);
748
        } catch (Exception $e) {
749
            throw new ValidationException('LDAP synchronisation failure: ' . $e->getMessage());
750
        }
751
752
        $user = $this->getUserByUsername($member->Username);
753
        if (empty($user['objectguid'])) {
754
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
755
        }
756
757
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
758
        $member->GUID = $user['objectguid'];
759
    }
760
761
    /**
762
     * Creates a new LDAP group from the passed Group record.
763
     *
764
     * @param Group $group
765
     * @throws ValidationException
766
     */
767
    public function createLDAPGroup(Group $group)
768
    {
769
        if (!$this->enabled()) {
770
            return;
771
        }
772
        if (empty($group->Title)) {
773
            throw new ValidationException('Group missing Title. Cannot create LDAP group');
774
        }
775
        if (!$this->config()->new_groups_dn) {
776
            throw new Exception('LDAPService::new_groups_dn must be configured to create LDAP groups');
777
        }
778
779
        // LDAP isn't really meant to distinguish between a Title and Code. Squash them.
780
        $group->Code = $group->Title;
781
782
        $dn = sprintf('CN=%s,%s', $group->Title, $this->config()->new_groups_dn);
783
        try {
784
            $this->add($dn, [
785
                'objectclass' => 'group',
786
                'cn' => $group->Title,
787
                'name' => $group->Title,
788
                'samaccountname' => $group->Title,
789
                'description' => $group->Description,
790
                'distinguishedname' => $dn
791
            ]);
792
        } catch (Exception $e) {
793
            throw new ValidationException('LDAP group creation failure: ' . $e->getMessage());
794
        }
795
796
        $data = $this->getGroupByDN($dn);
797
        if (empty($data['objectguid'])) {
798
            throw new ValidationException(
799
                new ValidationResult(
800
                    false,
801
                    'LDAP group creation failure: group might have been created in LDAP. GUID is missing.'
802
                )
803
            );
804
        }
805
806
        // Creation was successful, mark the group as LDAP managed by setting the GUID.
807
        $group->GUID = $data['objectguid'];
808
        $group->DN = $data['dn'];
809
    }
810
811
    /**
812
     * Update the Member data back to the corresponding LDAP user object.
813
     *
814
     * @param Member $member
815
     * @throws ValidationException
816
     */
817
    public function updateLDAPFromMember(Member $member)
818
    {
819
        if (!$this->enabled()) {
820
            return;
821
        }
822
        if (!$member->GUID) {
823
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
824
        }
825
826
        $data = $this->getUserByGUID($member->GUID);
827
        if (empty($data['objectguid'])) {
828
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
829
        }
830
831
        if (empty($member->Username)) {
832
            throw new ValidationException('Member missing Username. Cannot update LDAP user');
833
        }
834
835
        $dn = $data['distinguishedname'];
836
837
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
838
        $member->Username = strtolower($member->Username);
839
840
        try {
841
            // If the common name (cn) has changed, we need to ensure they've been moved
842
            // to the new DN, to avoid any clashes between user objects.
843
            if ($data['cn'] != $member->Username) {
844
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
845
                $this->move($dn, $newDn);
846
                $dn = $newDn;
847
            }
848
        } catch (Exception $e) {
849
            throw new ValidationException('LDAP move failure: '.$e->getMessage());
850
        }
851
852
        try {
853
            $attributes = [
854
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
855
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
856
                'userprincipalname' => sprintf(
857
                    '%s@%s',
858
                    $member->Username,
859
                    $this->gateway->config()->options['accountDomainName']
860
                ),
861
            ];
862
            foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
863
                $relationClass = $member->getRelationClass($field);
864
                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...
865
                    // todo no support for writing back relations yet.
866
                } else {
867
                    $attributes[$attribute] = $member->$field;
868
                }
869
            }
870
871
            $this->update($dn, $attributes);
872
        } catch (Exception $e) {
873
            throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
874
        }
875
    }
876
877
    /**
878
     * Ensure the user belongs to the correct groups in LDAP from their membership
879
     * to local LDAP mapped SilverStripe groups.
880
     *
881
     * This also removes them from LDAP groups if they've been taken out of one.
882
     * It will not affect group membership of non-mapped groups, so it will
883
     * not touch such internal AD groups like "Domain Users".
884
     *
885
     * @param Member $member
886
     * @throws ValidationException
887
     */
888
    public function updateLDAPGroupsForMember(Member $member)
889
    {
890
        if (!$this->enabled()) {
891
            return;
892
        }
893
        if (!$member->GUID) {
894
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
895
        }
896
897
        $addGroups = [];
898
        $removeGroups = [];
899
900
        $user = $this->getUserByGUID($member->GUID);
901
        if (empty($user['objectguid'])) {
902
            throw new ValidationException('LDAP update failure: user missing GUID');
903
        }
904
905
        // If a user belongs to a single group, this comes through as a string.
906
        // Normalise to a array so it's consistent.
907
        $existingGroups = !empty($user['memberof']) ? $user['memberof'] : [];
908
        if ($existingGroups && is_string($existingGroups)) {
909
            $existingGroups = [$existingGroups];
910
        }
911
912
        foreach ($member->Groups() as $group) {
913
            if (!$group->GUID) {
914
                continue;
915
            }
916
917
            // mark this group as something we need to ensure the user belongs to in LDAP.
918
            $addGroups[] = $group->DN;
919
        }
920
921
        // Which existing LDAP groups are not in the add groups? We'll check these groups to
922
        // see if the user should be removed from any of them.
923
        $remainingGroups = array_diff($existingGroups, $addGroups);
924
925
        foreach ($remainingGroups as $groupDn) {
926
            // We only want to be removing groups we have a local Group mapped to. Removing
927
            // membership for anything else would be bad!
928
            $group = Group::get()->filter('DN', $groupDn)->first();
929
            if (!$group || !$group->exists()) {
930
                continue;
931
            }
932
933
            // this group should be removed from the user's memberof attribute, as it's been removed.
934
            $removeGroups[] = $groupDn;
935
        }
936
937
        // go through the groups we want the user to be in and ensure they're in them.
938
        foreach ($addGroups as $groupDn) {
939
            $this->addLDAPUserToGroup($user['distinguishedname'], $groupDn);
940
        }
941
942
        // go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
943
        foreach ($removeGroups as $groupDn) {
944
            $members = $this->getLDAPGroupMembers($groupDn);
945
946
            // remove the user from the members data.
947
            if (in_array($user['distinguishedname'], $members)) {
948
                foreach ($members as $i => $dn) {
949
                    if ($dn == $user['distinguishedname']) {
950
                        unset($members[$i]);
951
                    }
952
                }
953
            }
954
955
            try {
956
                $this->update($groupDn, ['member' => $members]);
957
            } catch (Exception $e) {
958
                throw new ValidationException('LDAP group membership remove failure: ' . $e->getMessage());
959
            }
960
        }
961
    }
962
963
    /**
964
     * Add LDAP user by DN to LDAP group.
965
     *
966
     * @param string $userDn
967
     * @param string $groupDn
968
     * @throws Exception
969
     */
970
    public function addLDAPUserToGroup($userDn, $groupDn)
971
    {
972
        $members = $this->getLDAPGroupMembers($groupDn);
973
974
        // this user is already in the group, no need to do anything.
975
        if (in_array($userDn, $members)) {
976
            return;
977
        }
978
979
        $members[] = $userDn;
980
981
        try {
982
            $this->update($groupDn, ['member' => $members]);
983
        } catch (Exception $e) {
984
            throw new ValidationException('LDAP group membership add failure: ' . $e->getMessage());
985
        }
986
    }
987
988
    /**
989
     * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the
990
     * password in the `unicodePwd` attribute.
991
     *
992
     * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in
993
     * an abstract way, so it works on other LDAP directories, not just Active Directory.
994
     *
995
     * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure.
996
     *
997
     * @param Member $member
998
     * @param string $password
999
     * @param string|null $oldPassword Supply old password to perform a password change (as opposed to password reset)
1000
     * @return ValidationResult
1001
     */
1002
    public function setPassword(Member $member, $password, $oldPassword = null)
1003
    {
1004
        $validationResult = ValidationResult::create();
1005
1006
        $this->extend('onBeforeSetPassword', $member, $password, $validationResult);
1007
1008
        if (!$member->GUID) {
1009
            $this->getLogger()->warn(sprintf('Cannot update Member ID %s, GUID not set', $member->ID));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method warn() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

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

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

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

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

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

Available Fixes

  1. Change the type-hint for the parameter:

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

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

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