You are here

class BakeryService in Bakery Single Sign-On System 8.2

Common functionalities used in both controller and module.

Hierarchy

Expanded class hierarchy of BakeryService

7 files declare their use of BakeryService
BakeryPullForm.php in src/Forms/BakeryPullForm.php
BootSubscriber.php in src/EventSubscriber/BootSubscriber.php
For Boot event subscribe.
BrowserCookieTrait.php in src/Cookies/BrowserCookieTrait.php
BrowserCookieTraitTest.php in tests/src/Unit/Cookies/BrowserCookieTraitTest.php
ChildController.php in src/Controller/ChildController.php

... See full list

1 string reference to 'BakeryService'
bakery.services.yml in ./bakery.services.yml
bakery.services.yml
1 service uses BakeryService
bakery.bakery_service in ./bakery.services.yml
Drupal\bakery\BakeryService

File

src/BakeryService.php, line 20
Services used in bakery SSO functions.

Namespace

Drupal\bakery
View source
class BakeryService {
  protected $config;

  /**
   * If the current site is configured as the main site or a child.
   *
   * @var bool
   */
  protected $isMain;

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

  /**
   * When the service is created, set a value for the example variable.
   */
  public function __construct(ConfigFactoryInterface $configFactory, Kitchen $kitchen) {
    $this->config = $configFactory
      ->get('bakery.settings');
    $this->kitchen = $kitchen;
  }

  /**
   * Check if the current site is the main site.
   *
   * @return bool
   */
  public function isMain() {
    if (!isset($this->isMain)) {
      $this->isMain = $this->config
        ->get('bakery_is_master');
    }
    return $this->isMain;
  }

  /**
   * Check if the current site is a child site.
   *
   * @return bool
   */
  public function isChild() {
    return !$this
      ->isMain();
  }

  /**
   * Perform standard Drupal login operations for a user object.
   *
   * The user object must already be authenticated. This function verifies
   * that the user account is not blocked/denied and then performs the login,
   * updates the login timestamp in the database, invokes hook_user('login'),
   * and regenerates the session.
   *
   * @param \Drupal\user\UserInterface $account
   *   An authenticated user object to be set as the currently logged in user.
   *
   * @return bool
   *   TRUE if the login succeeds, FALSE otherwise.
   */
  public function userExternalLogin(UserInterface $account) {
    if (user_is_blocked($account
      ->getAccountName())) {

      // Invalid login.
      return FALSE;
    }

    // Valid login.
    user_login_finalize($account);
    return TRUE;
  }

  /**
   * Request account information from master to create account locally.
   *
   * @param string $name
   *   The username or e-mail to request information for to create.
   * @param bool $or_email
   *   Load account by name or email. Useful for getting
   *   account data from a password request where you get name or email.
   *
   * @return int|false
   *   The newly created local UID or FALSE.
   */
  public function requestAccount($name, $or_email = FALSE) {
    global $base_url;
    $existing_account = user_load_by_name($name);
    if (!$existing_account && $or_email) {
      $existing_account = user_load_by_mail($name);
    }

    // We return FALSE in cases that the account already exists locally or if
    // there was an error along the way of requesting and creating it.
    if ($existing_account) {
      return FALSE;
    }

    // Save a stub account so we have a slave UID to send.
    $language = \Drupal::languageManager()
      ->getCurrentLanguage()
      ->getId();
    $account = User::create([
      'name' => $name,
      // 'mail' => 'email',
      'pass' => user_password(),
      // This username must be unique and accept only a-Z,0-9, - _ @ .
      'init' => 'bakery_temp/' . mt_rand(),
      'langcode',
      $language,
      'preferred_langcode',
      $language,
      'preferred_admin_langcode',
      $language,
      'status' => 1,
    ]);

    // Save user.
    try {
      $account
        ->enforceIsNew();
      $account
        ->save();
    } catch (EntityStorageException $e) {
      \Drupal::logger('bakery')
        ->error('Unable to create stub account for @name', [
        '@name' => $name,
      ]);
      return FALSE;
    }
    $response = $this->kitchen
      ->ship(new Gingerbread($name, $or_email, rtrim($base_url, '/') . '/', $account
      ->id()));
    if ($response && $response
      ->getStatusCode() == 200) {

      // Parse result and create account.
      $cookie = $this->kitchen
        ->tasteData($response
        ->getBody());
      if ($cookie === FALSE) {

        // Invalid response.
        \Drupal::logger('bakery')
          ->error('Invalid response from master when attempting to create local account for @name', [
          '@name' => $name,
        ]);
        $account
          ->delete();
        return FALSE;
      }

      // Create account.
      $account
        ->set('init', $cookie['uid']);
      $this
        ->updateUserFields($account, $cookie);

      // Save user.
      if ($account
        ->save()) {
        \Drupal::logger('bakery')
          ->notice('Created account for @name', [
          '@name' => $name,
        ]);
        return $account
          ->id();
      }
    }
    if ($response) {
      $message = $response
        ->getBody();
      \Drupal::logger('bakery')
        ->error('Received response !code from master with message @message', [
        '!code' => $response
          ->getStatusCode(),
        '@message' => (string) $message,
      ]);
    }
    else {
      \Drupal::logger('bakery')
        ->error('Unable to create account for @name', [
        '@name' => $name,
      ]);
    }
    $account
      ->delete();
    return FALSE;
  }

  /**
   * Update a user account with fields from a cookie.
   *
   * @param \Drupal\user\UserInterface $account
   *   The user account being updated.
   * @param array $cookie
   *   Cookie data. From either stroopwafel or gingerbread.
   */
  public function updateUserFields(UserInterface $account, array $cookie) {
    foreach ($this->config
      ->get('bakery_supported_fields') as $type => $enabled) {
      if ($enabled && isset($cookie[$type])) {
        switch ($type) {
          case 'name':
            $account
              ->setUsername($cookie['name']);
            break;
          case 'mail':
            $account
              ->setEmail($cookie['mail']);
            break;
          default:
        }
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BakeryService::$config protected property
BakeryService::$isMain protected property If the current site is configured as the main site or a child.
BakeryService::$kitchen protected property
BakeryService::isChild public function Check if the current site is a child site.
BakeryService::isMain public function Check if the current site is the main site.
BakeryService::requestAccount public function Request account information from master to create account locally.
BakeryService::updateUserFields public function Update a user account with fields from a cookie.
BakeryService::userExternalLogin public function Perform standard Drupal login operations for a user object.
BakeryService::__construct public function When the service is created, set a value for the example variable.