Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like LDAPService often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use LDAPService, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 15 | class LDAPService extends Object implements Flushable |
||
|
|
|||
| 16 | { |
||
| 17 | /** |
||
| 18 | * @var array |
||
| 19 | */ |
||
| 20 | private static $dependencies = array( |
||
| 21 | 'gateway' => '%$LDAPGateway' |
||
| 22 | ); |
||
| 23 | |||
| 24 | /** |
||
| 25 | * If configured, only user objects within these locations will be exposed to this service. |
||
| 26 | * |
||
| 27 | * @var array |
||
| 28 | * @config |
||
| 29 | */ |
||
| 30 | private static $users_search_locations = array(); |
||
| 31 | |||
| 32 | /** |
||
| 33 | * If configured, only group objects within these locations will be exposed to this service. |
||
| 34 | * @var array |
||
| 35 | * |
||
| 36 | * @config |
||
| 37 | */ |
||
| 38 | private static $groups_search_locations = array(); |
||
| 39 | |||
| 40 | /** |
||
| 41 | * @var array |
||
| 42 | */ |
||
| 43 | private static $_cache_nested_groups = array(); |
||
| 44 | |||
| 45 | /** |
||
| 46 | * If this is configured to a "Code" value of a {@link Group} in SilverStripe, the user will always |
||
| 47 | * be added to this group's membership when imported, regardless of any sort of group mappings. |
||
| 48 | * |
||
| 49 | * @var string |
||
| 50 | * @config |
||
| 51 | */ |
||
| 52 | private static $default_group; |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Get the cache objecgt used for LDAP results. Note that the default lifetime set here |
||
| 56 | * is 8 hours, but you can change that by calling SS_Cache::set_lifetime('ldap', <lifetime in seconds>) |
||
| 57 | * |
||
| 58 | * @return Zend_Cache_Frontend |
||
| 59 | */ |
||
| 60 | public static function get_cache() |
||
| 67 | |||
| 68 | /** |
||
| 69 | * Flushes out the LDAP results cache when flush=1 is called. |
||
| 70 | */ |
||
| 71 | public static function flush() |
||
| 76 | |||
| 77 | /** |
||
| 78 | * @var LDAPGateway |
||
| 79 | */ |
||
| 80 | public $gateway; |
||
| 81 | |||
| 82 | /** |
||
| 83 | * Setter for gateway. Useful for overriding the gateway with a fake for testing. |
||
| 84 | * @var LDAPGateway |
||
| 85 | */ |
||
| 86 | public function setGateway($gateway) |
||
| 90 | |||
| 91 | /** |
||
| 92 | * Checkes whether or not the service is enabled. |
||
| 93 | * |
||
| 94 | * @return bool |
||
| 95 | */ |
||
| 96 | public function enabled() |
||
| 101 | |||
| 102 | /** |
||
| 103 | * Authenticate the given username and password with LDAP. |
||
| 104 | * |
||
| 105 | * @param string $username |
||
| 106 | * @param string $password |
||
| 107 | * |
||
| 108 | * @return array |
||
| 109 | */ |
||
| 110 | public function authenticate($username, $password) |
||
| 129 | |||
| 130 | /** |
||
| 131 | * Return all nodes (organizational units, containers, and domains) within the current base DN. |
||
| 132 | * |
||
| 133 | * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default. |
||
| 134 | * @param array $attributes List of specific AD attributes to return. Empty array means return everything. |
||
| 135 | * @return array |
||
| 136 | */ |
||
| 137 | public function getNodes($cached = true, $attributes = array()) |
||
| 154 | |||
| 155 | /** |
||
| 156 | * Return all AD groups in configured search locations, including all nested groups. |
||
| 157 | * Uses groups_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway |
||
| 158 | * to use the default baseDn defined in the connection. |
||
| 159 | * |
||
| 160 | * @param boolean $cached Cache the results from AD, so that subsequent calls are faster. Enabled by default. |
||
| 161 | * @param array $attributes List of specific AD attributes to return. Empty array means return everything. |
||
| 162 | * @param string $indexBy Attribute to use as an index. |
||
| 163 | * @return array |
||
| 164 | */ |
||
| 165 | public function getGroups($cached = true, $attributes = array(), $indexBy = 'dn') |
||
| 189 | |||
| 190 | /** |
||
| 191 | * Return all member groups (and members of those, recursively) underneath a specific group DN. |
||
| 192 | * Note that these get cached in-memory per-request for performance to avoid re-querying for the same results. |
||
| 193 | * |
||
| 194 | * @param string $dn |
||
| 195 | * @param array $attributes List of specific AD attributes to return. Empty array means return everything. |
||
| 196 | * @return array |
||
| 197 | */ |
||
| 198 | public function getNestedGroups($dn, $attributes = array()) |
||
| 216 | |||
| 217 | /** |
||
| 218 | * Get a particular AD group's data given a GUID. |
||
| 219 | * |
||
| 220 | * @param string $guid |
||
| 221 | * @param array $attributes List of specific AD attributes to return. Empty array means return everything. |
||
| 222 | * @return array |
||
| 223 | */ |
||
| 224 | View Code Duplication | public function getGroupByGUID($guid, $attributes = array()) |
|
| 234 | |||
| 235 | /** |
||
| 236 | * Get a particular AD group's data given a DN. |
||
| 237 | * |
||
| 238 | * @param string $dn |
||
| 239 | * @param array $attributes List of specific AD attributes to return. Empty array means return everything. |
||
| 240 | * @return array |
||
| 241 | */ |
||
| 242 | View Code Duplication | public function getGroupByDN($dn, $attributes = array()) |
|
| 252 | |||
| 253 | /** |
||
| 254 | * Return all AD users in configured search locations, including all users in nested groups. |
||
| 255 | * Uses users_search_locations if defined, otherwise falls back to NULL, which tells LDAPGateway |
||
| 256 | * to use the default baseDn defined in the connection. |
||
| 257 | * |
||
| 258 | * @param array $attributes List of specific AD attributes to return. Empty array means return everything. |
||
| 259 | * @return array |
||
| 260 | */ |
||
| 261 | public function getUsers($attributes = array()) |
||
| 279 | |||
| 280 | /** |
||
| 281 | * Get a specific AD user's data given a GUID. |
||
| 282 | * |
||
| 283 | * @param string $guid |
||
| 284 | * @param array $attributes List of specific AD attributes to return. Empty array means return everything. |
||
| 285 | * @return array |
||
| 286 | */ |
||
| 287 | View Code Duplication | public function getUserByGUID($guid, $attributes = array()) |
|
| 297 | |||
| 298 | /** |
||
| 299 | * Get a specific AD user's data given a DN. |
||
| 300 | * |
||
| 301 | * @param string $dn |
||
| 302 | * @param array $attributes List of specific AD attributes to return. Empty array means return everything. |
||
| 303 | * |
||
| 304 | * @return array |
||
| 305 | */ |
||
| 306 | View Code Duplication | public function getUserByDN($dn, $attributes = array()) |
|
| 316 | |||
| 317 | /** |
||
| 318 | * Get a specific user's data given an email. |
||
| 319 | * |
||
| 320 | * @param string $email |
||
| 321 | * @param array $attributes List of specific AD attributes to return. Empty array means return everything. |
||
| 322 | * @return array |
||
| 323 | */ |
||
| 324 | View Code Duplication | public function getUserByEmail($email, $attributes = array()) |
|
| 334 | |||
| 335 | /** |
||
| 336 | * Get a specific user's data given a username. |
||
| 337 | * |
||
| 338 | * @param string $username |
||
| 339 | * @param array $attributes List of specific AD attributes to return. Empty array means return everything. |
||
| 340 | * @return array |
||
| 341 | */ |
||
| 342 | View Code Duplication | public function getUserByUsername($username, $attributes = array()) |
|
| 352 | |||
| 353 | /** |
||
| 354 | * Get a username for an email. |
||
| 355 | * |
||
| 356 | * @param string $email |
||
| 357 | * @return string|null |
||
| 358 | */ |
||
| 359 | public function getUsernameByEmail($email) |
||
| 368 | |||
| 369 | /** |
||
| 370 | * Given a group DN, get the group membership data in LDAP. |
||
| 371 | * |
||
| 372 | * @param string $dn |
||
| 373 | * @return array |
||
| 374 | */ |
||
| 375 | public function getLDAPGroupMembers($dn) |
||
| 376 | { |
||
| 377 | $groupObj = Group::get()->filter('DN', $dn)->first(); |
||
| 378 | $groupData = $this->getGroupByGUID($groupObj->GUID); |
||
| 379 | $members = !empty($groupData['member']) ? $groupData['member'] : array(); |
||
| 380 | // If a user belongs to a single group, this comes through as a string. |
||
| 381 | // Normalise to a array so it's consistent. |
||
| 382 | if ($members && is_string($members)) { |
||
| 383 | $members = array($members); |
||
| 384 | } |
||
| 385 | |||
| 386 | return $members; |
||
| 387 | } |
||
| 388 | |||
| 389 | /** |
||
| 390 | * Update the current Member record with data from LDAP. |
||
| 391 | * |
||
| 392 | * Constraints: |
||
| 393 | * - Member *must* be in the database before calling this as it will need the ID to be mapped to a {@link Group}. |
||
| 394 | * - GUID of the member must have already been set, for integrity reasons we don't allow it to change here. |
||
| 395 | * |
||
| 396 | * @param Member |
||
| 397 | * @param array|null $data If passed, this is pre-existing AD attribute data to update the Member with. |
||
| 398 | * If not given, the data will be looked up by the user's GUID. |
||
| 399 | * @return bool |
||
| 400 | */ |
||
| 401 | public function updateMemberFromLDAP(Member $member, $data = null) |
||
| 402 | { |
||
| 403 | if (!$this->enabled()) { |
||
| 404 | return false; |
||
| 405 | } |
||
| 406 | |||
| 407 | if (!$member->GUID) { |
||
| 408 | SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN); |
||
| 409 | return false; |
||
| 410 | } |
||
| 411 | |||
| 412 | if (!$data) { |
||
| 413 | $data = $this->getUserByGUID($member->GUID); |
||
| 414 | if (!$data) { |
||
| 415 | SS_Log::log(sprintf('Could not retrieve data for user. GUID: %s', $member->GUID), SS_Log::WARN); |
||
| 416 | return false; |
||
| 417 | } |
||
| 418 | } |
||
| 419 | |||
| 420 | $member->IsExpired = ($data['useraccountcontrol'] & 2) == 2; |
||
| 421 | $member->LastSynced = (string)SS_Datetime::now(); |
||
| 422 | |||
| 423 | foreach ($member->config()->ldap_field_mappings as $attribute => $field) { |
||
| 424 | if (!isset($data[$attribute])) { |
||
| 425 | SS_Log::log(sprintf( |
||
| 426 | 'Attribute %s configured in Member.ldap_field_mappings, but no available attribute in AD data (GUID: %s, Member ID: %s)', |
||
| 427 | $attribute, |
||
| 428 | $data['objectguid'], |
||
| 429 | $member->ID |
||
| 430 | ), SS_Log::NOTICE); |
||
| 431 | |||
| 432 | continue; |
||
| 433 | } |
||
| 434 | |||
| 435 | if ($attribute == 'thumbnailphoto') { |
||
| 436 | $imageClass = $member->getRelationClass($field); |
||
| 437 | if ($imageClass !== 'Image' && !is_subclass_of($imageClass, 'Image')) { |
||
| 438 | SS_Log::log(sprintf( |
||
| 439 | 'Member field %s configured for thumbnailphoto AD attribute, but it isn\'t a valid relation to an Image class', |
||
| 440 | $field |
||
| 441 | ), SS_Log::WARN); |
||
| 442 | |||
| 443 | continue; |
||
| 444 | } |
||
| 445 | |||
| 446 | $filename = sprintf('thumbnailphoto-%s.jpg', $data['samaccountname']); |
||
| 447 | $path = ASSETS_DIR . '/' . $member->config()->ldap_thumbnail_path; |
||
| 448 | $absPath = BASE_PATH . '/' . $path; |
||
| 449 | if (!file_exists($absPath)) { |
||
| 450 | Filesystem::makeFolder($absPath); |
||
| 451 | } |
||
| 452 | |||
| 453 | // remove existing record if it exists |
||
| 454 | $existingObj = $member->getComponent($field); |
||
| 455 | if ($existingObj && $existingObj->exists()) { |
||
| 456 | $existingObj->delete(); |
||
| 457 | } |
||
| 458 | |||
| 459 | // The image data is provided in raw binary. |
||
| 460 | file_put_contents($absPath . '/' . $filename, $data[$attribute]); |
||
| 461 | $record = new $imageClass(); |
||
| 462 | $record->Name = $filename; |
||
| 463 | $record->Filename = $path . '/' . $filename; |
||
| 464 | $record->write(); |
||
| 465 | |||
| 466 | $relationField = $field . 'ID'; |
||
| 467 | $member->{$relationField} = $record->ID; |
||
| 468 | } else { |
||
| 469 | $member->$field = $data[$attribute]; |
||
| 470 | } |
||
| 471 | } |
||
| 472 | |||
| 473 | // if a default group was configured, ensure the user is in that group |
||
| 474 | if ($this->config()->default_group) { |
||
| 475 | $group = Group::get()->filter('Code', $this->config()->default_group)->limit(1)->first(); |
||
| 476 | if (!($group && $group->exists())) { |
||
| 477 | SS_Log::log( |
||
| 478 | sprintf( |
||
| 479 | 'LDAPService.default_group misconfiguration! There is no such group with Code = \'%s\'', |
||
| 480 | $this->config()->default_group |
||
| 481 | ), |
||
| 482 | SS_Log::WARN |
||
| 483 | ); |
||
| 484 | } else { |
||
| 485 | $group->Members()->add($member, array( |
||
| 486 | 'IsImportedFromLDAP' => '1' |
||
| 487 | )); |
||
| 488 | } |
||
| 489 | } |
||
| 490 | |||
| 491 | // this is to keep track of which groups the user gets mapped to |
||
| 492 | // and we'll use that later to remove them from any groups that they're no longer mapped to |
||
| 493 | $mappedGroupIDs = array(); |
||
| 494 | |||
| 495 | // ensure the user is in any mapped groups |
||
| 496 | if (isset($data['memberof'])) { |
||
| 497 | $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : array($data['memberof']); |
||
| 498 | foreach ($ldapGroups as $groupDN) { |
||
| 499 | foreach (LDAPGroupMapping::get() as $mapping) { |
||
| 500 | if (!$mapping->DN) { |
||
| 501 | SS_Log::log( |
||
| 502 | sprintf( |
||
| 503 | 'LDAPGroupMapping ID %s is missing DN field. Skipping', |
||
| 504 | $mapping->ID |
||
| 505 | ), |
||
| 506 | SS_Log::WARN |
||
| 507 | ); |
||
| 508 | continue; |
||
| 509 | } |
||
| 510 | |||
| 511 | // the user is a direct member of group with a mapping, add them to the SS group. |
||
| 512 | View Code Duplication | if ($mapping->DN == $groupDN) { |
|
| 513 | $group = $mapping->Group(); |
||
| 514 | if ($group && $group->exists()) { |
||
| 515 | $group->Members()->add($member, array( |
||
| 516 | 'IsImportedFromLDAP' => '1' |
||
| 517 | )); |
||
| 518 | $mappedGroupIDs[] = $mapping->GroupID; |
||
| 519 | } |
||
| 520 | } |
||
| 521 | |||
| 522 | // the user *might* be a member of a nested group provided the scope of the mapping |
||
| 523 | // is to include the entire subtree. Check all those mappings and find the LDAP child groups |
||
| 524 | // to see if they are a member of one of those. If they are, add them to the SS group |
||
| 525 | if ($mapping->Scope == 'Subtree') { |
||
| 526 | $childGroups = $this->getNestedGroups($mapping->DN, array('dn')); |
||
| 527 | if (!$childGroups) { |
||
| 528 | continue; |
||
| 529 | } |
||
| 530 | |||
| 531 | foreach ($childGroups as $childGroupDN => $childGroupRecord) { |
||
| 532 | View Code Duplication | if ($childGroupDN == $groupDN) { |
|
| 533 | $group = $mapping->Group(); |
||
| 534 | if ($group && $group->exists()) { |
||
| 535 | $group->Members()->add($member, array( |
||
| 536 | 'IsImportedFromLDAP' => '1' |
||
| 537 | )); |
||
| 538 | $mappedGroupIDs[] = $mapping->GroupID; |
||
| 539 | } |
||
| 540 | } |
||
| 541 | } |
||
| 542 | } |
||
| 543 | } |
||
| 544 | } |
||
| 545 | } |
||
| 546 | |||
| 547 | // remove the user from any previously mapped groups, where the mapping has since been removed |
||
| 548 | $groupRecords = DB::query(sprintf('SELECT "GroupID" FROM "Group_Members" WHERE "IsImportedFromLDAP" = 1 AND "MemberID" = %s', $member->ID)); |
||
| 549 | foreach ($groupRecords as $groupRecord) { |
||
| 550 | if (!in_array($groupRecord['GroupID'], $mappedGroupIDs)) { |
||
| 551 | $group = Group::get()->byId($groupRecord['GroupID']); |
||
| 552 | // Some groups may no longer exist. SilverStripe does not clean up join tables. |
||
| 553 | if ($group) { |
||
| 554 | $group->Members()->remove($member); |
||
| 555 | } |
||
| 556 | } |
||
| 557 | } |
||
| 558 | // This will throw an exception if there are two distinct GUIDs with the same email address. |
||
| 559 | // We are happy with a raw 500 here at this stage. |
||
| 560 | $member->write(); |
||
| 561 | } |
||
| 562 | |||
| 563 | /** |
||
| 564 | * Sync a specific Group by updating it with LDAP data. |
||
| 565 | * |
||
| 566 | * @param Group $group An existing Group or a new Group object |
||
| 567 | * @param array $data LDAP group object data |
||
| 568 | * |
||
| 569 | * @return bool |
||
| 570 | */ |
||
| 571 | public function updateGroupFromLDAP(Group $group, $data) |
||
| 572 | { |
||
| 573 | if (!$this->enabled()) { |
||
| 574 | return false; |
||
| 575 | } |
||
| 576 | |||
| 577 | // Synchronise specific guaranteed fields. |
||
| 578 | $group->Code = $data['samaccountname']; |
||
| 579 | if (!empty($data['name'])) { |
||
| 580 | $group->Title = $data['name']; |
||
| 581 | } else { |
||
| 582 | $group->Title = $data['samaccountname']; |
||
| 583 | } |
||
| 584 | if (!empty($data['description'])) { |
||
| 585 | $group->Description = $data['description']; |
||
| 586 | } |
||
| 587 | $group->DN = $data['dn']; |
||
| 588 | $group->LastSynced = (string)SS_Datetime::now(); |
||
| 589 | $group->write(); |
||
| 590 | |||
| 591 | // Mappings on this group are automatically maintained to contain just the group's DN. |
||
| 592 | // First, scan through existing mappings and remove ones that are not matching (in case the group moved). |
||
| 593 | $hasCorrectMapping = false; |
||
| 594 | foreach ($group->LDAPGroupMappings() as $mapping) { |
||
| 595 | if ($mapping->DN === $data['dn']) { |
||
| 596 | // This is the correct mapping we want to retain. |
||
| 597 | $hasCorrectMapping = true; |
||
| 598 | } else { |
||
| 599 | $mapping->delete(); |
||
| 600 | } |
||
| 601 | } |
||
| 602 | |||
| 603 | // Second, if the main mapping was not found, add it in. |
||
| 604 | if (!$hasCorrectMapping) { |
||
| 605 | $mapping = new LDAPGroupMapping(); |
||
| 606 | $mapping->DN = $data['dn']; |
||
| 607 | $mapping->write(); |
||
| 608 | $group->LDAPGroupMappings()->add($mapping); |
||
| 609 | } |
||
| 610 | } |
||
| 611 | |||
| 612 | /** |
||
| 613 | * Creates a new LDAP user from the passed Member record. |
||
| 614 | * Note that the Member record must have a non-empty Username field for this to work. |
||
| 615 | * |
||
| 616 | * @param Member $member |
||
| 617 | */ |
||
| 618 | public function createLDAPUser(Member $member) |
||
| 619 | { |
||
| 620 | if (!$this->enabled()) { |
||
| 621 | return; |
||
| 622 | } |
||
| 623 | if (empty($member->Username)) { |
||
| 624 | throw new ValidationException('Member missing Username. Cannot create LDAP user'); |
||
| 625 | } |
||
| 626 | |||
| 627 | // Normalise username to lowercase to ensure we don't have duplicates of different cases |
||
| 628 | $member->Username = strtolower($member->Username); |
||
| 629 | |||
| 630 | // Create user in LDAP using available information. |
||
| 631 | $dn = sprintf('CN=%s,%s', $member->Username, LDAP_NEW_USERS_DN); |
||
| 632 | |||
| 633 | try { |
||
| 634 | $this->add($dn, array( |
||
| 635 | 'objectclass' => 'user', |
||
| 636 | 'cn' => $member->Username, |
||
| 637 | 'accountexpires' => '9223372036854775807', |
||
| 638 | 'useraccountcontrol' => '66048', |
||
| 639 | 'userprincipalname' => sprintf( |
||
| 640 | '%s@%s', |
||
| 641 | $member->Username, |
||
| 642 | $this->gateway->config()->options['accountDomainName'] |
||
| 643 | ), |
||
| 644 | )); |
||
| 645 | } catch (\Exception $e) { |
||
| 646 | throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage()); |
||
| 647 | } |
||
| 648 | |||
| 649 | $user = $this->getUserByUsername($member->Username); |
||
| 650 | if (empty($user['objectguid'])) { |
||
| 651 | throw new ValidationException('LDAP synchronisation failure: user missing GUID'); |
||
| 652 | } |
||
| 653 | |||
| 654 | // Creation was successful, mark the user as LDAP managed by setting the GUID. |
||
| 655 | $member->GUID = $user['objectguid']; |
||
| 656 | } |
||
| 657 | |||
| 658 | /** |
||
| 659 | * Update the Member data back to the corresponding LDAP user object. |
||
| 660 | * |
||
| 661 | * @param Member $member |
||
| 662 | * @throws ValidationException |
||
| 663 | */ |
||
| 664 | public function updateLDAPFromMember(Member $member) |
||
| 665 | { |
||
| 666 | if (!$this->enabled()) { |
||
| 667 | return; |
||
| 668 | } |
||
| 669 | if (!$member->GUID) { |
||
| 670 | throw new ValidationException('Member missing GUID. Cannot update LDAP user'); |
||
| 671 | } |
||
| 672 | |||
| 673 | $data = $this->getUserByGUID($member->GUID); |
||
| 674 | if (empty($data['objectguid'])) { |
||
| 675 | throw new ValidationException('LDAP synchronisation failure: user missing GUID'); |
||
| 676 | } |
||
| 677 | |||
| 678 | $dn = $data['distinguishedname']; |
||
| 679 | |||
| 680 | // Normalise username to lowercase to ensure we don't have duplicates of different cases |
||
| 681 | $member->Username = strtolower($member->Username); |
||
| 682 | |||
| 683 | try { |
||
| 684 | // If the common name (cn) has changed, we need to ensure they've been moved |
||
| 685 | // to the new DN, to avoid any clashes between user objects. |
||
| 686 | if ($data['cn'] != $member->Username) { |
||
| 687 | $newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn)); |
||
| 688 | $this->move($dn, $newDn); |
||
| 689 | $dn = $newDn; |
||
| 690 | } |
||
| 691 | } catch (\Exception $e) { |
||
| 692 | throw new ValidationException('LDAP move failure: '.$e->getMessage()); |
||
| 693 | } |
||
| 694 | |||
| 695 | try { |
||
| 696 | $attributes = array( |
||
| 697 | 'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname), |
||
| 698 | 'name' => sprintf('%s %s', $member->FirstName, $member->Surname), |
||
| 699 | 'userprincipalname' => sprintf( |
||
| 700 | '%s@%s', |
||
| 701 | $member->Username, |
||
| 702 | $this->gateway->config()->options['accountDomainName'] |
||
| 703 | ), |
||
| 704 | ); |
||
| 705 | foreach ($member->config()->ldap_field_mappings as $attribute => $field) { |
||
| 706 | $relationClass = $member->getRelationClass($field); |
||
| 707 | if ($relationClass) { |
||
| 708 | // todo no support for writing back relations yet. |
||
| 709 | } else { |
||
| 710 | $attributes[$attribute] = $member->$field; |
||
| 711 | } |
||
| 712 | } |
||
| 713 | |||
| 714 | $this->update($dn, $attributes); |
||
| 715 | } catch (\Exception $e) { |
||
| 716 | throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage()); |
||
| 717 | } |
||
| 718 | } |
||
| 719 | |||
| 720 | /** |
||
| 721 | * Ensure the user belongs to the correct groups in LDAP from their membership |
||
| 722 | * to local LDAP mapped SilverStripe groups. |
||
| 723 | * |
||
| 724 | * This also removes them from LDAP groups if they've been taken out of one. |
||
| 725 | * It will not affect group membership of non-mapped groups, so it will |
||
| 726 | * not touch such internal AD groups like "Domain Users". |
||
| 727 | * |
||
| 728 | * @param Member $member |
||
| 729 | */ |
||
| 730 | public function updateLDAPGroupsForMember(Member $member) |
||
| 731 | { |
||
| 732 | if (!$this->enabled()) { |
||
| 733 | return; |
||
| 734 | } |
||
| 735 | if (!$member->GUID) { |
||
| 736 | throw new ValidationException('Member missing GUID. Cannot update LDAP user'); |
||
| 737 | } |
||
| 738 | |||
| 739 | $addGroups = array(); |
||
| 740 | $removeGroups = array(); |
||
| 741 | |||
| 742 | $user = $this->getUserByGUID($member->GUID); |
||
| 743 | if (empty($user['objectguid'])) { |
||
| 744 | throw new ValidationException('LDAP update failure: user missing GUID'); |
||
| 745 | } |
||
| 746 | |||
| 747 | // If a user belongs to a single group, this comes through as a string. |
||
| 748 | // Normalise to a array so it's consistent. |
||
| 749 | $existingGroups = !empty($user['memberof']) ? $user['memberof'] : array(); |
||
| 750 | if ($existingGroups && is_string($existingGroups)) { |
||
| 751 | $existingGroups = array($existingGroups); |
||
| 752 | } |
||
| 753 | |||
| 754 | foreach ($member->Groups() as $group) { |
||
| 755 | if (!$group->GUID) { |
||
| 756 | continue; |
||
| 757 | } |
||
| 758 | |||
| 759 | // mark this group as something we need to ensure the user belongs to in LDAP. |
||
| 760 | $addGroups[] = $group->DN; |
||
| 761 | } |
||
| 762 | |||
| 763 | // Which existing LDAP groups are not in the add groups? We'll check these groups to |
||
| 764 | // see if the user should be removed from any of them. |
||
| 765 | $remainingGroups = array_diff($existingGroups, $addGroups); |
||
| 766 | |||
| 767 | foreach ($remainingGroups as $groupDn) { |
||
| 768 | // We only want to be removing groups we have a local Group mapped to. Removing |
||
| 769 | // membership for anything else would be bad! |
||
| 770 | $group = Group::get()->filter('DN', $groupDn)->first(); |
||
| 771 | if (!$group || !$group->exists()) { |
||
| 772 | continue; |
||
| 773 | } |
||
| 774 | |||
| 775 | // this group should be removed from the user's memberof attribute, as it's been removed. |
||
| 776 | $removeGroups[] = $groupDn; |
||
| 777 | } |
||
| 778 | |||
| 779 | // go through the groups we want the user to be in and ensure they're in them. |
||
| 780 | foreach ($addGroups as $groupDn) { |
||
| 781 | $members = $this->getLDAPGroupMembers($groupDn); |
||
| 782 | |||
| 783 | // this user is already in the group, no need to do anything. |
||
| 784 | if (in_array($user['distinguishedname'], $members)) { |
||
| 785 | continue; |
||
| 786 | } |
||
| 787 | |||
| 788 | $members[] = $user['distinguishedname']; |
||
| 789 | |||
| 790 | try { |
||
| 791 | $this->update($groupDn, array('member' => $members)); |
||
| 792 | } catch (\Exception $e) { |
||
| 793 | throw new ValidationException('LDAP group membership add failure: '.$e->getMessage()); |
||
| 794 | } |
||
| 795 | } |
||
| 796 | |||
| 797 | // go through the groups we _don't_ want the user to be in and ensure they're taken out of them. |
||
| 798 | foreach ($removeGroups as $groupDn) { |
||
| 799 | $members = $this->getLDAPGroupMembers($groupDn); |
||
| 800 | |||
| 801 | // remove the user from the members data. |
||
| 802 | if (in_array($user['distinguishedname'], $members)) { |
||
| 803 | foreach ($members as $i => $dn) { |
||
| 804 | if ($dn == $user['distinguishedname']) { |
||
| 805 | unset($members[$i]); |
||
| 806 | } |
||
| 807 | } |
||
| 808 | } |
||
| 809 | |||
| 810 | try { |
||
| 811 | $this->update($groupDn, array('member' => $members)); |
||
| 812 | } catch (\Exception $e) { |
||
| 813 | throw new ValidationException('LDAP group membership remove failure: '.$e->getMessage()); |
||
| 814 | } |
||
| 815 | } |
||
| 816 | } |
||
| 817 | |||
| 818 | /** |
||
| 819 | * Change a members password on the AD. Works with ActiveDirectory compatible services that saves the |
||
| 820 | * password in the `unicodePwd` attribute. |
||
| 821 | * |
||
| 822 | * @todo Use the Zend\Ldap\Attribute::setPassword functionality to create a password in |
||
| 823 | * an abstract way, so it works on other LDAP directories, not just Active Directory. |
||
| 824 | * |
||
| 825 | * Ensure that the LDAP bind:ed user can change passwords and that the connection is secure. |
||
| 826 | * |
||
| 827 | * @param Member $member |
||
| 828 | * @param string $password |
||
| 829 | * @return ValidationResult |
||
| 830 | * @throws Exception |
||
| 831 | */ |
||
| 832 | public function setPassword(Member $member, $password) |
||
| 833 | { |
||
| 834 | $validationResult = ValidationResult::create(true); |
||
| 835 | if (!$member->GUID) { |
||
| 836 | SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN); |
||
| 837 | $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.')); |
||
| 838 | return $validationResult; |
||
| 839 | } |
||
| 840 | |||
| 841 | $userData = $this->getUserByGUID($member->GUID); |
||
| 842 | if (empty($userData['distinguishedname'])) { |
||
| 843 | $validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.')); |
||
| 844 | return $validationResult; |
||
| 845 | } |
||
| 846 | |||
| 847 | try { |
||
| 848 | $this->update( |
||
| 849 | $userData['distinguishedname'], |
||
| 850 | array('unicodePwd' => iconv('UTF-8', 'UTF-16LE', sprintf('"%s"', $password))) |
||
| 851 | ); |
||
| 852 | } catch (Exception $e) { |
||
| 853 | // Try to parse the exception to get the error message to display to user, eg: |
||
| 854 | // Can't change password for Member.ID "13": 0x13 (Constraint violation; 0000052D: Constraint violation - check_password_restrictions: the password does not meet the complexity criteria!): updating: CN=User Name,OU=Users,DC=foo,DC=company,DC=com |
||
| 855 | $pattern = '/^([^\s])*\s([^\;]*);\s([^\:]*):\s([^\:]*):\s([^\)]*)/i'; |
||
| 856 | if (preg_match($pattern, $e->getMessage(), $matches) && !empty($matches[5])) { |
||
| 857 | $validationResult->error($matches[5]); |
||
| 858 | } else { |
||
| 859 | // Unparsable exception, an administrator should check the logs |
||
| 860 | $validationResult->error(_t('LDAPAuthenticator.CANTCHANGEPASSWORD', 'We couldn\'t change your password, please contact an administrator.')); |
||
| 861 | } |
||
| 862 | } |
||
| 863 | |||
| 864 | return $validationResult; |
||
| 865 | } |
||
| 866 | |||
| 867 | /** |
||
| 868 | * Delete an LDAP user mapped to the Member record |
||
| 869 | * @param Member $member |
||
| 870 | */ |
||
| 871 | public function deleteLDAPMember(Member $member) { |
||
| 872 | if (!$this->enabled()) { |
||
| 873 | return; |
||
| 874 | } |
||
| 875 | if (!$member->GUID) { |
||
| 876 | throw new ValidationException('Member missing GUID. Cannot delete LDAP user'); |
||
| 877 | } |
||
| 878 | $data = $this->getUserByGUID($member->GUID); |
||
| 879 | if (empty($data['distinguishedname'])) { |
||
| 880 | throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute'); |
||
| 881 | } |
||
| 882 | |||
| 883 | try { |
||
| 884 | $this->delete($data['distinguishedname']); |
||
| 885 | } catch (\Exception $e) { |
||
| 886 | throw new ValidationException('LDAP delete user failed: '.$e->getMessage()); |
||
| 887 | } |
||
| 888 | } |
||
| 889 | |||
| 890 | /** |
||
| 891 | * A simple proxy to LDAP update operation. |
||
| 892 | * |
||
| 893 | * @param string $dn Location to add the entry at. |
||
| 894 | * @param array $attributes A simple associative array of attributes. |
||
| 895 | */ |
||
| 896 | public function update($dn, array $attributes) |
||
| 900 | |||
| 901 | /** |
||
| 902 | * A simple proxy to LDAP delete operation. |
||
| 903 | * |
||
| 904 | * @param string $dn Location of object to delete |
||
| 905 | * @param bool $recursively Recursively delete nested objects? |
||
| 906 | */ |
||
| 907 | public function delete($dn, $recursively = false) |
||
| 911 | |||
| 912 | /** |
||
| 913 | * A simple proxy to LDAP copy/delete operation. |
||
| 914 | * |
||
| 915 | * @param string $fromDn |
||
| 916 | * @param string $toDn |
||
| 917 | * @param bool $recursively Recursively move nested objects? |
||
| 918 | */ |
||
| 919 | public function move($fromDn, $toDn, $recursively = false) |
||
| 923 | |||
| 924 | /** |
||
| 925 | * A simple proxy to LDAP add operation. |
||
| 926 | * |
||
| 927 | * @param string $dn Location to add the entry at. |
||
| 928 | * @param array $attributes A simple associative array of attributes. |
||
| 929 | */ |
||
| 930 | public function add($dn, array $attributes) |
||
| 934 | } |
||
| 935 |
You can fix this by adding a namespace to your class:
When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.