Completed
Pull Request — master (#103)
by Sean
02:15
created

LDAPService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace SilverStripe\ActiveDirectory\Services;
4
5
use Exception;
6
use Psr\Log\LoggerInterface;
7
use Psr\SimpleCache\CacheInterface;
8
use SilverStripe\ActiveDirectory\Model\LDAPGateway;
9
use SilverStripe\ActiveDirectory\Model\LDAPGroupMapping;
10
use SilverStripe\Assets\Image;
11
use SilverStripe\Assets\Filesystem;
12
use SilverStripe\Core\Config\Config;
13
use SilverStripe\Core\Flushable;
14
use SilverStripe\Core\Extensible;
15
use SilverStripe\Core\Injector\Injector;
16
use SilverStripe\Core\Injector\Injectable;
17
use SilverStripe\ORM\DB;
18
use SilverStripe\ORM\FieldType\DBDatetime;
19
use SilverStripe\ORM\ValidationException;
20
use SilverStripe\ORM\ValidationResult;
21
use SilverStripe\Security\Group;
22
use SilverStripe\Security\Member;
23
use SilverStripe\Security\RandomGenerator;
24
use Zend\Ldap\Ldap;
25
26
/**
27
 * Class LDAPService
28
 *
29
 * Provides LDAP operations expressed in terms of the SilverStripe domain.
30
 * All other modules should access LDAP through this class.
31
 *
32
 * This class builds on top of LDAPGateway's detailed code by adding:
33
 * - caching
34
 * - data aggregation and restructuring from multiple lower-level calls
35
 * - error handling
36
 *
37
 * LDAPService relies on Zend LDAP module's data structures for some parameters and some return values.
38
 *
39
 * @package activedirectory
40
 */
41
class LDAPService implements Flushable
42
{
43
    use Injectable;
44
    use Extensible;
45
46
    /**
47
     * @var array
48
     */
49
    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...
50
        'gateway' => '%$' . LDAPGateway::class
51
    ];
52
53
    /**
54
     * If configured, only user objects within these locations will be exposed to this service.
55
     *
56
     * @var array
57
     * @config
58
     */
59
    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...
60
61
    /**
62
     * If configured, only group objects within these locations will be exposed to this service.
63
     * @var array
64
     *
65
     * @config
66
     */
67
    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...
68
69
    /**
70
     * Location to create new users in (distinguished name).
71
     * @var string
72
     *
73
     * @config
74
     */
75
    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...
76
77
    /**
78
     * Location to create new groups in (distinguished name).
79
     * @var string
80
     *
81
     * @config
82
     */
83
    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...
84
85
    /**
86
     * @var array
87
     */
88
    private static $_cache_nested_groups = [];
89
90
    /**
91
     * If this is configured to a "Code" value of a {@link Group} in SilverStripe, the user will always
92
     * be added to this group's membership when imported, regardless of any sort of group mappings.
93
     *
94
     * @var string
95
     * @config
96
     */
97
    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...
98
99
    /**
100
     * For samba4 directory, there is no way to enforce password history on password resets.
101
     * This only happens with changePassword (which requires the old password).
102
     * This works around it by making the old password up and setting it administratively.
103
     *
104
     * A cleaner fix would be to use the LDAP_SERVER_POLICY_HINTS_OID connection flag,
105
     * but it's not implemented in samba https://bugzilla.samba.org/show_bug.cgi?id=12020
106
     *
107
     * @var bool
108
     */
109
    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...
110
111
    /**
112
     * Get the cache object used for LDAP results. Note that the default lifetime set here
113
     * is 8 hours, but you can change that by adding configuration:
114
     *
115
     * <code>
116
     * SilverStripe\Core\Injector\Injector:
117
     *   Psr\SimpleCache\CacheInterface.ldap:
118
     *     constructor:
119
     *       defaultLifetime: 3600 # time in seconds
120
     * </code>
121
     *
122
     * @return Psr\SimpleCache\CacheInterface
123
     */
124
    public static function get_cache()
125
    {
126
        return Injector::inst()->get(CacheInterface::class . '.ldap');
127
    }
128
129
    /**
130
     * Flushes out the LDAP results cache when flush=1 is called.
131
     */
132
    public static function flush()
133
    {
134
        /** @var CacheInterface $cache */
135
        $cache = self::get_cache();
136
        $cache->clear();
137
    }
138
139
    /**
140
     * @var LDAPGateway
141
     */
142
    public $gateway;
143
144
    public function __construct()
145
    {
146
        $this->constructExtensions();
147
    }
148
149
    /**
150
     * Setter for gateway. Useful for overriding the gateway with a fake for testing.
151
     * @var LDAPGateway
152
     */
153
    public function setGateway($gateway)
154
    {
155
        $this->gateway = $gateway;
156
    }
157
158
    /**
159
     * Checkes whether or not the service is enabled.
160
     *
161
     * @return bool
162
     */
163
    public function enabled()
164
    {
165
        $options = Config::inst()->get(LDAPGateway::class, 'options');
166
        return !empty($options);
167
    }
168
169
    /**
170
     * Authenticate the given username and password with LDAP.
171
     *
172
     * @param string $username
173
     * @param string $password
174
     *
175
     * @return array
176
     */
177
    public function authenticate($username, $password)
178
    {
179
        $result = $this->gateway->authenticate($username, $password);
180
        $messages = $result->getMessages();
181
182
        // all messages beyond the first one are for debugging and
183
        // not suitable to display to the user.
184
        foreach ($messages as $i => $message) {
185
            if ($i > 0) {
186
                $this->getLogger()->debug(str_replace("\n", "\n  ", $message));
187
            }
188
        }
189
190
        $message = $messages[0]; // first message is user readable, suitable for showing on login form
191
192
        // show better errors than the defaults for various status codes returned by LDAP
193 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...
194
            $message = _t(
195
                'LDAPService.ACCOUNTLOCKEDOUT',
196
                'Your account has been temporarily locked because of too many failed login attempts. ' .
197
                'Please try again later.'
198
            );
199
        }
200 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...
201
            $message = _t(
202
                'LDAPService.INVALIDCREDENTIALS',
203
                'The provided details don\'t seem to be correct. Please try again.'
204
            );
205
        }
