Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ldaprecord Laravel Laravel Package

directorytree/ldaprecord-laravel

Integrate LDAP authentication and directory management into Laravel with LdapRecord. Configure connections, sync users and groups, run queries, and handle logins against Active Directory/OpenLDAP with clean, Laravel-friendly APIs and tooling.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require directorytree/ldaprecord-laravel

Publish the config and migrations:

php artisan vendor:publish --provider="DirectoryTree\LdapRecordLaravel\LdapRecordLaravelServiceProvider" --tag="config"
php artisan vendor:publish --provider="DirectoryTree\LdapRecordLaravel\LdapRecordLaravelServiceProvider" --tag="migrations"
php artisan migrate
  1. Configure LDAP Connection: Edit config/ldap.php with your LDAP server details (e.g., host, base DN, bind DN, password). Example:

    'connections' => [
        'ad' => [
            'host' => 'ldap.example.com',
            'port' => 389,
            'use_ssl' => true,
            'base_dn' => 'dc=example,dc=com',
            'username' => 'cn=admin,dc=example,dc=com',
            'password' => 'password',
            'account_prefix' => 'uid=',
            'account_suffix' => '',
            'user_model' => \App\Models\User::class,
        ],
    ],
    
  2. First Use Case: LDAP Authentication Add an LDAP guard to config/auth.php:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'ldap',
        ],
    ],
    'providers' => [
        'ldap' => [
            'driver' => 'ldap',
            'connection' => 'ad',
            'model' => \App\Models\User::class,
        ],
    ],
    

    Test login with:

    Auth::guard('web')->attempt(['username' => 'jdoe', 'password' => 'password']);
    
  3. Query LDAP Users: Use Eloquent-like syntax to query LDAP:

    use DirectoryTree\LdapRecordLaravel\Models\LdapUser;
    
    $users = LdapUser::where('mail', 'like', '%@example.com')
        ->where('department', 'Marketing')
        ->get();
    

Implementation Patterns

Core Workflows

1. LDAP Authentication Flow

  • Login: Use Auth::guard('ldap')->attempt() with username/password.
  • Custom Rules: Extend DirectoryTree\LdapRecordLaravel\Auth\LdapAuthenticator to add pre-auth rules (e.g., account expiry checks).
  • Password Handling: Leverage password_column in config to map LDAP attributes to Laravel’s password field or disable password storage in DB.

Example custom authenticator:

use DirectoryTree\LdapRecordLaravel\Auth\LdapAuthenticator;

class CustomLdapAuthenticator extends LdapAuthenticator
{
    protected function validateCredentials($username, $password, $guard)
    {
        // Add custom logic (e.g., check for suspended accounts)
        if ($this->isAccountSuspended($username)) {
            return false;
        }
        return parent::validateCredentials($username, $password, $guard);
    }
}

2. User Synchronization

  • Bulk Import: Use LdapImporter or ldap:import Artisan command:
    php artisan ldap:import --connection=ad --resolve=merge
    
  • Conflict Resolution: Configure --resolve flag (merge, skip, delete).
  • Scheduled Syncs: Use Laravel’s task scheduling:
    $schedule->command('ldap:import --connection=ad --resolve=merge')->daily();
    

Example importer with scopes:

use DirectoryTree\LdapRecordLaravel\LdapImporter;

$importer = new LdapImporter('ad');
$importer->addScope(function ($query) {
    return $query->where('department', 'Engineering');
});
$importer->import();

3. Querying LDAP

  • Eloquent-Like Syntax: Query LDAP as if it were a database:
    $activeUsers = LdapUser::where('userAccountControl', '<>', 2)
        ->where('mail', 'like', '%@company.com')
        ->orderBy('sn', 'asc')
        ->get();
    
  • Virtual Attributes: Use accessors for computed fields:
    public function getFullNameAttribute()
    {
        return "{$this->givenName} {$this->sn}";
    }
    
  • Directory Emulator: Test queries locally without LDAP:
    $this->actingAs(new LdapUser(), 'ldap');
    

4. Attribute Mapping

  • Custom Mappings: Override default attribute mappings in your model:
    protected $ldapAttributes = [
        'username' => 'sAMAccountName',
        'email' => 'mail',
        'first_name' => 'givenName',
        'last_name' => 'sn',
        'department' => 'department',
    ];
    
  • Dynamic Attributes: Use closures for complex mappings:
    protected $ldapAttributes = [
        'display_name' => function ($record) {
            return "{$record->givenName} {$record->sn}";
        },
    ];
    

5. Events and Observers

  • Listen for LDAP Events: Extend functionality via events:
    use DirectoryTree\LdapRecordLaravel\Events\LdapUserAuthenticated;
    
    LdapUserAuthenticated::listen(function ($event) {
        // Log authentication or trigger additional actions
        Log::info("LDAP user authenticated: {$event->user->username}");
    });
    
  • Custom Observers: Attach observers to LDAP models:
    class LdapUserObserver
    {
        public function saving(LdapUser $user)
        {
            // Pre-save logic (e.g., normalize attributes)
            $user->username = strtolower($user->username);
        }
    }
    

Integration Tips

1. Hybrid Auth (LDAP + Database)

  • Use Auth::guard('ldap')->user() to fetch LDAP user, then sync to database:
    $ldapUser = Auth::guard('ldap')->user();
    $dbUser = User::updateOrCreate(
        ['email' => $ldapUser->mail],
        [
            'name' => $ldapUser->displayName,
            'department' => $ldapUser->department,
        ]
    );
    

2. Group-Based Access Control

  • Query LDAP groups and map to Laravel roles:
    use DirectoryTree\LdapRecordLaravel\Models\LdapGroup;
    
    $adminGroup = LdapGroup::where('cn', 'Admins')
        ->where('member', '=*', $ldapUser->distinguishedName)
        ->first();
    
    if ($adminGroup) {
        $user->assignRole('admin');
    }
    

3. Password Policy Enforcement

  • Extend DirectoryTree\LdapRecordLaravel\Auth\LdapAuthenticator to enforce custom rules:
    protected function validatePassword($password, $record)
    {
        if (strlen($password) < 8) {
            throw new \DirectoryTree\LdapRecord\Exception\AuthenticationException(
                'Password must be at least 8 characters.'
            );
        }
        return parent::validatePassword($password, $record);
    }
    

4. Multi-Tenant LDAP Connections

  • Dynamically switch connections based on tenant:
    $connection = config("ldap.connections.{$tenant->ldap_connection}");
    LdapRecord::setConnection($connection);
    

5. Testing with Directory Emulator

  • Mock LDAP responses in tests:
    use DirectoryTree\LdapRecordLaravel\Testing\DirectoryEmulator;
    
    public function testLdapLogin()
    {
        DirectoryEmulator::fake([
            'users' => [
                'jdoe' => [
                    'dn' => 'uid=jdoe,ou=users,dc=example,dc=com',
                    'givenName' => 'John',
                    'sn' => 'Doe',
                    'mail' => 'jdoe@example.com',
                ],
            ],
        ]);
    
        $this->assertAuthenticated();
    }
    

Gotchas and Tips

Pitfalls and Debugging

1. Connection Issues

  • Symptom: Authentication fails silently or throws generic errors.
  • Debugging:
    • Enable LDAP logging in config/ldap.php:
      'logging' => [
          'enabled'
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony