You are here

class MainDeprecatedController in Bakery Single Sign-On System 8.2

Hierarchy

Expanded class hierarchy of MainDeprecatedController

File

src/Controller/MainDeprecatedController.php, line 20

Namespace

Drupal\bakery\Controller
View source
class MainDeprecatedController extends ControllerBase {

  /**
   * @var \Drupal\bakery\BakeryService
   */
  protected $bakeryService;

  /**
   * @var \Drupal\bakery\Kitchen
   */
  protected $kitchen;

  /**
   * Initialize bakery service.
   *
   * @param \Drupal\bakery\BakeryService $bakery_service
   *   For bakery service.
   * @param \Drupal\bakery\Kitchen $kitchen
   *   For bakery service.
   */
  public function __construct(BakeryService $bakery_service, Kitchen $kitchen) {
    $this->bakeryService = $bakery_service;
    $this->kitchen = $kitchen;
  }

  /**
   * When this controller is created, it will get the bakery.bakery_service.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   For getting Bakery service.
   *
   * @return static
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('bakery.bakery_service'), $container
      ->get('bakery.kitchen'));
  }

  /**
   * Special Bakery register callback registers the user and returns to child.
   */
  public function register() {
    $cookie = $this->kitchen
      ->taste(Kitchen::OATMEAL);
    if ($cookie) {

      // Valid cookie.
      // Destroy the current oatmeal cookie,
      // we'll set a new one when we return to the slave.
      $this->kitchen
        ->eat(Kitchen::OATMEAL);

      // Users are allowed to register.
      if ($this
        ->config('user.settings')
        ->get('register') != UserInterface::REGISTER_ADMINISTRATORS_ONLY) {
        $name = trim($cookie['data']['name']);
        $mail = trim($cookie['data']['mail']);
        $data = [
          'name' => $name,
        ];

        // Save errors.
        $errors = [];

        // Check if user exists with same email.
        if (user_load_by_mail($mail)) {
          $errors['mail'] = 1;
        }
        elseif (user_load_by_name($name)) {
          $errors['name'] = 1;
        }
        else {

          // Create user.
          if (!$cookie['data']['pass']) {
            $pass = user_password();
          }
          else {
            $pass = $cookie['data']['pass'];
          }
          $language = $this
            ->languageManager()
            ->getCurrentLanguage()
            ->getId();
          $account = User::create();

          // Mandatory settings.
          $account
            ->setPassword($pass);
          $account
            ->enforceIsNew();
          $account
            ->setEmail($mail);

          // This username must be unique and accept only a-Z,0-9, - _ @ .
          $account
            ->setUsername($name);

          // Optional settings.
          $account
            ->set("init", $mail);
          $account
            ->set("langcode", $language);
          $account
            ->set("preferred_langcode", $language);
          $account
            ->set("preferred_admin_langcode", $language);

          // $user->set("setting_name", 'setting_value');.
          $account
            ->activate();

          // Save user.
          $account
            ->save();

          // Set some info to return to the slave.
          $data['uid'] = $account
            ->id();
          $data['mail'] = $mail;
          $this
            ->getLogger('bakery')
            ->notice('New external user: %name using module bakery from slave !slave.', [
            '%name' => $account
              ->getAccountName(),
            '!slave' => $cookie['slave'],
          ]);

          // Redirect to slave.
          if (!$this
            ->config('user.settings')
            ->get('verify_mail')) {

            // Create identification cookie and log user in.
            $this->kitchen
              ->reBakeChocolateChipCookie($account);
            $this->bakeryService
              ->userExternalLogin($account);
          }
          else {

            // The user needs to validate their email, redirect back to slave to
            // inform them.
            $errors['validate'] = 1;
          }
        }
      }
      else {
        $this
          ->getLogger('bakery')
          ->error('Master Bakery site user registration is disabled but users are trying to register from a subsite.');
        $errors['register'] = 1;
      }
      if (!empty($errors)) {

        // There were errors.
        session_destroy();
      }

      // Redirect back to custom Bakery callback on slave.
      $data['errors'] = $errors;

      // Carry destination through return.
      if (isset($cookie['data']['destination'])) {
        $data['destination'] = $cookie['data']['destination'];
      }

      // Bake a new cookie for validation on the slave.
      $this->kitchen
        ->bake(new OatmealCookie($name, $data));
      return new TrustedRedirectResponse(Url::fromUri(rtrim($cookie['slave'], '/') . '/bakery')
        ->toString());
    }

    // Invalid request.
    throw new AccessDeniedHttpException();
  }