206
207
        return [
208
            'success' => $result->getCode() === 1,
209
            'identity' => $result->getIdentity(),
210
            'message' => $message
211
        ];
212
    }
213
214
    /**
215
     * Return all nodes (organizational units, containers, and domains) within the current base DN.
216
     *
217
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
218
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
219
     * @return array
220
     */
221
    public function getNodes($cached = true, $attributes = [])
222
    {
223
        $cache = self::get_cache();
224
        $cacheKey = 'nodes' . md5(implode('', $attributes));
225
        $results = $cache->has($cacheKey);
226
227
        if (!$results || !$cached) {
228
            $results = [];
229
            $records = $this->gateway->getNodes(null, Ldap::SEARCH_SCOPE_SUB, $attributes);
230
            foreach ($records as $record) {
231
                $results[$record['dn']] = $record;
232
            }
233
234
            $cache->set($cacheKey, $results);
235
        }
236
237
        return $results;
238
    }
239
240
    /**
241
     * Return all AD groups in configured search locations, including all nested groups.
242
     * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
243
     * to use the default baseDn defined in the connection.
244
     *
245
     * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default.
246
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
247
     * @param string $indexBy Attribute to use as an index.
248
     * @return array
249
     */
250
    public function getGroups($cached = true, $attributes = [], $indexBy = 'dn')
251
    {
252
        $searchLocations = $this->config()->groups_search_locations ?: [null];
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
253
        $cache = self::get_cache();
254
        $cacheKey = 'groups' . md5(implode('', array_merge($searchLocations, $attributes)));
255
        $results = $cache->has($cacheKey);
256
257
        if (!$results || !$cached) {
258
            $results = [];
259 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...
260
                $records = $this->gateway->getGroups($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
261
                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...
262
                    continue;
263
                }
264
265
                foreach ($records as $record) {
266
                    $results[$record[$indexBy]] = $record;
267
                }
268
            }
269
270
            $cache->set($cacheKey, $results);
271
        }
272
273
        if ($cached && $results === true) {
274
            $results = $cache->get($cacheKey);
275
        }
276
277
        return $results;
278
    }
279
280
    /**
281
     * Return all member groups (and members of those, recursively) underneath a specific group DN.
282
     * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results.
283
     *
284
     * @param string $dn
285
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
286
     * @return array
287
     */
288
    public function getNestedGroups($dn, $attributes = [])
