You are here

class Oauth2AuthorizeForm in Simple OAuth (OAuth2) & OpenID Connect 8.3

Same name and namespace in other branches
  1. 8.2 simple_oauth_extras/src/Controller/Oauth2AuthorizeForm.php \Drupal\simple_oauth_extras\Controller\Oauth2AuthorizeForm

Authorize form.

Hierarchy

Expanded class hierarchy of Oauth2AuthorizeForm

File

simple_oauth_extras/src/Controller/Oauth2AuthorizeForm.php, line 20

Namespace

Drupal\simple_oauth_extras\Controller
View source
class Oauth2AuthorizeForm extends FormBase {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * @var \Symfony\Bridge\PsrHttpMessage\HttpMessageFactoryInterface
   */
  protected $messageFactory;

  /**
   * @var \Symfony\Bridge\PsrHttpMessage\HttpFoundationFactoryInterface
   */
  protected $foundationFactory;

  /**
   * @var \League\OAuth2\Server\AuthorizationServer
   */
  protected $server;

  /**
   * @var \Drupal\simple_oauth\Plugin\Oauth2GrantManagerInterface
   */
  protected $grantManager;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The known client repository service.
   *
   * @var \Drupal\simple_oauth\KnownClientsRepositoryInterface
   */
  protected $knownClientRepository;

  /**
   * Oauth2AuthorizeForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Symfony\Bridge\PsrHttpMessage\HttpMessageFactoryInterface $message_factory
   *   The message factory.
   * @param \Symfony\Bridge\PsrHttpMessage\HttpFoundationFactoryInterface $foundation_factory
   *   The foundation factory.
   * @param \Drupal\simple_oauth\Plugin\Oauth2GrantManagerInterface $grant_manager
   *   The grant manager.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\simple_oauth\KnownClientsRepositoryInterface $known_clients_repository
   *   The known client repository service.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, HttpMessageFactoryInterface $message_factory, HttpFoundationFactoryInterface $foundation_factory, Oauth2GrantManagerInterface $grant_manager, ConfigFactoryInterface $config_factory, KnownClientsRepositoryInterface $known_clients_repository) {
    $this->entityTypeManager = $entity_type_manager;
    $this->messageFactory = $message_factory;
    $this->foundationFactory = $foundation_factory;
    $this->grantManager = $grant_manager;
    $this->configFactory = $config_factory;
    $this->knownClientRepository = $known_clients_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('psr7.http_message_factory'), $container
      ->get('psr7.http_foundation_factory'), $container
      ->get('plugin.manager.oauth2_grant.processor'), $container
      ->get('config.factory'), $container
      ->get('simple_oauth.known_clients'));
  }

  /**
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'simple_oauth_authorize_form';
  }

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form structure.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \League\OAuth2\Server\Exception\OAuthServerException
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $request = $this
      ->getRequest();
    if ($request
      ->get('response_type') == 'code') {
      $grant_type = 'code';
    }
    elseif ($request
      ->get('response_type') == 'token') {
      $grant_type = 'implicit';
    }
    else {
      $grant_type = NULL;
    }
    $this->server = $this->grantManager
      ->getAuthorizationServer($grant_type);

    // Transform the HTTP foundation request object into a PSR-7 object. The
    // OAuth library expects a PSR-7 request.
    $psr7_request = $this->messageFactory
      ->createRequest($request);

    // Validate the HTTP request and return an AuthorizationRequest object.
    // The auth request object can be serialized into a user's session.
    $auth_request = $this->server
      ->validateAuthorizationRequest($psr7_request);

    // Store the auth request temporarily.
    $form_state
      ->set('auth_request', $auth_request);
    $manager = $this->entityTypeManager;
    $form = [
      '#type' => 'container',
    ];
    $client_uuid = $request
      ->get('client_id');
    $client_drupal_entities = $manager
      ->getStorage('consumer')
      ->loadByProperties([
      'uuid' => $client_uuid,
    ]);
    if (empty($client_drupal_entities)) {
      throw OAuthServerException::invalidClient();
    }
    $client_drupal_entity = reset($client_drupal_entities);
    $cacheablity_metadata = new CacheableMetadata();
    $form['client'] = $manager
      ->getViewBuilder('consumer')
      ->view($client_drupal_entity);
    $form['scopes'] = [
      '#title' => $this
        ->t('Permissions'),
      '#theme' => 'item_list',
      '#items' => [],
    ];
    $client_roles = [];
    foreach ($client_drupal_entity
      ->get('roles') as $role_item) {
      $client_roles[$role_item->target_id] = $role_item->entity;
    }

    /** @var \Drupal\simple_oauth\Entities\ScopeEntityNameInterface $scope */
    foreach ($auth_request
      ->getScopes() as $scope) {
      $cacheablity_metadata
        ->addCacheableDependency($scope);
      $form['scopes']['#items'][] = $scope
        ->getName();
      unset($client_roles[$scope
        ->getIdentifier()]);
    }

    // Add the client roles that were not explicitly requested to the list.
    foreach ($client_roles as $client_role) {
      $cacheablity_metadata
        ->addCacheableDependency($client_role);
      $form['scopes']['#items'][] = $client_role
        ->label();
    }
    $cacheablity_metadata
      ->applyTo($form['scopes']);
    $form['redirect_uri'] = [
      '#type' => 'hidden',
      '#value' => $request
        ->get('redirect_uri') ? $request
        ->get('redirect_uri') : $client_drupal_entity
        ->get('redirect')->value,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Grant'),
    ];
    return $form;
  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($auth_request = $form_state
      ->get('auth_request')) {
      $can_grant_codes = $this
        ->currentUser()
        ->hasPermission('grant simple_oauth codes');
      $redirect_response = Oauth2AuthorizeController::redirectToCallback($auth_request, $this->server, $this
        ->currentUser(), (bool) $form_state
        ->getValue('submit') && $can_grant_codes, (bool) $this->configFactory
        ->get('simple_oauth.settings')
        ->get('remember_clients'), $this->knownClientRepository);
      $form_state
        ->setResponse($redirect_response);
    }
  }

}

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.
Oauth2AuthorizeForm::$configFactory protected property The config factory. Overrides FormBase::$configFactory
Oauth2AuthorizeForm::$entityTypeManager protected property
Oauth2AuthorizeForm::$foundationFactory protected property
Oauth2AuthorizeForm::$grantManager protected property
Oauth2AuthorizeForm::$knownClientRepository protected property The known client repository service.
Oauth2AuthorizeForm::$messageFactory protected property
Oauth2AuthorizeForm::$server protected property
Oauth2AuthorizeForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
Oauth2AuthorizeForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
Oauth2AuthorizeForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
Oauth2AuthorizeForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
Oauth2AuthorizeForm::__construct public function Oauth2AuthorizeForm 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.