You are here

class AuthenticationController in Janrain Registration 8

Authentication controller.

Hierarchy

Expanded class hierarchy of AuthenticationController

File

src/Controller/AuthenticationController.php, line 21

Namespace

Drupal\janrain_capture\Controller
View source
class AuthenticationController extends ControllerBase {

  /**
   * An instance of the "janrain_capture.capture_api" service.
   *
   * @var \Drupal\janrain_capture\JanrainCaptureApi
   */
  protected $captureApi;

  /**
   * An instance of the "janrain_capture.markup_builder" service.
   *
   * @var \Drupal\janrain_capture\JanrainMarkupBuilder
   */
  protected $markupBuilder;

  /**
   * {@inheritdoc}
   */
  public function __construct(JanrainCaptureApi $capture_api, JanrainMarkupBuilder $markup_builder) {
    $this->captureApi = $capture_api;
    $this->markupBuilder = $markup_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) : self {
    return new static($container
      ->get('janrain_capture.capture_api'), $container
      ->get('janrain_capture.markup_builder'));
  }

  /**
   * Restore password form.
   */
  public function forgot() {
    return $this->markupBuilder
      ->getScreenRenderArray('forgot');
  }

  /**
   * Edit profile page.
   */
  public function editProfile() {
    $access_token = $this->captureApi
      ->getAccessToken();
    $return = $this->markupBuilder
      ->getScreenRenderArray('edit-profile');
    $return['janrain_capture_edit_js'] = [
      '#markup' => '<script>var access_token = "' . $access_token . '";</script>',
      '#allowed_tags' => [
        'script',
      ],
      '#cache' => [
        'contexts' => [
          'user',
        ],
        'max-age' => 60,
      ],
    ];
    return $return;
  }

  /**
   * View profile page.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The incoming HTTP request.
   */
  public function viewProfile(Request $request) {
    if (!$request->query
      ->get('uuid')) {
      $user = User::load(\Drupal::currentUser()
        ->id());
      $uuid = $user
        ->uuid();
      return new RedirectResponse(Url::fromRoute('janrain_capture.view_profile', [
        'uuid' => $uuid,
      ])
        ->toString(), RedirectResponse::HTTP_MOVED_PERMANENTLY);
    }

    // Get current user's UUID and compare it against UUID from the parameter.
    $current_janrain_uuid = $this->captureApi
      ->getUserProfile()
      ->getUuid();
    if ($current_janrain_uuid == $_GET['uuid']) {
      return $this->markupBuilder
        ->getScreenRenderArray('public-profile');
    }
    else {
      throw new \InvalidArgumentException('An invalid uuid is given.');
    }
  }

  /**
   * Logout user from the system.
   */
  public function logout() {
    user_logout();
    return new RedirectResponse(Url::fromRoute('<front>', [], [
      'absolute' => TRUE,
    ])
      ->toString(), RedirectResponse::HTTP_MOVED_PERMANENTLY);
  }

  /**
   * Login or reset a password for a user using Janrain API.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The incoming HTTP request.
   *
   * @return string
   *   The URI to redirect the user to or the forgot password link usually
   *   used in email.
   */
  public function login(Request $request) {

    // Usually, this controller should return a URI to redirect a user to.
    // This is valid for authentication. When the password reset requested
    // a user will receive an email with the link and, opening it in a
    // browser, this controller must show the real HTML page instead of
    // just a URI.
    $response_class = Response::class;
    $one_time_login_link = FALSE;
    if ($request->query
      ->get('url_type') === 'forgot') {
      return $this
        ->forgot();
    }
    $destination_url = $this
      ->getDestinationUrl($request)
      ->setAbsolute()
      ->toString();
    try {

      // The authentication can throw exceptions so their messages
      // will be exposed on the frontend.
      $this->captureApi
        ->authenticate($this
        ->getAuthorizationCode($request), $request
        ->getUri());
      if ($one_time_login_link) {
        $this
          ->messenger()
          ->addStatus('You have been successfully logged in via one-time login link.');
      }
      $module_handler = \Drupal::moduleHandler();
      $module_handler
        ->alter('janrain_capture_auth_destination', $destination_url, $this->captureApi
        ->getUserProfile(), $this->captureApi
        ->getCurrentUser());
    } catch (\Throwable $e) {
      $this
        ->messenger()
        ->addError($e
        ->getMessage());
    }
    return new $response_class($destination_url);
  }

  /**
   * Returns the authorization code.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return string
   *   The OAuth authorization code.
   */
  protected function getAuthorizationCode(Request $request) : string {

    // If the request has no "code" it means it's malformed.
    if (!$request->query
      ->has('code')) {
      throw new BadRequestHttpException($this
        ->t('Malformed request. Authorization code is missing.'));
    }
    $code = $request->query
      ->get('code');

    // The code must be read first and then removed from the request. This
    // is required for an operation, for instance, for resetting the password.
    // The link that user will get via email will look the following:
    // https://a.com/janrain_capture/oauth?url_type=forgot&code=8uy9j8quyj3tam
    // The Janrain will expect "redirect_uri" without the "code":
    // https://a.com/janrain_capture/oauth?url_type=forgot
    // If the domain will differ, OAuth will throw the "redirect_uri does not
    // match expected value" error.
    $request->query
      ->remove('code');

    // Override global variables to ensure the "code" is no longer presented.
    $request
      ->overrideGlobals();

    // Return ejected value.
    return $code;
  }

  /**
   * Returns the URL to redirect to.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return \Drupal\Core\Url
   *   The URL to redirect to.
   */
  protected function getDestinationUrl(Request $request) : Url {

    // See whether the request has HTTP referer.
    if ($request->server
      ->has('HTTP_REFERER')) {
      $request_uri = new Uri($request
        ->getUri());
      $referer_uri = new Uri($request->server
        ->get('HTTP_REFERER'));

      // Make sure we'll not redirect out of the current origin.
      if ($referer_uri
        ->getAuthority() === $request_uri
        ->getAuthority()) {
        return Url::fromUserInput($referer_uri
          ->getPath(), [
          'query' => parse_query($referer_uri
            ->getQuery()),
        ]);
      }
    }

    // Fallback to the front page.
    return Url::fromRoute('<front>');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AuthenticationController::$captureApi protected property An instance of the "janrain_capture.capture_api" service.
AuthenticationController::$markupBuilder protected property An instance of the "janrain_capture.markup_builder" service.
AuthenticationController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
AuthenticationController::editProfile public function Edit profile page.
AuthenticationController::forgot public function Restore password form.
AuthenticationController::getAuthorizationCode protected function Returns the authorization code.
AuthenticationController::getDestinationUrl protected function Returns the URL to redirect to.
AuthenticationController::login public function Login or reset a password for a user using Janrain API.
AuthenticationController::logout public function Logout user from the system.
AuthenticationController::viewProfile public function View profile page.
AuthenticationController::__construct public function
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.
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.