289
    {
290
        if (isset(self::$_cache_nested_groups[$dn])) {
291
            return self::$_cache_nested_groups[$dn];
292
        }
293
294
        $searchLocations = $this->config()->groups_search_locations ?: [null];
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
295
        $results = [];
296 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...
297
            $records = $this->gateway->getNestedGroups($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
298
            foreach ($records as $record) {
299
                $results[$record['dn']] = $record;
300
            }
301
        }
302
303
        self::$_cache_nested_groups[$dn] = $results;
304
        return $results;
305
    }
306
307
    /**
308
     * Get a particular AD group's data given a GUID.
309
     *
310
     * @param string $guid
311
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
312
     * @return array
313
     */
314 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...
315
    {
316
        $searchLocations = $this->config()->groups_search_locations ?: [null];
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
317
        foreach ($searchLocations as $searchLocation) {
318
            $records = $this->gateway->getGroupByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
319
            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...
320
                return $records[0];
321
            }
322
        }
323
    }
324
325
    /**
326
     * Get a particular AD group's data given a DN.
327
     *
328
     * @param string $dn
329
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
330
     * @return array
331
     */
332 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...
333
    {
334
        $searchLocations = $this->config()->groups_search_locations ?: [null];
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
335
        foreach ($searchLocations as $searchLocation) {
336
            $records = $this->gateway->getGroupByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
337
            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...
338
                return $records[0];
339
            }
340
        }
341
    }
342
343
    /**
344
     * Return all AD users in configured search locations, including all users in nested groups.
345
     * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway
346
     * to use the default baseDn defined in the connection.
347
     *
348
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
349
     * @return array
350
     */
351
    public function getUsers($attributes = [])
352
    {
353
        $searchLocations = $this->config()->users_search_locations ?: [null];
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
354
        $results = [];
355
356 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...
357
            $records = $this->gateway->getUsers($searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
358
            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...
359
                continue;
360
            }
361
362
            foreach ($records as $record) {
363
                $results[$record['objectguid']] = $record;
364
            }
365
        }
366
367
        return $results;
368
    }
369
370
    /**
371
     * Get a specific AD user's data given a GUID.
372
     *
373
     * @param string $guid
374
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
375
     * @return array
376
     */
377 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...
378
    {
379
        $searchLocations = $this->config()->users_search_locations ?: [null];
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
380
        foreach ($searchLocations as $searchLocation) {
381
            $records = $this->gateway->getUserByGUID($guid, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
382
            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...
383
                return $records[0];
384
            }
385
        }
386
    }
387
388
    /**
389
     * Get a specific AD user's data given a DN.
390
     *
391
     * @param string $dn
392
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
393
     *
394
     * @return array
395
     */
396 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...
397
    {
398
        $searchLocations = $this->config()->users_search_locations ?: [null];
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
399
        foreach ($searchLocations as $searchLocation) {
400
            $records = $this->gateway->getUserByDN($dn, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
401
            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...
402
                return $records[0];
403
            }
404
        }
405
    }
406
407
    /**
408
     * Get a specific user's data given an email.
409
     *
410
     * @param string $email
411
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
412
     * @return array
413
     */
414 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...
415
    {
416
        $searchLocations = $this->config()->users_search_locations ?: [null];
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
417
        foreach ($searchLocations as $searchLocation) {
418
            $records = $this->gateway->getUserByEmail($email, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
419
            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...
420
                return $records[0];
421
            }
422
        }
423
    }
424
425
    /**
426
     * Get a specific user's data given a username.
427
     *
428
     * @param string $username
429
     * @param array $attributes List of specific AD attributes to return. Empty array means return everything.
430
     * @return array
431
     */
432 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...
433
    {
434
        $searchLocations = $this->config()->users_search_locations ?: [null];
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
435
        foreach ($searchLocations as $searchLocation) {
436
            $records = $this->gateway->getUserByUsername($username, $searchLocation, Ldap::SEARCH_SCOPE_SUB, $attributes);
437
            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...
438
                return $records[0];
439
            }
440
        }
441
    }
442
443
    /**
444
     * Get a username for an email.
445
     *
446
     * @param string $email
447
     * @return string|null
448
     */
449
    public function getUsernameByEmail($email)
450
    {
451
        $data = $this->getUserByEmail($email);
452
        if (empty($data)) {
453
            return null;
454
        }
455
456
        return $this->gateway->getCanonicalUsername($data);
457
    }
458
459
    /**
460
     * Given a group DN, get the group membership data in LDAP.
461
     *
462
     * @param string $dn
463
     * @return array
464
     */
465
    public function getLDAPGroupMembers($dn)
