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 Lumen Laravel Package

directorytree/ldaprecord-lumen

Integrate LDAP into your Lumen app with LdapRecord-Lumen. Adds configuration and service provider support for LdapRecord so you can connect to LDAP directories, query users and groups, and authenticate via LDAP in Lumen.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require directorytree/ldaprecord-lumen
    

    Ensure your composer.json includes "laravel/lumen-framework": "^8.0|^9.0|^10.0|^11.0".

  2. Publish Config:

    php artisan vendor:publish --provider="DirectoryTree\LdapRecord\Lumen\LdapRecordServiceProvider" --tag="config"
    

    This generates config/ldaprecord.php. Configure your LDAP server details (host, base DN, bind DN, etc.).

  3. First Use Case: Authenticate a user via LDAP in a Lumen route:

    use DirectoryTree\LdapRecord\Lumen\Facades\LdapRecord;
    
    $route->get('/auth', function () {
        $user = LdapRecord::findUser('username');
        if ($user && $user->validatePassword('password')) {
            return response()->json(['success' => true]);
        }
        return response()->json(['error' => 'Invalid credentials'], 401);
    });
    

Key Files to Review

  • Config: config/ldaprecord.php (LDAP connection settings, user model mappings).
  • Facade: DirectoryTree\LdapRecord\Lumen\Facades\LdapRecord (primary entry point).
  • Documentation: LdapRecord-Lumen Docs (covers advanced usage).

Implementation Patterns

Core Workflows

  1. Authentication: Use LdapRecord::findUser() + validatePassword() for login logic.

    $user = LdapRecord::findUser($username);
    if ($user && $user->validatePassword($password)) {
        // Authenticate (e.g., generate JWT or session).
    }
    
  2. User Management: Sync LDAP users to your database or fetch attributes:

    // Fetch a user's attributes
    $user = LdapRecord::findUser($username);
    $email = $user->getAttribute('mail');
    
    // Sync all users (if configured)
    LdapRecord::syncUsers();
    
  3. Group Handling: Check group membership:

    $user = LdapRecord::findUser($username);
    $isAdmin = $user->isInGroup('cn=Admins,ou=Groups');
    

Integration Tips

  • Middleware: Create a custom middleware for LDAP auth:

    use DirectoryTree\LdapRecord\LdapRecord;
    
    class LdapAuthMiddleware
    {
        public function handle($request, Closure $next)
        {
            $user = LdapRecord::findUser($request->input('username'));
            if (!$user || !$user->validatePassword($request->input('password'))) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }
            return $next($request);
        }
    }
    
  • Event Listeners: Listen for LDAP sync events (e.g., LdapRecord\Events\UserSynced):

    LdapRecord::listen('user.synced', function ($user) {
        // Log or process synced user.
    });
    
  • Custom Models: Extend DirectoryTree\LdapRecord\Lumen\Models\User to add custom logic:

    class CustomLdapUser extends \DirectoryTree\LdapRecord\Lumen\Models\User
    {
        public function getFullName()
        {
            return $this->getAttribute('givenName') . ' ' . $this->getAttribute('sn');
        }
    }
    

    Bind it in config/ldaprecord.php under user_model.

  • Connection Management: Use LdapRecord::connection() to switch between multiple LDAP servers:

    LdapRecord::connection('secondary_ldap')->findUser($username);
    

Gotchas and Tips

Pitfalls

  1. Connection Timeouts:

    • LDAP servers may timeout during heavy loads. Configure retries in config/ldaprecord.php:
      'connections' => [
          'default' => [
              'timeout' => 30, // Increase timeout (default: 5).
              'retry' => 3,    // Retry failed connections.
          ],
      ],
      
  2. Attribute Mapping:

    • Incorrect attribute mappings (e.g., mail vs. userPrincipalName) can break auth. Verify mappings in config/ldaprecord.php:
      'attributes' => [
          'username' => 'sAMAccountName', // AD-specific.
          'email' => 'mail',
      ],
      
  3. Case Sensitivity:

    • LDAP usernames may be case-insensitive. Normalize inputs:
      $username = strtolower($request->input('username'));
      
  4. SSL/TLS Issues:

    • If using LDAPS, ensure your CA cert is trusted. Configure in config/ldaprecord.php:
      'ssl' => [
          'verify_peer' => true,
          'cafile' => '/path/to/ca-cert.pem',
      ],
      
  5. Lumen-Specific Quirks:

    • Lumen lacks Laravel’s service container helpers. Manually bind the LDAP connection if needed:
      $app->singleton('ldap', function ($app) {
          return LdapRecord::connection();
      });
      

Debugging Tips

  1. Enable Logging: Add to config/ldaprecord.php:

    'debug' => env('LDAP_DEBUG', false),
    

    Check logs for LDAP queries/responses.

  2. Test Connections: Use Tinker to verify connectivity:

    php artisan tinker
    >>> LdapRecord::connection()->connect();
    >>> LdapRecord::connection()->isConnected();
    
  3. Common Errors:

    • "Invalid Credentials": Verify bind DN/password in config.
    • "No Such Object": Check base DN and user search filters.
    • "Timeout": Increase timeout or check network latency.

Extension Points

  1. Custom Search Filters: Override default search logic by extending DirectoryTree\LdapRecord\Lumen\Search\Searchable:

    class CustomSearchable extends \DirectoryTree\LdapRecord\Lumen\Search\Searchable
    {
        protected function getSearchFilter()
        {
            return '(&(objectClass=user)(sAMAccountName=' . $this->username . '))';
        }
    }
    
  2. Post-Sync Hooks: Extend DirectoryTree\LdapRecord\Lumen\Sync\Syncable to add logic after sync:

    class CustomSyncable extends \DirectoryTree\LdapRecord\Lumen\Sync\Syncable
    {
        protected function afterSync($user)
        {
            // Example: Update local DB.
            DB::table('users')->where('ldap_id', $user->getDn())->update([
                'last_sync' => now(),
            ]);
        }
    }
    
  3. Custom Providers: Implement DirectoryTree\LdapRecord\Contracts\LdapProvider for non-standard LDAP setups (e.g., Active Directory with custom schema).

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4