0

I am trying to perform an LDAP search from hook_form_validation() in a webform using Drupal 9 and drupal/ldap 4.3.

I have configured the LDAP module on my site, but I am not using it for authentication. I can however use ldap query and perform a test of the ldap server on /admin/config/people/ldap/server successfully.

At the bottom of API usage they say you can use the following code.

$factory = \Drupal::service('ldap.servers');
$server = $factory->getServerByIdEnabled('my_server');

I have been enlightend cliefen that the service is ldap.bridge. Here is my current code.

use Drupal\user\Entity\User;
use Drupal\taxonomy\Entity\Term;
use Drupal\ldap_servers\Entity\Server;


function drp_form_alter( &$form, &$form_state, $form_id ) {
  if ( $form_id === 'webform_submission__myform_node_5930_add_form' ) {
    $userid = \Drupal::currentUser()->id();
    $username = \Drupal::currentUser()->getAccountName();
    $server = \Drupal::service('entity_type.manager')->getStorage( 'ldap_server')->load('myserver');
    $bridge = \Drupal::service('ldap.bridge');
    $bridge->setServer( $server );
    if ($bridge->bind()) {
        
        // $dn ='ou=accounts,ou=departments,dc=servername,dc=someplace';
        // $filter="(uid=xxxx1)";
        // $returnattr = array( "sn", "givenname", "mail");

    }
  }

}

I was able to successfully bind the ldap server.

Question: how do I actually make an ldap search, using the drupal/ldap code, inside the bridge->bind if statement?

I did not use the $factory-> code that the API mentioned. Do I need to?

Thanks for all your help, I am struggling, but learning :)

4
  • 1
    Is that a valid service name?
    – Kevin
    Jan 31, 2023 at 16:35
  • 1
    Welcome to Drupal Answers! That documentation page also reads "Disclaimer: The 3.x branch still receives heavy refactoring on an on-going basis. You will need to update your custom code accordingly." and now it's on version 4. I think the service you want is now called ldap.bridge, but I am not writing this as an answer because I am not sure.
    – cilefen
    Jan 31, 2023 at 18:24
  • Thanks cilefen! You are correct. I am getting closer :) Jan 31, 2023 at 19:00
  • Anyone know of any example code I can look at? Feb 1, 2023 at 14:55

1 Answer 1

1

I think there's just a couple of calls missing, or at least the following works for me:

if ($bridge->bind()) {
    $ldap = $bridge->get() ;
    $options = [] ;
    $entries = $ldap
        ->query('', "(&(objectclass=groupOfNames)(member=$user_dn))", $options) 
        ->execute() 
        ->toArray() ;
}

(The query is irrelevant, of course – it comes straight from my code).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.