You are here

class OauthController in Media: Acquia DAM 8

Controller routines for acquiadam routes.

Hierarchy

Expanded class hierarchy of OauthController

File

src/Controller/OauthController.php, line 23

Namespace

Drupal\media_acquiadam\Controller
View source
class OauthController extends ControllerBase {

  /**
   * The base API url.
   *
   * @var string
   */
  protected $webdamApiBase = "https://apiv2.webdamdb.com";

  /**
   * The media_acquiadam oauth service.
   *
   * @var \Drupal\media_acquiadam\Oauth
   */
  protected $oauth;

  /**
   * The current request object.
   *
   * @var null|\Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * UserData interface to handle storage of tokens.
   *
   * @var \Drupal\user\UserDataInterface
   */
  protected $userData;

  /**
   * Drupal Date Formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * Drupal Url Generator service.
   *
   * @var \Drupal\Core\Routing\UrlGeneratorInterface
   */
  protected $urlGenerator;

  /**
   * AcquiadamController constructor.
   *
   * {@inheritdoc}
   */
  public function __construct(OauthInterface $oauth, RequestStack $request_stack, UserDataInterface $user_data, AccountProxyInterface $currentUser, DateFormatterInterface $dateFormatter, UrlGeneratorInterface $urlGenerator) {
    $this->oauth = $oauth;
    $this->request = $request_stack
      ->getCurrentRequest();
    $this->userData = $user_data;
    $this->currentUser = $currentUser;
    $this->dateFormatter = $dateFormatter;
    $this->urlGenerator = $urlGenerator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('media_acquiadam.oauth'), $container
      ->get('request_stack'), $container
      ->get('user.data'), $container
      ->get('current_user'), $container
      ->get('date.formatter'), $container
      ->get('url_generator'));
  }

  /**
   * Builds the auth page for a given user.
   *
   * Route: /user/{$user}/acquiadam.
   *
   * @param \Drupal\user\UserInterface $user
   *   The User object.
   *
   * @return array
   *   Array with HTML markup message.
   */
  public function authPage(UserInterface $user) {

    // Users cannot access other users' auth forms.
    if ($user
      ->id() !== $this
      ->currentUser()
      ->id()) {
      throw new NotFoundHttpException();
    }
    $result = [];

    /** @var \Drupal\Core\Config\Config $media_acquiadam_settings */
    $media_acquiadam_settings = $this
      ->config('media_acquiadam.settings');
    $redirect_url = sprintf('/user/%d/acquiadam', $this
      ->currentUser()
      ->id());
    $access_token = $this->userData
      ->get('media_acquiadam', $this->currentUser
      ->id(), 'acquiadam_access_token');
    $refresh_token = $this->userData
      ->get('media_acquiadam', $this->currentUser
      ->id(), 'acquiadam_refresh_token');
    $access_token_expiration = $this->userData
      ->get('media_acquiadam', $this->currentUser
      ->id(), 'acquiadam_access_token_expiration');
    $is_expired = empty($access_token) || $access_token_expiration <= time();
    $is_authenticated = !$is_expired || $is_expired && !empty($refresh_token);
    $is_no_credentials = !$media_acquiadam_settings
      ->get('secret') || !$media_acquiadam_settings
      ->get('client_id');
    if ($is_no_credentials) {
      $result[] = [
        '#markup' => '<p>' . $this
          ->t('The Acquia DAM module is not fully configured.') . '</p>',
      ];
      if ($this
        ->currentUser()
        ->hasPermission('administer site configuration')) {
        $config_url = $this->urlGenerator
          ->generateFromRoute('media_acquiadam.config', [], [
          'query' => [
            'destination' => $redirect_url,
          ],
        ]);
        $result[] = [
          '#markup' => '<p>' . $this
            ->t('Please <a href="@configure">configure</a> the Acquia DAM module to continue.', [
            '@configure' => $config_url,
          ]) . '</p>',
        ];
      }
      else {
        $result[] = [
          '#markup' => '<p>' . $this
            ->t('Please contact a site administrator to continue.') . '</p>',
        ];
      }
    }
    elseif ($is_expired) {
      $this->userData
        ->delete('media_acquiadam', $this->currentUser
        ->id(), 'acquiadam_access_token');
      $this->userData
        ->delete('media_acquiadam', $this->currentUser
        ->id(), 'acquiadam_access_token_expiration');
      $this->userData
        ->delete('media_acquiadam', $this->currentUser
        ->id(), 'acquiadam_refresh_token');
      $link = Link::createFromRoute('Authenticate', 'media_acquiadam.auth_start', [
        'auth_finish_redirect' => $redirect_url,
      ]);
      $result[] = [
        '#markup' => '<p>' . $this
          ->t('You are <strong>not</strong> authenticated with Acquia DAM.') . '</p>',
      ];
      $result[] = [
        '#markup' => '<p>' . $link
          ->toString() . '</p>',
      ];
    }
    elseif ($is_authenticated) {
      $logout_link = Link::createFromRoute('Logout from DAM', 'media_acquiadam.logout', [
        'auth_finish_redirect' => $redirect_url,
      ]);
      $reauthenticate_link = Link::createFromRoute('Reauthenticate', 'media_acquiadam.auth_start', [
        'auth_finish_redirect' => $redirect_url,
      ]);
      $result[] = [
        '#markup' => '<p>' . $this
          ->t('You are authenticated with Acquia DAM.') . '</p>',
      ];
      $result[] = [
        '#markup' => '<p>' . $this
          ->t('Your authentication expires on @date.', [
          '@date' => $this->dateFormatter
            ->format($access_token_expiration),
        ]) . '</p>',
      ];
      $result[] = [
        '#markup' => '<p>' . $reauthenticate_link
          ->toString() . ' | ' . $logout_link
          ->toString() . '</p>',
      ];
    }
    return !empty($result) ? $result : NULL;
  }

  /**
   * Redirects the user to the auth url.
   *
   * Route: /acquiadam/authStart.
   */
  public function authStart() {
    $authFinishRedirect = $this->request->query
      ->get('auth_finish_redirect');
    $this->oauth
      ->setAuthFinishRedirect($authFinishRedirect);
    return new TrustedRedirectResponse($this->oauth
      ->getAuthLink());
  }

  /**
   * Redirects the user to the auth url.
   *
   * Route: /acquiadam/logout.
   */
  public function logout() {
    $this->userData
      ->delete('media_acquiadam', $this->currentUser
      ->id(), 'acquiadam_access_token');
    $this->userData
      ->delete('media_acquiadam', $this->currentUser
      ->id(), 'acquiadam_access_token_expiration');
    $this->userData
      ->delete('media_acquiadam', $this->currentUser
      ->id(), 'acquiadam_refresh_token');
    $authFinishRedirect = $this->request->query
      ->get('auth_finish_redirect');
    return new TrustedRedirectResponse($authFinishRedirect);
  }

  /**
   * Finish the authentication process.
   *
   * Route: /acquiadam/authFinish.
   */
  public function authFinish() {
    $authFinishRedirect = $this->request->query
      ->get('auth_finish_redirect');
    if ($original_path = $this->request->query
      ->get('original_path', FALSE)) {
      $authFinishRedirect .= '&original_path=' . $original_path;
    }
    $this->oauth
      ->setAuthFinishRedirect($authFinishRedirect);
    if (!$this->oauth
      ->authRequestStateIsValid($this->request
      ->get('state'))) {
      throw new AccessDeniedHttpException();
    }
    $access_token = $this->oauth
      ->getAccessToken($this->request
      ->get('code'));
    $this->userData
      ->set('media_acquiadam', $this->currentUser
      ->id(), 'acquiadam_access_token', $access_token['access_token']);
    $this->userData
      ->set('media_acquiadam', $this->currentUser
      ->id(), 'acquiadam_access_token_expiration', $access_token['expire_time']);
    $this->userData
      ->set('media_acquiadam', $this->currentUser
      ->id(), 'acquiadam_refresh_token', $access_token['refresh_token']);
    return new RedirectResponse($authFinishRedirect);
  }

}

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::$entityManager protected property The entity manager.
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::entityManager Deprecated protected function Retrieves the entity manager service.
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. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
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.
OauthController::$dateFormatter protected property Drupal Date Formatter service.
OauthController::$oauth protected property The media_acquiadam oauth service.
OauthController::$request protected property The current request object.
OauthController::$urlGenerator protected property Drupal Url Generator service. Overrides UrlGeneratorTrait::$urlGenerator
OauthController::$userData protected property UserData interface to handle storage of tokens.
OauthController::$webdamApiBase protected property The base API url.
OauthController::authFinish public function Finish the authentication process.
OauthController::authPage public function Builds the auth page for a given user.
OauthController::authStart public function Redirects the user to the auth url.
OauthController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
OauthController::logout public function Redirects the user to the auth url.
OauthController::__construct public function AcquiadamController 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::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.