466
    {
467
        $groupObj = Group::get()->filter('DN', $dn)->first();
468
        $groupData = $this->getGroupByGUID($groupObj->GUID);
469
        $members = !empty($groupData['member']) ? $groupData['member'] : [];
470
        // If a user belongs to a single group, this comes through as a string.
471
        // Normalise to a array so it's consistent.
472
        if ($members && is_string($members)) {
473
            $members = [$members];
474
        }
475
476
        return $members;
477
    }
478
479
    /**
480
     * Update the current Member record with data from LDAP.
481
     *
482
     * Constraints:
483
     * - Member *must* be in the database before calling this as it will need the ID to be mapped to a {@link Group}.
484
     * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here.
485
     *
486
     * @param Member
487
     * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with.
488
     *            If not given, the data will be looked up by the user's GUID.
489
     * @return bool
490
     */
491
    public function updateMemberFromLDAP(Member $member, $data = null)
492
    {
493
        if (!$this->enabled()) {
494
            return false;
495
        }
496
497
        if (!$member->GUID) {
498
            $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...
499
            return false;
500
        }
501
502
        if (!$data) {
503
            $data = $this->getUserByGUID($member->GUID);
504
            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...
505
                $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...
506
                return false;
507
            }
508
        }
509
510
        $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2;
511
        $member->LastSynced = (string)DBDatetime::now();
512
513
        foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
514
            if (!isset($data[$attribute])) {
515
                $this->getLogger()->notice(
516
                    sprintf(
517
                        'Attribute %s configured in Member.ldap_field_mappings, but no available attribute in AD data (GUID: %s, Member ID: %s)',
518
                        $attribute,
519
                        $data['objectguid'],
520
                        $member->ID
521
                    )
522
                );
523
524
                continue;
525
            }
526
527
            if ($attribute == 'thumbnailphoto') {
528
                $imageClass = $member->getRelationClass($field);
529
                if ($imageClass !== Image::class
530
                    && !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...
531
                ) {
532
                    $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...
533
                        sprintf(
534
                            'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an Image class',
535
                            $field
536
                        )
537
                    );
538
539
                    continue;
540
                }
541
542
                $filename = sprintf('thumbnailphoto-%s.jpg', $data['samaccountname']);
543
                $path = ASSETS_DIR . '/' . $member->config()->ldap_thumbnail_path;
544
                $absPath = BASE_PATH . '/' . $path;
545
                if (!file_exists($absPath)) {
546
                    Filesystem::makeFolder($absPath);
547
                }
548
549
                // remove existing record if it exists
550
                $existingObj = $member->getComponent($field);
551
                if ($existingObj && $existingObj->exists()) {
552
                    $existingObj->delete();
553
                }
554
555
                // The image data is provided in raw binary.
556
                file_put_contents($absPath . '/' . $filename, $data[$attribute]);
557
                $record = new $imageClass();
558
                $record->Name = $filename;
559
                $record->Filename = $path . '/' . $filename;
560
                $record->write();
561
562
                $relationField = $field . 'ID';
563
                $member->{$relationField} = $record->ID;
564
            } else {
565
                $member->$field = $data[$attribute];
566
            }
567
        }
568
569
        // if a default group was configured, ensure the user is in that group
570
        if ($this->config()->default_group) {
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
571
            $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first();
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
572
            if (!($group && $group->exists())) {
573
                $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...
574
                    sprintf(
575
                        'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'',
576
                        $this->config()->default_group
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
577
                    )
578
                );
579
            } else {
580
                $group->Members()->add($member, [
581
                    'IsImportedFromLDAP' => '1'
582
                ]);
583
            }
584
        }
585
586
        // this is to keep track of which groups the user gets mapped to
587
        // and we'll use that later to remove them from any groups that they're no longer mapped to
588
        $mappedGroupIDs = [];
589
590
        // ensure the user is in any mapped groups