  /**
   * Special Bakery login callback authenticates the user and returns to slave.
   */
  public function login(Request $request) {
    $cookie = $this->kitchen
      ->taste(Kitchen::OATMEAL, $request->cookies);
    if ($cookie) {

      // Remove the data pass cookie.
      $this->kitchen
        ->eat(Kitchen::OATMEAL);
      $current_user = $this
        ->currentUser();
      if ($current_user
        ->id()) {
        if ($current_user
          ->getAccountName() != $cookie['data']['name']) {

          // Trying to log in as another user. That seems likely to cause
          // problems. Let's just bail.
          throw new AccessDeniedHttpException();
        }

        // This user is already logged in. Let's make sure the CC is correct and
        // redirect them back.
        $this->kitchen
          ->reBakeChocolateChipCookie($current_user);
        $data = [
          'errors' => [],
          'name' => $current_user
            ->getAccountName(),
        ];
      }
      else {

        // First see if the user_login form validation has any errors for them.
        $name = trim($cookie['data']['name']);

        // Execute the login form which checks
        // username, password, status and flood.
        $form_state = new FormState();
        $form_state
          ->setValues($cookie['data']);
        $form_builder = $this
          ->formBuilder();
        $form_builder
          ->submitForm(UserLoginForm::class, $form_state);
        $errors = $form_state
          ->getErrors();
        if (empty($errors)) {

          // Check if account credentials are correct.

          /** @var \Drupal\user\UserInterface|false $account */
          $account = user_load_by_name($name);
          if ($account && $account
            ->id()) {

            // Check if the mail is denied.
            if ($account
              ->isBlocked()) {
              $errors['name'] = t('The name %name is registered using a reserved e-mail address and therefore could not be logged in.', [
                '%name' => $name,
              ]);
            }
            else {

              // Passed all checks, create identification cookie and log in.
              $this->kitchen
                ->reBakeChocolateChipCookie($account);
              $this->bakeryService
                ->userExternalLogin($account);
            }
          }
          else {
            $errors['incorrect-credentials'] = 1;
          }
        }
        if (!empty($errors)) {

          // Report failed login.
          $this
            ->getLogger('user')
            ->notice('Login attempt failed for %user.', [
            '%user' => $name,
          ]);

          // Clear the messages on the master's session,
          // since they were set during
          // drupal_form_submit() and will be displayed out of context.
          $this
            ->messenger()
            ->deleteAll();
        }

        // Bake a new cookie for validation on the slave.
        $data = [
          'errors' => $errors,
          'name' => $name,
        ];
      }

      // Carry destination through login.
      if (isset($cookie['data']['destination'])) {
        $data['destination'] = $cookie['data']['destination'];
      }
      $this->kitchen
        ->bake(new OatmealCookie($name, $data));
      return new TrustedRedirectResponse(Url::fromUri(rtrim($cookie['slave'], '/') . '/bakery/login')
        ->toString());
    }
    throw new AccessDeniedHttpException();
  }

  /**
   * User is anonymous or not .
   */
  public function userIsAnonymous() {
    if ($this
      ->currentUser()
      ->isAnonymous()) {
      return AccessResult::allowed();
    }
    else {
      return AccessResult::forbidden();
    }
  }

}

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.
MainDeprecatedController::$bakeryService protected property
MainDeprecatedController::$kitchen protected property
MainDeprecatedController::create public static function When this controller is created, it will get the bakery.bakery_service. Overrides ControllerBase::create
MainDeprecatedController::login public function Special Bakery login callback authenticates the user and returns to slave.
MainDeprecatedController::register public function Special Bakery register callback registers the user and returns to child.
MainDeprecatedController::userIsAnonymous public function User is anonymous or not .
MainDeprecatedController::__construct public function Initialize bakery service.
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.