Exemplo n.º 1
17
 /**
  * Refresh ldap users
  *
  * New users (found in ldap) will be automatically created if all required fiélds are set.
  * Profile fields which are bind to LDAP will automatically updated.
  */
 public function syncUsers()
 {
     if (!Yii::$app->getModule('user')->settings->get('auth.ldap.enabled') || !Yii::$app->getModule('user')->settings->get('auth.ldap.refreshUsers')) {
         return;
     }
     $userFilter = Yii::$app->getModule('user')->settings->get('auth.ldap.userFilter');
     $baseDn = Yii::$app->getModule('user')->settings->get('auth.ldap.baseDn');
     $userCollection = $this->getLdap()->search($userFilter, $baseDn, Ldap::SEARCH_SCOPE_SUB);
     $authClient = null;
     $ids = [];
     foreach ($userCollection as $attributes) {
         $authClient = new static();
         $authClient->setUserAttributes($attributes);
         $attributes = $authClient->getUserAttributes();
         $user = AuthClientHelpers::getUserByAuthClient($authClient);
         if ($user === null) {
             if (!AuthClientHelpers::createUser($authClient)) {
                 Yii::warning('Could not automatically create LDAP user ' . $attributes['email'] . ' - check required attributes!');
             }
         } else {
             AuthClientHelpers::updateUser($authClient, $user);
         }
         $ids[] = $attributes['id'];
     }
     /**
      * Since userTableAttribute can be automatically set on user attributes
      * try to take it from initialized authclient instance.
      */
     $userTableIdAttribute = $this->getUserTableIdAttribute();
     if ($authClient !== null) {
         $userTableIdAttribute = $authClient->getUserTableIdAttribute();
     }
     // Disable not longer existing users
     foreach (AuthClientHelpers::getUsersByAuthClient($this)->each() as $user) {
         if ($user->status !== User::STATUS_DISABLED && !in_array($user->getAttribute($userTableIdAttribute), $ids)) {
             $user->status = User::STATUS_DISABLED;
             $user->save();
             Yii::warning('Disabled user ' . $user->username . ' (' . $user->id . ') - Not found in LDAP!');
         }
     }
 }