591
        if (isset($data['memberof'])) {
592
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : [$data['memberof']];
593
            foreach ($ldapGroups as $groupDN) {
594
                foreach (LDAPGroupMapping::get() as $mapping) {
595
                    if (!$mapping->DN) {
596
                        $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...
597
                            sprintf(
598
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
599
                                $mapping->ID
600
                            )
601
                        );
602
                        continue;
603
                    }
604
605
                    // the user is a direct member of group with a mapping, add them to the SS group.
606 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...
607
                        $group = $mapping->Group();
608
                        if ($group && $group->exists()) {
609
                            $group->Members()->add($member, [
610
                                'IsImportedFromLDAP' => '1'
611
                            ]);
612
                            $mappedGroupIDs[] = $mapping->GroupID;
613
                        }
614
                    }
615
616
                    // the user *might* be a member of a nested group provided the scope of the mapping
617
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
618
                    // to see if they are a member of one of those. If they are, add them to the SS group
619
                    if ($mapping->Scope == 'Subtree') {
620
                        $childGroups = $this->getNestedGroups($mapping->DN, ['dn']);
621
                        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...
622
                            continue;
623
                        }
624
625
                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
626 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...
627
                                $group = $mapping->Group();
628
                                if ($group && $group->exists()) {
629
                                    $group->Members()->add($member, [
630
                                        'IsImportedFromLDAP' => '1'
631
                                    ]);
632
                                    $mappedGroupIDs[] = $mapping->GroupID;
633
                                }
634
                            }
635
                        }
636
                    }
637
                }
638
            }
639
        }
640
641
        // remove the user from any previously mapped groups, where the mapping has since been removed
642
        $groupRecords = DB::query(
643
            sprintf(
644
                'SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s',
645
                $member->ID
646
            )
647
        );
648
649
        foreach ($groupRecords as $groupRecord) {
650
            if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) {
651
                $group = Group::get()->byId($groupRecord['GroupID']);
652
                // Some groups may no longer exist. SilverStripe does not clean up join tables.
653
                if ($group) {
654
                    $group->Members()->remove($member);
655
                }
656
            }
657
        }
658
        // This will throw an exception if there are two distinct GUIDs with the same email address.
659
        // We are happy with a raw 500 here at this stage.
660
        $member->write();
661
    }
662
663
    /**
664
     * Sync a specific Group by updating it with LDAP data.
665
     *
666
     * @param Group $group An existing Group or a new Group object
667
     * @param array $data LDAP group object data
668
     *
669
     * @return bool
670
     */
671
    public function updateGroupFromLDAP(Group $group, $data)
672
    {
673
        if (!$this->enabled()) {
674
            return false;
675
        }
676
677
        // Synchronise specific guaranteed fields.
678
        $group->Code = $data['samaccountname'];
679
        $group->Title = $data['samaccountname'];
680
        if (!empty($data['description'])) {
681
            $group->Description = $data['description'];
682
        }
683
        $group->DN = $data['dn'];
684
        $group->LastSynced = (string)DBDatetime::now();
685
        $group->write();
686
687
        // Mappings on this group are automatically maintained to contain just the group's DN.
688
        // First, scan through existing mappings and remove ones that are not matching (in case the group moved).
689
        $hasCorrectMapping = false;
690
        foreach ($group->LDAPGroupMappings() as $mapping) {
691
            if ($mapping->DN === $data['dn']) {
692
                // This is the correct mapping we want to retain.
693
                $hasCorrectMapping = true;
694
            } else {
695
                $mapping->delete();
696
            }
697
        }
698
699
        // Second, if the main mapping was not found, add it in.
700
        if (!$hasCorrectMapping) {
701
            $mapping = new LDAPGroupMapping();
702
            $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...
703
            $mapping->write();
704
            $group->LDAPGroupMappings()->add($mapping);
705
        }
706
    }
707
708
    /**
709
     * Creates a new LDAP user from the passed Member record.
710
     * Note that the Member record must have a non-empty Username field for this to work.
711
     *
712
     * @param Member $member
713
     * @throws ValidationException
714
     * @throws Exception
715
     */
716
    public function createLDAPUser(Member $member)
717
    {
718
        if (!$this->enabled()) {
719
            return;
720
        }
721
        if (empty($member->Username)) {
722
            throw new ValidationException('Member missing Username. Cannot create LDAP user');
723
        }
724
        if (!$this->config()->new_users_dn) {
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
725
            throw new Exception('LDAPService::new_users_dn must be configured to create LDAP users');
726
        }
727
728
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
729
        $member->Username = strtolower($member->Username);
730
731
        // Create user in LDAP using available information.
732
        $dn = sprintf('CN=%s,%s', $member->Username, $this->config()->new_users_dn);
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
733
734
        try {
735
            $this->add($dn, [
736
                'objectclass' => 'user',
737
                'cn' => $member->Username,
738
                'accountexpires' => '9223372036854775807',
739
                'useraccountcontrol' => '66048',
740
                'userprincipalname' => sprintf(
741
                    '%s@%s',
742
                    $member->Username,
743
                    $this->gateway->config()->options['accountDomainName']
0 ignored issues
show
Bug introduced by
The method config() does not seem to exist on object<SilverStripe\Acti...tory\Model\LDAPGateway>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
744
                ),
745
            ]);
746
        } catch (Exception $e) {
747
            throw new ValidationException('LDAP synchronisation failure: ' . $e->getMessage());
748
        }
749
750
        $user = $this->getUserByUsername($member->Username);
751
        if (empty($user['objectguid'])) {
752
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
753
        }
754
755
        // Creation was successful, mark the user as LDAP managed by setting the GUID.
756
        $member->GUID = $user['objectguid'];
757
    }
