# Usage examples

> Use LdapRecord's native models. The same username can exist on two named connections without changing the default.

## Query users and groups

Use LdapRecord's native models. The same username can exist on two named connections without changing the default.

```php
use LdapRecord\Models\ActiveDirectory\User as ActiveDirectoryUser;
use LdapRecord\Models\OpenLDAP\User as OpenLdapUser;

$employee = ActiveDirectoryUser::on('corporate')->whereEquals('samaccountname', 'alex')->firstOrFail();
$partner = OpenLdapUser::on('partners')->whereEquals('uid', 'alex')->firstOrFail();

$employeeGroups = $employee->groups()->get();
$partnerGroups = $partner->groups()->get();
```

The stock OpenLDAP models expect `inetOrgPerson` users and `groupOfUniqueNames` groups. For another LDAP schema, use the
appropriate models and relationship definitions from [LdapRecord Core](https://ldaprecord.com/docs/core/v4/models).
Directory lookups and sync do not depend on how the application establishes a session.

## Synchronize selected attributes

Run sync from a Yii console command. Create a unique key on `(ldap_source, ldap_guid)` in your local table. Use the
application's existing validation and persistence policy; the example intentionally maps only two fields.

```php
use LdapRecord\Models\OpenLDAP\User as OpenLdapUser;
use yii2\extensions\ldap\Directory;
use yii2\extensions\ldap\UserSynchronizer;

/** @var Directory $directory */
$directory = Yii::$app->get('directory');
$db = Yii::$app->get('db');

$count = (new UserSynchronizer($directory))->sync(
    OpenLdapUser::on('people'),
    ['display_name' => 'cn', 'email' => 'mail'],
    static function (string $source, string $guid, array $attributes) use ($db): void {
        $profile = [
            'display_name' => $attributes['display_name'][0] ?? null,
            'email' => $attributes['email'][0] ?? null,
        ];

        $db->createCommand()->upsert(
            '{{%directory_user}}',
            ['ldap_source' => $source, 'ldap_guid' => $guid] + $profile,
            $profile,
        )->execute();
    },
    pageSize: 250,
);
```

The synchronizer reads all matches of the supplied query in pages using a separate connection to the same directory. Use
query filters to change the population; a query limit is not a sync cap. The stable identifier is the AD `objectGUID` or
OpenLDAP `entryUUID`, not the username or DN. A missing or unreadable attribute arrives as `null`; decide whether to
clear or preserve its local value. A missing GUID fails the sync. Earlier upserts are not rolled back on later failure.
Use idempotent writes and do not use this operation to infer deletions, provision sign-in access or grant application
roles.

## Add or remove a direct group membership

Look up both entries on the same configured write connection after applying the application's authorization rules.

```php
use LdapRecord\Models\OpenLDAP\Group;
use LdapRecord\Models\OpenLDAP\User as OpenLdapUser;
use yii2\extensions\ldap\Directory;

/** @var Directory $directory */
$directory = Yii::$app->get('directory');

$group = Group::on('memberships')->whereEquals('cn', 'operators')->firstOrFail();
$user = OpenLdapUser::on('memberships')->whereEquals('uid', 'alex')->firstOrFail();

$added = $directory->setMembership($group, $user, true);
// Supply false to remove that one direct membership.
```

The method adds or deletes a single value using the directory's LDAP operation. It does not replace the entire member
list, change an AD primary group or delete an entry. The directory can reject a duplicate, a missing membership or the
removal of the last required member. Do not use models from a different connection, even if the names or DNs match.

## Log in an existing Yii user

Persist a unique principal on each eligible local identity: for example, an OpenLDAP distinguished name or an Active
Directory user principal name (UPN). The directory administrator must confirm what the configured endpoint accepts.
Prevent users from editing that mapping themselves. Keep names in sync when accounts are renamed, and do not reuse a
stale mapping for a new directory account.

After validating the form and applying login throttling, resolve the same identity for both credential verification and
the Yii session:

```php
use yii2\extensions\ldap\DirectoryUnavailableException;
use yii2\extensions\ldap\PasswordVerifier;

/** @var PasswordVerifier $directory */
$directory = Yii::$app->get('ldapLogin');
$identity = User::findActiveByUsername($this->username);

if ($identity === null) {
    return false;
}

try {
    if (!$directory->verify($identity->ldapPrincipal, $this->password)) {
        return false;
    }
} catch (DirectoryUnavailableException) {
    // Record a generic availability metric if desired. Never log the form or the password.
    return false;
}

return Yii::$app->user->login($identity);
```

The local lookup and `ldapPrincipal` field above are application code. Do not take a separate bind principal from the
request. Missing credentials and an invalid-credentials reply return `false`. A failed TLS upgrade, directory connection
error, or unexpected directory reply raises `DirectoryUnavailableException`. Present the same login error to the client
in all cases. Account eligibility, session duration, authorization and revocation remain with the application.

[Back to documentation](/docs/extensions/ldap/index.md#documentation)