You are here

class OpenIDConnectAccountsForm in OpenID Connect / OAuth client 8

Same name and namespace in other branches
  1. 2.x 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 implements ContainerInjectionInterface {

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

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

  /**
   * The OpenID Connect authmap service.
   *
   * @var \Drupal\openid_connect\OpenIDConnectAuthmap
   */
  protected $authmap;

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

  /**
   * The OpenID Connect client plugin manager.
   *
   * @var \Drupal\openid_connect\Plugin\OpenIDConnectClientManager
   */
  protected $pluginManager;

  /**
   * Drupal\Core\Config\ConfigFactory definition.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $configFactory;

  /**
   * The constructor.
   *
   * @param \Drupal\Core\Session\AccountProxy $current_user
   *   The current user account.
   * @param \Drupal\openid_connect\OpenIDConnectSession $session
   *   The OpenID Connect service.
   * @param \Drupal\openid_connect\OpenIDConnectAuthmap $authmap
   *   The authmap storage.
   * @param \Drupal\openid_connect\OpenIDConnectClaims $claims
   *   The OpenID Connect claims.
   * @param \Drupal\openid_connect\Plugin\OpenIDConnectClientManager $plugin_manager
   *   The OpenID Connect client manager.
   * @param \Drupal\Core\Config\ConfigFactory $config_factory
   *   The config factory.
   */
  public function __construct(AccountProxy $current_user, OpenIDConnectSession $session, OpenIDConnectAuthmap $authmap, OpenIDConnectClaims $claims, OpenIDConnectClientManager $plugin_manager, ConfigFactory $config_factory) {
    $this->currentUser = $current_user;
    $this->session = $session;
    $this->authmap = $authmap;
    $this->claims = $claims;
    $this->pluginManager = $plugin_manager;
    $this->configFactory = $config_factory;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, AccountInterface $user = NULL) {
    $form_state
      ->set('account', $user);
    $clients = $this->pluginManager
      ->getDefinitions();
    $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
      ->getConnectedAccounts($user);
    foreach ($clients as $client) {
      $enabled = $this->configFactory
        ->getEditable('openid_connect.settings.' . $client['id'])
        ->get('enabled');
      if (!$enabled) {
        continue;
      }
      $form[$client['id']] = [
        '#type' => 'fieldset',
        '#title' => $this
          ->t('Provider: @title', [
          '@title' => $client['label'],
        ]),
      ];
      $fieldset =& $form[$client['id']];
      $connected = isset($connected_accounts[$client['id']]);
      $fieldset['status'] = [
        '#type' => 'item',
        '#title' => $this
          ->t('Status'),
        '#markup' => $this
          ->t('Not connected'),
      ];
      if ($connected) {
        $fieldset['status']['#markup'] = $this
          ->t('Connected as %sub', [
          '%sub' => $connected_accounts[$client['id']],
        ]);
        $fieldset['openid_connect_client_' . $client['id'] . '_disconnect'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Disconnect from @client_title', [
            '@client_title' => $client['label'],
          ]),
          '#name' => 'disconnect__' . $client['id'],
        ];
      }
      else {
        $fieldset['status']['#markup'] = $this
          ->t('Not connected');
        $fieldset['openid_connect_client_' . $client['id'] . '_connect'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Connect with @client_title', [
            '@client_title' => $client['label'],
          ]),
          '#name' => 'connect__' . $client['id'],
          '#access' => $this->currentUser
            ->id() == $user
            ->id(),
        ];
      }
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    list($op, $client_name) = explode('__', $form_state
      ->getTriggeringElement()['#name'], 2);
    if ($op === 'disconnect') {
      $this->authmap
        ->deleteAssociation($form_state
        ->get('account')
        ->id(), $client_name);
      $client = $this->pluginManager
        ->getDefinition($client_name);
      $this
        ->messenger()
        ->addMessage($this
        ->t('Account successfully disconnected from @client.', [
        '@client' => $client['label'],
      ]));
      return;
    }
    if ($this->currentUser
      ->id() !== $form_state
      ->get('account')
      ->id()) {
      $this
        ->messenger()
        ->addError($this
        ->t("You cannot connect another user's account."));
      return;
    }
    $this->session
      ->saveDestination();
    $configuration = $this
      ->config('openid_connect.settings.' . $client_name)
      ->get('settings');

    /** @var \Drupal\openid_connect\Plugin\OpenIDConnectClientInterface $client */
    $client = $this->pluginManager
      ->createInstance($client_name, $configuration);
    $scopes = $this->claims
      ->getScopes($client);
    $_SESSION['openid_connect_op'] = $op;
    $_SESSION['openid_connect_connect_uid'] = $this->currentUser
      ->id();
    $response = $client
      ->authorize($scopes, $form_state);
    $form_state
      ->setResponse($response);
  }

  /**
   * 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) {
    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 An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
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. 1
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. Overrides UrlGeneratorTrait::redirect
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 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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::$configFactory protected property Drupal\Core\Config\ConfigFactory definition. Overrides FormBase::$configFactory
OpenIDConnectAccountsForm::$currentUser protected property Drupal\Core\Session\AccountProxy definition.
OpenIDConnectAccountsForm::$pluginManager protected property The OpenID Connect client plugin 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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.