/**
  * @param string    $username
  * @param string    $password
  * @param null|User $user
  *
  * @return boolean
  */
 public function authenticate($username, $password, &$user)
 {
     if ($this->ad === null) {
         $this->ad = new Adldap($this->adConfig);
     }
     $authSuccess = false;
     if ($this->ad->authenticate($username, $password, true)) {
         $adUser = $this->ad->users()->find($username);
         $sid = \Adldap\Classes\Utilities::binarySidToText($adUser->getObjectSID());
         if ($user === null and $this->hasAutoAddUser($adUser)) {
             $user = $this->createUserFromAd($adUser);
         }
         if ($user !== null) {
             if ($this->autoUpdateRole) {
                 $this->updateRole($user, $adUser);
             }
             $user->addAuthDriver($this->getName(), $sid);
             $authSuccess = true;
         }
     }
     return $authSuccess;
 }
 /**
  * Grants membership to local groups for each LDAP/AD group that the user
  * is a member of. See the option "LDAP_RECURSIVE_GROUPS" to enable
  * deep LDAP/AD group probe.
  * NOTE: This will not maintain the hierarchical structure of the groups,
  * instead the structure will be 'flattened'. If you want to maintain
  * the hierarchical structure, set the option "LDAP_RECURSIVE_GROUPS"
  * to false, and build a group structure that mirrors the LDAP/AD
  * structure.
  *
  * @param  $user      The user to replicate group membership for.
  * @throws Exception
  */
 private function replicateMembershipFromLDAP($user)
 {
     $adldap = false;
     try {
         $groupModel = $this->createGroupModel();
         $ldapConOp = $this->GetLDAPConnectionOptions();
         //            // Set LDAP debug log level - useful in DEV, dangerous in PROD!!
         //            ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
         // Connect to AD/LDAP
         $adldap = new Adldap($ldapConOp);
         // Request the user's group membership.
         $adldapGroups = $adldap->users()->find($user->username)->getGroups();
         foreach ($adldapGroups as $adldapGroup) {
             try {
                 $adldapGroupName = $adldapGroup->getName();
                 $localGroup = null;
                 $localGroup = $groupModel->where('name', $adldapGroupName)->firstOrFail();
                 if (!$user->isMemberOf($adldapGroupName)) {
                     $user->membershipList()->attach($localGroup->id);
                 }
             } catch (ModelNotFoundException $e) {
                 // Mute the exception as we expect not to find all groups.
             }
         }
     } catch (\Exception $ex) {
         Log::error('Exception replicating group membership for user: '******', Exception message: ' . $ex->getMessage());
         Log::error($ex->getTraceAsString());
         $this->handleLDAPError($adldap);
     }
     // Close connection.
     if (isset($adldap)) {
         unset($adldap);
     }
 }