You are here

class OAuth2Controller in OAuth2 Server 2.0.x

Same name and namespace in other branches
  1. 8 src/Controller/OAuth2Controller.php \Drupal\oauth2_server\Controller\OAuth2Controller

Class OAuth2 Controller.

@package Drupal\oauth2_server\Controller

Hierarchy

Expanded class hierarchy of OAuth2Controller

File

src/Controller/OAuth2Controller.php, line 23

Namespace

Drupal\oauth2_server\Controller
View source
class OAuth2Controller extends ControllerBase {

  /**
   * The OAuth2Storage.
   *
   * @var \Drupal\oauth2_server\OAuth2StorageInterface
   */
  protected $storage;

  /**
   * Constructs a new \Drupal\oauth2_server\Controller\OAuth2Controller object.
   *
   * @param \Drupal\oauth2_server\OAuth2StorageInterface $oauth2_storage
   *   The OAuth2 storage object.
   */
  public function __construct(OAuth2StorageInterface $oauth2_storage) {
    $this->storage = $oauth2_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('oauth2_server.storage'));
  }

  /**
   * Authorize.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match object.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return array|\OAuth2\HttpFoundationBridge\Response|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
   *   A form array or a response object.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function authorize(RouteMatchInterface $route_match, Request $request) {
    $this
      ->moduleHandler()
      ->invokeAll('oauth2_server_pre_authorize');

    // Workaround https://www.drupal.org/project/oauth2_server/issues/3049250
    // Create a duplicate request with the parameters removed, so that the
    // object can survive being serialized.
    $duplicated_request = $request
      ->duplicate(NULL, NULL, []);
    $bridgeRequest = BridgeRequest::createFromRequest($duplicated_request);
    if ($this
      ->currentUser()
      ->isAnonymous()) {
      $_SESSION['oauth2_server_authorize'] = $bridgeRequest;
      $url = new Url('user.login', [], [
        'query' => [
          'destination' => Url::fromRoute('oauth2_server.authorize')
            ->toString(),
        ],
      ]);
      $url
        ->setAbsolute(TRUE);
      return new RedirectResponse($url
        ->toString());
    }

    // A login happened: Create the request with parameters from the session.
    if (!empty($_SESSION['oauth2_server_authorize'])) {
      $bridgeRequest = $_SESSION['oauth2_server_authorize'];
    }
    $client = FALSE;
    if ($bridgeRequest
      ->get('client_id')) {

      /** @var \Drupal\oauth2_server\ClientInterface[] $clients */
      $clients = $this
        ->entityTypeManager()
        ->getStorage('oauth2_server_client')
        ->loadByProperties([
        'client_id' => $bridgeRequest
          ->get('client_id'),
      ]);
      if ($clients) {
        $client = reset($clients);
      }
    }
    if (!$client) {
      return new JsonResponse([
        'error' => 'Client could not be found.',
      ], JsonResponse::HTTP_NOT_FOUND);
    }

    // Initialize the server.
    $oauth2_server = Utility::startServer($client
      ->getServer(), $this->storage);

    // Automatic authorization is enabled for this client. Finish authorization.
    // handleAuthorizeRequest() will call validateAuthorizeRequest().
    $response = new BridgeResponse();
    if ($client->automatic_authorization) {
      unset($_SESSION['oauth2_server_authorize']);
      $oauth2_server
        ->handleAuthorizeRequest($bridgeRequest, $response, TRUE, $this
        ->currentUser()
        ->id());
      return $response;
    }
    else {

      // Validate the request.
      if (!$oauth2_server
        ->validateAuthorizeRequest($bridgeRequest, $response)) {

        // Clear the parameters saved in the session to avoid reusing them when
        // doing an other request while logged in.
        unset($_SESSION['oauth2_server_authorize']);
        return $response;
      }

      // Determine the scope for this request.
      $scope_util = new ScopeUtility($client
        ->getServer());
      if (!($scope = $scope_util
        ->getScopeFromRequest($bridgeRequest))) {
        $scope = $scope_util
          ->getDefaultScope();
      }

      // Convert the scope string to a set of entities.
      $scope_names = explode(' ', $scope);
      $scopes = $this
        ->entityTypeManager()
        ->getStorage('oauth2_server_scope')
        ->loadByProperties([
        'server_id' => $client
          ->getServer()
          ->id(),
        'scope_id' => $scope_names,
      ]);

      // Show the authorize form.
      return $this
        ->formBuilder()
        ->getForm('Drupal\\oauth2_server\\Form\\AuthorizeForm', [
        'client' => $client,
        'scopes' => $scopes,
      ]);
    }
  }

  /**
   * Token.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match object.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return \OAuth2\HttpFoundationBridge\Response|\Symfony\Component\HttpFoundation\JsonResponse
   *   A response object.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function token(RouteMatchInterface $route_match, Request $request) {
    $bridgeRequest = BridgeRequest::createFromRequest($request);
    $client_credentials = Utility::getClientCredentials($bridgeRequest);

    // Get the client and use it to load the server and initialize the server.
    $client = FALSE;
    if ($client_credentials) {

      /** @var \Drupal\oauth2_server\ClientInterface[] $clients */
      $clients = $this
        ->entityTypeManager()
        ->getStorage('oauth2_server_client')
        ->loadByProperties([
        'client_id' => $client_credentials['client_id'],
      ]);
      if ($clients) {
        $client = reset($clients);
      }
    }
    if (!$client) {
      return new JsonResponse([
        'error' => 'Client could not be found.',
      ], JsonResponse::HTTP_NOT_FOUND);
    }
    $response = new BridgeResponse();
    $oauth2_server = Utility::startServer($client
      ->getServer(), $this->storage);
    $oauth2_server
      ->handleTokenRequest($bridgeRequest, $response);
    return $response;
  }

  /**
   * Tokens.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match object.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return \OAuth2\HttpFoundationBridge\Response|\Symfony\Component\HttpFoundation\JsonResponse
   *   The response object.
   */
  public function tokens(RouteMatchInterface $route_match, Request $request) {
    $token = $route_match
      ->getRawParameter('oauth2_server_token');
    $token = $this->storage
      ->getAccessToken($token);

    // No token found. Stop here.
    if (!$token || $token['expires'] <= time()) {
      return new BridgeResponse([], 404);
    }

    // Return the token, without the server and client_id keys.
    unset($token['server']);
    return new JsonResponse($token);
  }

  /**
   * User info.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match object.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return \OAuth2\HttpFoundationBridge\Response
   *   The response object.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function userInfo(RouteMatchInterface $route_match, Request $request) {
    $bridgeRequest = BridgeRequest::createFromRequest($request);
    $client_credentials = Utility::getClientCredentials($bridgeRequest);

    // Get the client and use it to load the server and initialize the server.
    $client = FALSE;
    if ($client_credentials) {

      /** @var \Drupal\oauth2_server\ClientInterface[] $clients */
      $clients = $this
        ->entityTypeManager()
        ->getStorage('oauth2_server_client')
        ->loadByProperties([
        'client_id' => $client_credentials['client_id'],
      ]);
      if ($clients) {
        $client = reset($clients);
      }
    }
    $server = NULL;
    if ($client) {
      $server = $client
        ->getServer();
    }
    $response = new BridgeResponse();
    $oauth2_server = Utility::startServer($server, $this->storage);
    $oauth2_server
      ->handleUserInfoRequest($bridgeRequest, $response);
    return $response;
  }

  /**
   * Certificates.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match object.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The response object.
   */
  public function certificates(RouteMatchInterface $route_match, Request $request) {
    $keys = Utility::getKeys();
    $certificates = [];
    $certificates[] = $keys['public_key'];
    return new JsonResponse($certificates);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage 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. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
OAuth2Controller::$storage protected property The OAuth2Storage.
OAuth2Controller::authorize public function Authorize.
OAuth2Controller::certificates public function Certificates.
OAuth2Controller::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
OAuth2Controller::token public function Token.
OAuth2Controller::tokens public function Tokens.
OAuth2Controller::userInfo public function User info.
OAuth2Controller::__construct public function Constructs a new \Drupal\oauth2_server\Controller\OAuth2Controller object.
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.