You are here

class OpenIDConnectSettingsForm in OpenID Connect / OAuth client 2.x

Same name and namespace in other branches
  1. 8 src/Form/OpenIDConnectSettingsForm.php \Drupal\openid_connect\Form\OpenIDConnectSettingsForm

Provides the OpenID Connect settings form.

@package Drupal\openid_connect\Form

Hierarchy

Expanded class hierarchy of OpenIDConnectSettingsForm

1 string reference to 'OpenIDConnectSettingsForm'
openid_connect.routing.yml in ./openid_connect.routing.yml
openid_connect.routing.yml

File

src/Form/OpenIDConnectSettingsForm.php, line 19

Namespace

Drupal\openid_connect\Form
View source
class OpenIDConnectSettingsForm extends ConfigFormBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The OpenID Connect service.
   *
   * @var \Drupal\openid_connect\OpenIDConnect
   */
  protected $openIDConnect;

  /**
   * The OpenID Connect claims service.
   *
   * @var \Drupal\openid_connect\OpenIDConnectClaims
   */
  protected $claims;

  /**
   * The constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   * @param \Drupal\openid_connect\OpenIDConnect $openid_connect
   *   The OpenID Connect service.
   * @param \Drupal\openid_connect\OpenIDConnectClaims $claims
   *   The claims.
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, OpenIDConnect $openid_connect, OpenIDConnectClaims $claims) {
    parent::__construct($config_factory);
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFieldManager = $entity_field_manager;
    $this->openIDConnect = $openid_connect;
    $this->claims = $claims;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'), $container
      ->get('openid_connect.openid_connect'), $container
      ->get('openid_connect.claims'));
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() : array {
    return [
      'openid_connect.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() : string {
    return 'openid_connect_admin_settings';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) : array {
    $settings = $this
      ->configFactory()
      ->getEditable('openid_connect.settings');
    $form['always_save_userinfo'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Save user claims on every login'),
      '#description' => $this
        ->t('If disabled, user claims will only be saved when the account is first created.'),
      '#default_value' => $settings
        ->get('always_save_userinfo'),
    ];
    $form['connect_existing_users'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Automatically connect existing users'),
      '#description' => $this
        ->t('If disabled, authentication will fail for existing email addresses.'),
      '#default_value' => $settings
        ->get('connect_existing_users'),
    ];
    $form['override_registration_settings'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Override registration settings'),
      '#description' => $this
        ->t('If enabled, user creation will always be allowed, even if the registration setting is set to require admin approval, or only allowing admins to create users.'),
      '#default_value' => $settings
        ->get('override_registration_settings'),
    ];
    $form['end_session_enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Logout from identity provider'),
      '#description' => $this
        ->t('If enabled and supported by the identity provider, logging out from Drupal will also logout the user from the identity provider.'),
      '#default_value' => $settings
        ->get('end_session_enabled'),
    ];
    $form['user_login_display'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('OpenID buttons display in user login form'),
      '#options' => [
        'hidden' => $this
          ->t('Hidden'),
        'above' => $this
          ->t('Above'),
        'below' => $this
          ->t('Below'),
        'replace' => $this
          ->t('Replace'),
      ],
      '#description' => $this
        ->t("Modify the user login form to show the the OpenID login buttons. If the 'Replace' option is selected, only the OpenID buttons will be displayed. In this case, pass the 'showcore' URL parameter to return to a password-based login form."),
      '#default_value' => $settings
        ->get('user_login_display'),
    ];
    $form['redirects'] = [
      '#title' => $this
        ->t('Redirects'),
      '#type' => 'fieldset',
    ];
    $form['redirects']['redirect_login'] = [
      '#title' => $this
        ->t('Login'),
      '#type' => 'textfield',
      '#description' => $this
        ->t('Path to redirect to on client login'),
      '#default_value' => $settings
        ->get('redirect_login'),
    ];
    $form['redirects']['redirect_logout'] = [
      '#title' => $this
        ->t('Logout'),
      '#type' => 'textfield',
      '#description' => $this
        ->t('Path to redirect to on client logout'),
      '#default_value' => $settings
        ->get('redirect_logout'),
    ];
    $form['userinfo_mappings'] = [
      '#title' => $this
        ->t('User claims mapping'),
      '#type' => 'fieldset',
      '#tree' => TRUE,
    ];
    $properties = $this->entityFieldManager
      ->getFieldDefinitions('user', 'user');
    $properties_skip = $this->openIDConnect
      ->userPropertiesIgnore();
    $claims = $this->claims
      ->getOptions();
    $mappings = $settings
      ->get('userinfo_mappings');
    foreach ($properties as $property_name => $property) {
      if (isset($properties_skip[$property_name])) {
        continue;
      }
      $form['userinfo_mappings'][$property_name] = [
        '#type' => 'select',
        '#title' => $property
          ->getLabel(),
        '#description' => $property
          ->getDescription(),
        '#options' => (array) $claims,
        '#empty_value' => '',
        '#empty_option' => $this
          ->t('- No mapping -'),
        '#default_value' => $mappings[$property_name] ?? '',
      ];
    }

    /** @var \Drupal\user\Entity\Role[] $roles */
    $roles = $this->entityTypeManager
      ->getStorage('user_role')
      ->loadMultiple();
    unset($roles['anonymous']);
    unset($roles['authenticated']);
    $role_mappings = $settings
      ->get('role_mappings');
    $form['role_mappings'] = [
      '#title' => 'EXPERIMENTAL - ' . $this
        ->t('User role mapping'),
      '#type' => 'fieldset',
      '#description' => $this
        ->t('For each Drupal role, provide the sets of equivalent external groups, separated by spaces. A user belonging to one of the provided groups will be assigned the configured Drupal role. Use client_id.group to limit a group to a specific client.'),
      '#tree' => TRUE,
    ];
    foreach ($roles as $role_id => $role) {
      $default = '';
      if (is_array($role_mappings[$role_id])) {

        // Surround any mappings with spaces with double quotes.
        foreach ($role_mappings[$role_id] as $key => $mapping) {
          if (strpos($mapping, ' ') !== FALSE) {
            $role_mappings[$role_id][$key] = '"' . $mapping . '"';
          }
        }
        $default = implode(' ', $role_mappings[$role_id]);
      }
      $form['role_mappings'][$role_id] = [
        '#title' => $role
          ->label(),
        '#type' => 'textfield',
        '#default_value' => $default,
      ];
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $role_mappings = [];
    foreach ($form_state
      ->getValue('role_mappings') as $role => $mapping) {
      $role_mappings[$role] = array_values(array_filter(str_getcsv($mapping, ' ')));
    }
    $this
      ->config('openid_connect.settings')
      ->set('always_save_userinfo', $form_state
      ->getValue('always_save_userinfo'))
      ->set('connect_existing_users', $form_state
      ->getValue('connect_existing_users'))
      ->set('override_registration_settings', $form_state
      ->getValue('override_registration_settings'))
      ->set('end_session_enabled', $form_state
      ->getValue('end_session_enabled'))
      ->set('user_login_display', $form_state
      ->getValue('user_login_display'))
      ->set('redirect_login', $form_state
      ->getValue('redirect_login'))
      ->set('redirect_logout', $form_state
      ->getValue('redirect_logout'))
      ->set('userinfo_mappings', array_filter($form_state
      ->getValue('userinfo_mappings')))
      ->set('role_mappings', $role_mappings)
      ->save();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 72
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
OpenIDConnectSettingsForm::$claims protected property The OpenID Connect claims service.
OpenIDConnectSettingsForm::$entityFieldManager protected property The entity field manager.
OpenIDConnectSettingsForm::$entityTypeManager protected property The entity type manager.
OpenIDConnectSettingsForm::$openIDConnect protected property The OpenID Connect service.
OpenIDConnectSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
OpenIDConnectSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
OpenIDConnectSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
OpenIDConnectSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
OpenIDConnectSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
OpenIDConnectSettingsForm::__construct public function The constructor. Overrides ConfigFormBase::__construct
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.