You are here

function _cas_user_form_validate in CAS 8

Same name and namespace in other branches
  1. 2.x cas.module \_cas_user_form_validate()

Validation callback for the user entity form.

Verify that the provided CAS username is not already taken by someone else.

Parameters

array $form: The form.

\Drupal\Core\Form\FormStateInterface $form_state: The form state object.

1 string reference to '_cas_user_form_validate'
_cas_add_cas_username_to_user_form in ./cas.module
Alter the user entity form to include a textfield for CAS username.

File

./cas.module, line 166
Provides CAS authentication for Drupal.

Code

function _cas_user_form_validate(array &$form, FormStateInterface $form_state) {

  // Verify that it was the save / register button that was clicked. We don't
  // want to run our validation if this was for a 'cancel account' action.
  if (in_array('::save', $form_state
    ->getTriggeringElement()['#submit'])) {

    // If the CAS enabled checkbox was checked, then ensure that the CAS
    // username field is not empty.
    if ($form_state
      ->getValue('cas_enabled') && empty($form_state
      ->getValue('cas_username'))) {
      $form_state
        ->setError($form['account']['cas_username'], t('Please provide a CAS username, or uncheck "Allow user to log in via CAS".'));
    }

    // The externalauth module does not provide this validation so we have to
    // implement it ourselves. See https://drupal.org/node/2804797.
    $cas_username = $form_state
      ->getValue('cas_username');
    if (!empty($cas_username)) {
      $cas_user_manager = \Drupal::service('cas.user_manager');
      $existing_uid = $cas_user_manager
        ->getUidForCasUsername($cas_username);
      $user_being_edited = $form_state
        ->getFormObject()
        ->getEntity();
      if ($existing_uid && $existing_uid !== $user_being_edited
        ->id()) {
        $form_state
          ->setError($form['account']['cas_username'], t('The specified CAS username is already in use by another user.'));
      }
    }
  }
}