You are here

class OpenIDConnectAccountsForm in OpenID Connect / OAuth client 2.x

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

Provides the user-specific OpenID Connect settings form.

@package Drupal\openid_connect\Form

Hierarchy

Expanded class hierarchy of OpenIDConnectAccountsForm

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

File

src/Form/OpenIDConnectAccountsForm.php, line 23

Namespace

Drupal\openid_connect\Form
View source
class OpenIDConnectAccountsForm extends FormBase {

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

  /**
   * Drupal\Core\Session\AccountProxyInterface definition.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * The OpenID Connect session service.
   *
   * @var \Drupal\openid_connect\OpenIDConnectSessionInterface
   */
  protected $session;

  /**
   * The OpenID Connect authmap service.
   *
   * @var \Drupal\externalauth\AuthmapInterface
   */
  protected $authmap;

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

  /**
   * The constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactory $config_factory
   *   The config factory.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user account.
   * @param \Drupal\externalauth\AuthmapInterface $authmap
   *   The authmap storage.
   * @param \Drupal\openid_connect\OpenIDConnectClaims $claims
   *   The OpenID Connect claims.
   * @param \Drupal\openid_connect\OpenIDConnectSessionInterface $session
   *   The OpenID Connect session service.
   */
  public function __construct(ConfigFactory $config_factory, EntityTypeManagerInterface $entity_type_manager, AccountProxyInterface $current_user, AuthmapInterface $authmap, OpenIDConnectClaims $claims, OpenIDConnectSessionInterface $session) {
    $this
      ->setConfigFactory($config_factory);
    $this->entityTypeManager = $entity_type_manager;
    $this->currentUser = $current_user;
    $this->authmap = $authmap;
    $this->claims = $claims;
    $this->session = $session;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, AccountInterface $user = NULL) : array {
    $form_state
      ->set('account', $user);

    /** @var \Drupal\openid_connect\OpenIDConnectClientEntityInterface[] $clients */
    $clients = $this->entityTypeManager
      ->getStorage('openid_connect_client')
      ->loadByProperties([
      'status' => TRUE,
    ]);
    $form['help'] = [
      '#prefix' => '<p class="description">',
      '#suffix' => '</p>',
    ];
    if (empty($clients)) {
      $form['help']['#markup'] = $this
        ->t('No external account providers are available.');
      return $form;
    }
    elseif ($this->currentUser
      ->id() == $user
      ->id()) {
      $form['help']['#markup'] = $this
        ->t('You can connect your account with these external providers.');
    }
    $connected_accounts = $this->authmap
      ->getAll($user
      ->id());
    foreach ($clients as $client) {
      $id = $client
        ->id();
      $label = $client
        ->label();
      $form[$id] = [
        '#type' => 'fieldset',
        '#title' => $this
          ->t('Provider: @title', [
          '@title' => $label,
        ]),
      ];
      $fieldset =& $form[$id];
      $connected = isset($connected_accounts['openid_connect.' . $id]);
      $fieldset['status'] = [
        '#type' => 'item',
        '#title' => $this
          ->t('Status'),
      ];
      if ($connected) {
        $fieldset['status']['#markup'] = $this
          ->t('Connected as %sub', [
          '%sub' => $connected_accounts['openid_connect.' . $id],
        ]);
        $fieldset['openid_connect_client_' . $id . '_disconnect'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Disconnect from @client_title', [
            '@client_title' => $label,
          ]),
          '#name' => 'disconnect__' . $id,
        ];
      }
      else {
        $fieldset['status']['#markup'] = $this
          ->t('Not connected');
        $fieldset['openid_connect_client_' . $id . '_connect'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Connect with @client_title', [
            '@client_title' => $label,
          ]),
          '#name' => 'connect__' . $id,
          '#access' => $this->currentUser
            ->id() == $user
            ->id(),
        ];
      }
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($this->currentUser
      ->id() !== $form_state
      ->get('account')
      ->id()) {
      $this
        ->messenger()
        ->addError($this
        ->t("You cannot connect another user's account."));
      return;
    }
    list($op, $client_name) = explode('__', $form_state
      ->getTriggeringElement()['#name'], 2);

    /** @var \Drupal\openid_connect\OpenIDConnectClientEntityInterface $client */
    $client = $this->entityTypeManager
      ->getStorage('openid_connect_client')
      ->loadByProperties([
      'id' => $client_name,
    ])[$client_name];
    switch ($op) {
      case 'disconnect':
        $this->authmap
          ->delete($form_state
          ->get('account')
          ->id(), 'openid_connect.' . $client_name);
        $this
          ->messenger()
          ->addMessage($this
          ->t('Account successfully disconnected from @client.', [
          '@client' => $client
            ->label(),
        ]));
        break;
      case 'connect':
        $this->session
          ->saveDestination();
        $plugin = $client
          ->getPlugin();
        $scopes = $this->claims
          ->getScopes($plugin);
        $this->session
          ->saveOp('connect', $this->currentUser
          ->id());
        $response = $plugin
          ->authorize($scopes);
        $form_state
          ->setResponse($response);
        break;
    }
  }

  /**
   * Checks access for the OpenID-Connect accounts form.
   *
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The user having accounts.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $user) : AccessResultInterface {
    if ($this->currentUser
      ->hasPermission('administer users')) {
      return AccessResult::allowed();
    }
    if ($this->currentUser
      ->id() && $this->currentUser
      ->id() === $user
      ->id() && $this->currentUser
      ->hasPermission('manage own openid connect accounts')) {
      return AccessResult::allowed();
    }
    return AccessResult::forbidden();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::config protected function Retrieves a configuration object.
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.
OpenIDConnectAccountsForm::$authmap protected property The OpenID Connect authmap service.
OpenIDConnectAccountsForm::$claims protected property The OpenID Connect claims service.
OpenIDConnectAccountsForm::$currentUser protected property Drupal\Core\Session\AccountProxyInterface definition.
OpenIDConnectAccountsForm::$entityTypeManager protected property The entity type manager.
OpenIDConnectAccountsForm::$session protected property The OpenID Connect session service.
OpenIDConnectAccountsForm::access public function Checks access for the OpenID-Connect accounts form.
OpenIDConnectAccountsForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
OpenIDConnectAccountsForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
OpenIDConnectAccountsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
OpenIDConnectAccountsForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
OpenIDConnectAccountsForm::__construct public function The constructor.
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.