You are here

class SimplesamlphpAuthController in simpleSAMLphp Authentication 8.3

Controller routines for simplesamlphp_auth routes.

Hierarchy

Expanded class hierarchy of SimplesamlphpAuthController

File

src/Controller/SimplesamlphpAuthController.php, line 22

Namespace

Drupal\simplesamlphp_auth\Controller
View source
class SimplesamlphpAuthController extends ControllerBase implements ContainerInjectionInterface {

  /**
   * The SimpleSAML Authentication helper service.
   *
   * @var \Drupal\simplesamlphp_auth\Service\SimplesamlphpAuthManager
   */
  public $simplesaml;

  /**
   * The SimpleSAML Drupal Authentication service.
   *
   * @var \Drupal\simplesamlphp_auth\Service\SimplesamlphpDrupalAuth
   */
  public $simplesamlDrupalauth;

  /**
   * The url generator service.
   *
   * @var \Drupal\Core\Routing\UrlGeneratorInterface
   */
  protected $urlGenerator;

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  public $requestStack;

  /**
   * The current account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $account;

  /**
   * The path validator.
   *
   * @var \Drupal\Core\Path\PathValidatorInterface
   */
  protected $pathValidator;

  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * A configuration object.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * {@inheritdoc}
   *
   * @param \Drupal\simplesamlphp_auth\Service\SimplesamlphpAuthManager $simplesaml
   *   The SimpleSAML Authentication helper service.
   * @param \Drupal\simplesamlphp_auth\Service\SimplesamlphpDrupalAuth $simplesaml_drupalauth
   *   The SimpleSAML Drupal Authentication service.
   * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
   *   The url generator service.
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The request stack.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current account.
   * @param \Drupal\Core\Path\PathValidatorInterface $path_validator
   *   The path validator.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory.
   */
  public function __construct(SimplesamlphpAuthManager $simplesaml, SimplesamlphpDrupalAuth $simplesaml_drupalauth, UrlGeneratorInterface $url_generator, RequestStack $request_stack, AccountInterface $account, PathValidatorInterface $path_validator, LoggerInterface $logger, ConfigFactoryInterface $config_factory) {
    $this->simplesaml = $simplesaml;
    $this->simplesamlDrupalauth = $simplesaml_drupalauth;
    $this->urlGenerator = $url_generator;
    $this->requestStack = $request_stack;
    $this->account = $account;
    $this->pathValidator = $path_validator;
    $this->logger = $logger;
    $this->config = $config_factory
      ->get('simplesamlphp_auth.settings');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('simplesamlphp_auth.manager'), $container
      ->get('simplesamlphp_auth.drupalauth'), $container
      ->get('url_generator'), $container
      ->get('request_stack'), $container
      ->get('current_user'), $container
      ->get('path.validator'), $container
      ->get('logger.factory')
      ->get('simplesamlphp_auth'), $container
      ->get('config.factory'));
  }

  /**
   * Logs the user in via SimpleSAML federation.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to either a designated page or the user login page.
   */
  public function authenticate() {
    global $base_url;

    // Ensure the module has been turned on before continuing with the request.
    if (!$this->simplesaml
      ->isActivated()) {
      return $this
        ->redirect('user.login');
    }

    // Ensure phpsession isn't the session storage location.
    if ($this->simplesaml
      ->getStorage() === 'phpsession') {
      return $this
        ->redirect('user.login');
    }

    // See if a URL has been explicitly provided in ReturnTo. If so, use it
    // otherwise, use the HTTP_REFERER. Each must point to the site to be valid.
    $request = $this->requestStack
      ->getCurrentRequest();
    if (($return_to = $request->query
      ->get('ReturnTo')) || ($return_to = $request->request
      ->get('ReturnTo')) || ($return_to = $request->server
      ->get('HTTP_REFERER'))) {
      if ($this->pathValidator
        ->isValid($return_to) && UrlHelper::externalIsLocal($return_to, $base_url)) {
        $redirect = $return_to;
      }
    }

    // The user is not logged into Drupal.
    if ($this->account
      ->isAnonymous()) {
      if (isset($redirect)) {

        // Set the cookie so we can deliver the user to the place they started.
        // @TODO probably a more symfony way of doing this
        $cookie_secure = $this->config
          ->get('secure');
        $cookie_httponly = $this->config
          ->get('httponly');
        setrawcookie('simplesamlphp_auth_returnto', $redirect, time() + 60 * 60, "", "", $cookie_secure, $cookie_httponly);
      }

      // User is logged in to the SimpleSAMLphp IdP, but not to Drupal.
      if ($this->simplesaml
        ->isAuthenticated()) {
        if (!$this->simplesaml
          ->allowUserByAttribute()) {
          return [
            '#markup' => $this
              ->t('You are not allowed to login via this service.'),
          ];
        }

        // Get unique identifier from saml attributes.
        $authname = $this->simplesaml
          ->getAuthname();
        if (!empty($authname)) {
          if ($this->config
            ->get('debug')) {
            $this->logger
              ->debug('Trying to login SAML-authenticated user with authname %authname', [
              '%authname' => $authname,
            ]);
          }

          // User is logged in with SAML authentication and we got the unique
          // identifier, so try to log into Drupal.
          // Check to see whether the external user exists in Drupal. If they
          // do not exist, create them.
          // Also log in the user.
          $this->simplesamlDrupalauth
            ->externalLoginRegister($authname);
        }
      }
      if (\Drupal::config('simplesamlphp_auth.settings')
        ->get('header_no_cache')) {
        header('Cache-Control: no-cache');
      }
      $this->simplesaml
        ->externalAuthenticate();
    }

    // Check to see if we've set a cookie. If there is one, give it priority.
    if ($request->cookies
      ->has('simplesamlphp_auth_returnto')) {
      $redirect = $request->cookies
        ->get('simplesamlphp_auth_returnto');

      // Unset the cookie.
      setrawcookie('simplesamlphp_auth_returnto', '');
    }
    if (isset($redirect)) {

      // Avoid caching of redirect response object.
      \Drupal::service('page_cache_kill_switch')
        ->trigger();
      if ($this->config
        ->get('debug')) {
        $this->logger
          ->debug('Redirecting user to %redirect', [
          '%redirect' => $redirect,
        ]);
      }
      $response = new RedirectResponse($redirect, RedirectResponse::HTTP_FOUND);
      return $response;
    }
    return $this
      ->redirect('user.login');
  }

}

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.
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.
SimplesamlphpAuthController::$account protected property The current account.
SimplesamlphpAuthController::$config protected property A configuration object.
SimplesamlphpAuthController::$logger protected property A logger instance.
SimplesamlphpAuthController::$pathValidator protected property The path validator.
SimplesamlphpAuthController::$requestStack public property The request stack.
SimplesamlphpAuthController::$simplesaml public property The SimpleSAML Authentication helper service.
SimplesamlphpAuthController::$simplesamlDrupalauth public property The SimpleSAML Drupal Authentication service.
SimplesamlphpAuthController::$urlGenerator protected property The url generator service. Overrides UrlGeneratorTrait::$urlGenerator
SimplesamlphpAuthController::authenticate public function Logs the user in via SimpleSAML federation.
SimplesamlphpAuthController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
SimplesamlphpAuthController::__construct public function
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.