I have created a module that bulk create user entities depending on ldap filters and assign selected roles . The problem is the connection with cas is then not working when a user entry has been already created
here is my code so far:
<?php /**
* @file
* Contains \Drupal\example\Form\ExampleForm.
*/
namespace Drupal\my_import_ldap\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements an example form.
*/
class MyImportLdapSettingsForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'my_ldap_import_settings_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$system_roles = user_role_names(TRUE);
$form['ldap_filter'] = array(
'#type' => 'textarea',
'#title' => $this->t('LDAP Filter'),
'#description' => t('Specify LDAP filter used to populate Drupal user account'),
);
$form['actions2']['#type'] = 'actions';
$form['actions2']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Save Filter'),
'#button_type' => 'primary',
);
$form['roles_list'] = array(
'#type' => 'checkboxes',
'#title' => $this->t('Rôles'),
'#description' => t('Select the roles to assign created account'),
'#options' => $system_roles,
);
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Import to Drupal People'),
'#button_type' => 'primary',
);
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
}
/**
* {@inheritdoc}
*
* @author m.Dandonneau
*
*
* add or update users, corresponding to the LDAP filters and add the selected roles
*
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
if ($_POST['op']== 'Import to Drupal People'){
$filter = $form_state->getValue('ldap_filter');
$roles =$form_state->getValue('roles_list');
$selected_roles=array();
foreach($roles as $key => $value)
{
if(is_string($value))
{
$selected_roles[]=$value;
}
}
//retrieve ldap settings yml from my_ldap module
$my_ldap_config = \Drupal::service('config.factory')->getEditable('my_ldap.config_settings');
$restrictions = explode(",", $my_ldap_config->get('my_ldap_restrictions'));
$server = $my_ldap_config->get('my_ldap_server');
$port = $my_ldap_config->get('my_ldap_port');
$dn = $my_ldap_config->get('my_ldap_dn');
$rootdn = $my_ldap_config->get('my_ldap_root_dn');
$rootpw = $my_ldap_config->get('my_ldap_root_pwd');
$attributes = array();
$ds = ldap_connect($server, $port);
if ($ds) {
$r = ldap_bind($ds, $rootdn, $rootpw);
$sr = ldap_search($ds, $dn, $filter, $restrictions);
$info = ldap_get_entries($ds, $sr);
$selected_users=array();
if ($info["count"] > 0) {
for($i=0;$i<$info["count"];$i++)
{
$account=$this->create_update_drupal_user_account($info[$i]["uid"][0],$info[$i]["mymail"][0],$selected_roles);
$this->set_cas_user_name($account,$info[$i]["cn"][0]);
$selected_users[] = $info[$i]["uid"][0];
}
drupal_set_message($this->t('@selected_users ont été ajoutées ou updatées aux utilisateurs avec le(s) roles @selected_roles', array('@selected_users' => json_encode($selected_users),'@selected_roles' => json_encode($selected_roles))));
\Drupal::logger('my_import_ldap')->notice($this->t('les personnes aux uids suivants @selected_users ont été ajoutées ou updatées avec le(s) roles @selected_roles', array('@selected_users' => json_encode($selected_users),'@selected_roles' => json_encode($selected_roles))));
}
else{
drupal_set_message($this->t("le filtre LDAP @filtre n'a retourné aucun utilisateur", array('@filtre' => $form_state->getValue('ldap_filter'))));
\Drupal::logger('my_import_ldap')->error($this->t("le filtre LDAP @filtre n'a retourné aucun utilisateur", array('@filtre' => $form_state->getValue('ldap_filter'))));
}
}
}
if ($_POST['op']== 'Save Filter')
drupal_set_message($this->t('update filter', array('@number' => $form_state->getValue('ldap_filter'))));
}
public function create_update_drupal_user_account($user_name,$user_mail,$roles){
$lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
$uid = \Drupal::entityQuery('user')
->condition('name', $user_name)
->execute();
if(!empty($uid)){
$uid=(int)reset($uid);
$user = \Drupal\user\Entity\User::load($uid);
}
if (!$user) {
$user = \Drupal\user\Entity\User::create();
//table structure is UNIQUE KEY `user__name` (`name`,`langcode`)
$user->setUsername($user_name);
$user->set("langcode", $lang);
$user->enforceIsNew();
$user->setEmail($user_mail);
/*$user->setPassword(user_password());*/
}
foreach ($roles as $role)
$user->addRole($role);
$user->activate();
$result = $user->save();
return $user;
}
/**
* @param $account
*/
public function set_cas_user_name($account,$ldap_common_name){
$lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
$uid=$account->get('uid')->getValue()[0];
$db = \Drupal::database();
$query=$db->insert('user__field_cn_ldap')->fields(
array(
'bundle' => 'user',
'entity_id' => $uid['value'],
'revision_id' => $uid['value'],
'langcode' => 'en',
'delta' => 0,
'field_cn_ldap_value' => $ldap_common_name,
)
)->execute();
$cas_user_manager = \Drupal::service('cas.user_manager');
$cas_user_manager->setCasUsernameForAccount($account, '$ldap_common_name');
}
}