758
759
    /**
760
     * Creates a new LDAP group from the passed Group record.
761
     *
762
     * @param Group $group
763
     * @throws ValidationException
764
     */
765
    public function createLDAPGroup(Group $group)
766
    {
767
        if (!$this->enabled()) {
768
            return;
769
        }
770
        if (empty($group->Title)) {
771
            throw new ValidationException('Group missing Title. Cannot create LDAP group');
772
        }
773
        if (!$this->config()->new_groups_dn) {
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
774
            throw new Exception('LDAPService::new_groups_dn must be configured to create LDAP groups');
775
        }
776
777
        // LDAP isn't really meant to distinguish between a Title and Code. Squash them.
778
        $group->Code = $group->Title;
779
780
        $dn = sprintf('CN=%s,%s', $group->Title, $this->config()->new_groups_dn);
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ActiveDirectory\Services\LDAPService. Did you maybe mean get_extra_config_sources()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
781
        try {
782
            $this->add($dn, [
783
                'objectclass' => 'group',
784
                'cn' => $group->Title,
785
                'name' => $group->Title,
786
                'samaccountname' => $group->Title,
787
                'description' => $group->Description,
788
                'distinguishedname' => $dn
789
            ]);
790
        } catch (Exception $e) {
791
            throw new ValidationException('LDAP group creation failure: ' . $e->getMessage());
792
        }
793
794
        $data = $this->getGroupByDN($dn);
795
        if (empty($data['objectguid'])) {
796
            throw new ValidationException(
797
                new ValidationResult(
798
                    false,
799
                    'LDAP group creation failure: group might have been created in LDAP. GUID is missing.'
800
                )
801
            );
802
        }
803
804
        // Creation was successful, mark the group as LDAP managed by setting the GUID.
805
        $group->GUID = $data['objectguid'];
806
        $group->DN = $data['dn'];
807
    }
808
809
    /**
810
     * Update the Member data back to the corresponding LDAP user object.
811
     *
812
     * @param Member $member
813
     * @throws ValidationException
814
     */
815
    public function updateLDAPFromMember(Member $member)
816
    {
817
        if (!$this->enabled()) {
818
            return;
819
        }
820
        if (!$member->GUID) {
821
            throw new ValidationException('Member missing GUID. Cannot update LDAP user');
822
        }
823
824
        $data = $this->getUserByGUID($member->GUID);
825
        if (empty($data['objectguid'])) {
826
            throw new ValidationException('LDAP synchronisation failure: user missing GUID');
827
        }
828
829
        if (empty($member->Username)) {
830
            throw new ValidationException('Member missing Username. Cannot update LDAP user');
831
        }
832
833
        $dn = $data['distinguishedname'];
834
835
        // Normalise username to lowercase to ensure we don't have duplicates of different cases
836
        $member->Username = strtolower($member->Username);
837
838
        try {
839
            // If the common name (cn) has changed, we need to ensure they've been moved
840
            // to the new DN, to avoid any clashes between user objects.
841
            if ($data['cn'] != $member->Username) {
842
                $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
843
                $this->move($dn, $newDn);
844
                $dn = $newDn;
845
            }
846
        } catch (Exception $e) {
847
            throw new ValidationException('LDAP move failure: '.$e->getMessage());
848
        }
849
850
        try {
851
            $attributes = [
852
                'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
853
                'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
854
                'userprincipalname' => sprintf(
855
                    '%s@%s',
856
                    $member->Username,
857
                    $this->gateway->config()->options['accountDomainName']
0 ignored issues
show
Bug introduced by
The method config() does not seem to exist on object<SilverStripe\Acti...tory\Model\LDAPGateway>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

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