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

Ldap Laravel Package

chill-project/ldap

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chill-project/ldap
    

    Add the service provider to config/app.php under providers:

    Chill\Ldap\LdapServiceProvider::class,
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Chill\Ldap\LdapServiceProvider" --tag="ldap-config"
    

    Update config/ldap.php with your LDAP server details (host, base DN, bind credentials, etc.).

  3. First Use Case: Sync a User Trigger a one-time sync for a specific user:

    use Chill\Ldap\Facades\Ldap;
    
    $user = User::find(1); // Replace with your user model
    $ldapUser = Ldap::syncUser($user);
    
  4. Verify Connection Test LDAP connectivity via Tinker:

    php artisan tinker
    
    \Chill\Ldap\Facades\Ldap::connect();
    // Should return true if connection succeeds
    

Implementation Patterns

Core Workflows

1. User Synchronization

  • Periodic Sync (Cron Job) Schedule a daily sync for all users via artisan command:

    php artisan ldap:sync:users --dry-run  # Test without changes
    php artisan ldap:sync:users            # Run full sync
    

    Customize the command in app/Console/Commands/SyncUsersCommand.php to filter users (e.g., only active ones).

  • Event-Based Sync Listen for user creation/update events and trigger LDAP sync:

    use Chill\Ldap\Events\UserSynced;
    use Illuminate\Support\Facades\Event;
    
    Event::listen(UserSynced::class, function ($event) {
        // Post-sync logic (e.g., log, notify)
    });
    

2. Group Synchronization

Sync Laravel groups to LDAP groups (if supported by your LDAP schema):

Ldap::syncGroup($laravelGroup, $ldapGroupDn);

Extend app/Models/LdapGroup.php to map Laravel groups to LDAP group DNs.

3. Authentication

Override Laravel’s default auth to use LDAP for login:

// In AuthController or similar
public function login(Request $request) {
    if (config('ldap.auth_enabled')) {
        return Ldap::authenticate($request->email, $request->password);
    }
    // Fallback to default auth
}

4. Attribute Mapping

Customize attribute mapping in config/ldap.php:

'attribute_mappings' => [
    'email'    => 'mail',
    'username' => 'sAMAccountName',
    'name'     => 'cn',
],

Override dynamically in a service:

Ldap::setAttributeMapping(['custom_field' => 'extensionAttribute3']);

Integration Tips

Laravel Models

  • Extend User Model Add LDAP-specific methods to your User model:

    public function syncWithLdap() {
        return Ldap::syncUser($this);
    }
    
  • Accessors for LDAP Data Fetch LDAP attributes without syncing:

    public function getLdapAttribute($attribute) {
        return Ldap::getUserAttribute($this->email, $attribute);
    }
    

Middleware

Restrict LDAP-dependent routes:

Route::middleware(['ldap.connected'])->group(function () {
    // Routes requiring LDAP
});

Register middleware in app/Http/Kernel.php:

protected $routeMiddleware = [
    'ldap.connected' => \Chill\Ldap\Http\Middleware\CheckLdapConnection::class,
];

Testing

Mock LDAP responses in tests:

$this->partialMock(\Chill\Ldap\LdapManager::class, function ($mock) {
    $mock->shouldReceive('search')
         ->andReturn([/* mock LDAP entry */]);
});

Gotchas and Tips

Pitfalls

  1. Connection Issues

    • Symptom: Sync fails silently or throws Connection refused.
    • Fix: Verify config/ldap.php settings (host, port, TLS/SSL). Test with:
      Ldap::connect()->isConnected(); // Should return true
      
    • Debug: Enable logging in config/ldap.php:
      'debug' => env('LDAP_DEBUG', false),
      
  2. Attribute Mismatches

    • Symptom: User sync fails with "Invalid attribute mapping".
    • Fix: Check your LDAP schema for correct attribute names (e.g., uid vs. sAMAccountName). Use:
      Ldap::getSchema(); // Inspect available attributes
      
  3. Performance with Large Directories

    • Symptom: Sync hangs or times out.
    • Fix: Limit sync scope with paginate in config/ldap.php:
      'sync' => [
          'batch_size' => 50, // Process 50 users at a time
      ],
      
  4. Case Sensitivity

    • Symptom: User not found during sync/auth.
    • Fix: Normalize usernames/emails in config/ldap.php:
      'options' => [
          'case_insensitive' => true,
      ],
      
  5. Password Sync Risks

    • Symptom: Accidental password overwrites.
    • Fix: Disable password sync in config/ldap.php:
      'sync_passwords' => false,
      
      Or implement a confirmation step before syncing passwords.

Debugging Tips

  1. Enable Verbose Logging Add to config/ldap.php:

    'log_level' => \Monolog\Logger::DEBUG,
    

    Check logs at storage/logs/ldap.log.

  2. LDAP Server-Side Debugging Enable LDAP server logging (e.g., OpenLDAP’s slapd):

    slapd -d -1  # Debug level 1 (adjust as needed)
    
  3. Test with a Single User Use ldap:test command to validate a specific user:

    php artisan ldap:test --email=user@example.com
    
  4. Check for Circular Dependencies Ensure your User model doesn’t trigger infinite loops during sync (e.g., avoid calling syncWithLdap() in observers or accessors).


Extension Points

  1. Custom Sync Logic Override the sync behavior by extending Chill\Ldap\Syncers\UserSyncer:

    namespace App\Ldap;
    
    use Chill\Ldap\Syncers\UserSyncer as BaseSyncer;
    
    class CustomUserSyncer extends BaseSyncer {
        protected function mapAttributes($ldapEntry) {
            // Custom mapping logic
            return parent::mapAttributes($ldapEntry);
        }
    }
    

    Bind it in AppServiceProvider:

    Ldap::extend(function ($app) {
        $app->bind('syncers.user', function () {
            return new CustomUserSyncer();
        });
    });
    
  2. Add Custom LDAP Filters Extend the LdapManager to support custom search filters:

    Ldap::addFilter('active_users', function ($query) {
        return $query->where('objectClass', '=', 'person')
                     ->where('userAccountControl:1.2.840.113556.1.4.803:=2'); // Active flag
    });
    

    Use in sync commands:

    Ldap::search('active_users');
    
  3. Support for Multiple LDAP Servers Dynamically switch LDAP configurations:

    Ldap::setConfig('secondary_ldap');
    

    Define configs in config/ldap.php:

    'configs' => [
        'primary' => [...],
        'secondary' => [...],
    ],
    
  4. Webhooks for Sync Events Dispatch events for pre/post-sync actions:

    // In your sync command
    event(new \Chill\Ldap\Events\PreUserSync($user));
    $result = Ldap::syncUser($user);
    event(new \Chill\Ldap\Events\PostUserSync($user, $result));
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware