randomBytesBase64 example


  public function set($key$value) {
    if ($this->currentUser->isAnonymous()) {
      // Ensure that an anonymous user has a session created for them, as       // otherwise subsequent page loads will not be able to retrieve their       // tempstore data. Note this has to be done before the key is created as       // the owner is used in key creation.       $this->startSession();
      $session = $this->requestStack->getCurrentRequest()->getSession();
      if (!$session->has('core.tempstore.private.owner')) {
        $session->set('core.tempstore.private.owner', Crypt::randomBytesBase64());
      }
    }

    $key = $this->createkey($key);
    if (!$this->lockBackend->acquire($key)) {
      $this->lockBackend->wait($key);
      if (!$this->lockBackend->acquire($key)) {
        throw new TempStoreException("Couldn't acquire lock to update item '$key' in '{$this->storage->getCollectionName()}' temporary storage.");
      }
    }

    
->disableOriginalConstructor()
      ->onlyMethods(['getRoles', 'id'])
      ->getMock();
    $this->account2Updated->expects($this->any())
      ->method('getRoles')
      ->willReturn($roles_2_updated);
    $this->account2Updated->expects($this->any())
      ->method('id')
      ->willReturn(2);

    // Mocked private key + cache services.     $random = Crypt::randomBytesBase64(55);
    $this->privateKey = $this->getMockBuilder('Drupal\Core\PrivateKey')
      ->disableOriginalConstructor()
      ->onlyMethods(['get'])
      ->getMock();
    $this->privateKey->expects($this->any())
      ->method('get')
      ->willReturn($random);
    $this->cache = $this->getMockBuilder('Drupal\Core\Cache\CacheBackendInterface')
      ->disableOriginalConstructor()
      ->getMock();
    $this->staticCache = $this->getMockBuilder('Drupal\Core\Cache\CacheBackendInterface')
      


    new Settings($settings);

    $this->generator = new CsrfTokenGenerator($this->privateKey, $this->sessionMetadata);
  }

  /** * Set up default expectations on the mocks. */
  protected function setupDefaultExpectations() {
    $key = Crypt::randomBytesBase64();
    $this->privateKey->expects($this->any())
      ->method('get')
      ->willReturn($key);

    $seed = Crypt::randomBytesBase64();
    $this->sessionMetadata->expects($this->any())
      ->method('getCsrfTokenSeed')
      ->willReturn($seed);
  }

  /** * Tests CsrfTokenGenerator::get(). * * @covers ::get */

  protected $key;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    $this->key = Crypt::randomBytesBase64(55);

    $this->state = $this->createMock('Drupal\Core\State\StateInterface');

    $this->privateKey = new PrivateKey($this->state);
  }

  /** * Tests PrivateKey::get(). */
  public function testGet() {
    $this->state->expects($this->once())
      

  protected function tempnam($directory$prefix) {
    do {
      $path = $directory . '/' . $prefix . Crypt::randomBytesBase64(20);
    } while (file_exists($path));
    return $path;
  }

}
if (empty($normalized_omissions)) {
      return new CacheableOmission($cacheability);
    }
    $omission_links = [
      'detail' => 'Some resources have been omitted because of insufficient authorization.',
      'links' => [
        'help' => [
          'href' => 'https://www.drupal.org/docs/8/modules/json-api/filtering#filters-access-control',
        ],
      ],
    ];
    $link_hash_salt = Crypt::randomBytesBase64();
    foreach ($normalized_omissions as $omission) {
      $cacheability->addCacheableDependency($omission);
      // Add the errors to the pre-existing errors.       foreach ($omission->getNormalization() as $error) {
        // JSON:API links cannot be arrays and the spec generally favors link         // relation types as keys. 'item' is the right link relation type, but         // we need multiple values. To do that, we generate a meaningless,         // random value to use as a unique key. That value is a hash of a         // random salt and the link href. This ensures that the key is non-         // deterministic while letting use deduplicate the links by their         // href. The salt is *not* used for any cryptographic reason.

  protected function hashByHref(Link $link) {
    // Generate a salt unique to each instance of this class.     if (!$this->hashSalt) {
      $this->hashSalt = Crypt::randomBytesBase64();
    }
    // Create a dictionary of link parameters.     $link_parameters = [
      'href' => $link->getHref(),
    ] + $link->getTargetAttributes();
    // Serialize the dictionary into a string.     foreach ($link_parameters as $name => $value) {
      $serialized_parameters[] = sprintf('%s="%s"', $nameimplode(' ', (array) $value));
    }
    // Hash the string.     $b64_hash = Crypt::hashBase64($this->hashSalt . implode('; ', $serialized_parameters));
    

  public function get($value = '') {
    $seed = $this->sessionMetadata->getCsrfTokenSeed();
    if (empty($seed)) {
      $seed = Crypt::randomBytesBase64();
      $this->sessionMetadata->setCsrfTokenSeed($seed);
    }

    return $this->computeToken($seed$value);
  }

  /** * Validates a token based on $value, the user session, and the private key. * * @param string $token * The token to be validated. * @param string $value * (optional) An additional value to base the token on. * * @return bool * TRUE for a valid token, FALSE for an invalid token. */
/** * {@inheritdoc} * * phpcs:ignore Drupal.Commenting.FunctionComment.VoidReturn * @return void */
  public function stampNew($lifetime = NULL) {
    parent::stampNew($lifetime);

    // Set the token seed immediately to avoid a race condition between two     // simultaneous requests without a seed.     $this->setCsrfTokenSeed(Crypt::randomBytesBase64());
  }

}

  abstract protected function setDatabaseDumpFiles();

  /** * Add settings that are missed since the installer isn't run. */
  protected function prepareSettings() {
    parent::prepareSettings();

    // Generate a hash salt.     $settings['settings']['hash_salt'] = (object) [
      'value'    => Crypt::randomBytesBase64(55),
      'required' => TRUE,
    ];

    // Since the installer isn't run, add the database settings here too.     $settings['databases']['default'] = (object) [
      'value' => Database::getConnectionInfo(),
      'required' => TRUE,
    ];

    // Force every update hook to only run one entity per batch.     $settings['entity_update_batch_size'] = (object) [
      

  public function getCache($form_build_id, FormStateInterface $form_state) {
    if ($form = $this->keyValueExpirableFactory->get('form')->get($form_build_id)) {
      if ((isset($form['#cache_token']) && $this->csrfToken->validate($form['#cache_token'])) || (!isset($form['#cache_token']) && $this->currentUser->isAnonymous())) {
        $this->loadCachedFormState($form_build_id$form_state);

        // Generate a new #build_id if the cached form was rendered on a         // cacheable page.         $build_info = $form_state->getBuildInfo();
        if (!empty($build_info['immutable'])) {
          $form['#build_id_old'] = $form['#build_id'];
          $form['#build_id'] = 'form-' . Crypt::randomBytesBase64();
          $form['form_build_id']['#value'] = $form['#build_id'];
          $form['form_build_id']['#id'] = $form['#build_id'];
          unset($build_info['immutable']);
          $form_state->setBuildInfo($build_info);
        }
        return $form;
      }
    }
  }

  /** * Loads the cached form state. * * @param string $form_build_id * The unique form build ID. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. */

  public static function getUniqueId($id) {
    // If this is an Ajax request, then content returned by this page request     // will be merged with content already on the base page. The HTML IDs must     // be unique for the fully merged content. Therefore use unique IDs.     if (static::$isAjax) {
      return static::getId($id) . '--' . Crypt::randomBytesBase64(8);
    }

    // @todo Remove all that code once we switch over to random IDs only,     // see https://www.drupal.org/node/1090592.     if (!isset(static::$seenIdsInit)) {
      static::$seenIdsInit = [];
    }
    if (!isset(static::$seenIds)) {
      static::$seenIds = static::$seenIdsInit;
    }

    

  protected $syncDirectory;

  /** * {@inheritdoc} */
  protected function prepareEnvironment() {
    parent::prepareEnvironment();
    $this->syncDirectory = $this->publicFilesDirectory . '/config_' . Crypt::randomBytesBase64() . '/sync';
    $this->settings['settings']['config_sync_directory'] = (object) [
      'value' => $this->syncDirectory,
      'required' => TRUE,
    ];
  }

  /** * Verifies that installation succeeded. */
  public function testInstaller() {
    $this->assertSession()->addressEquals('user/1');
    
$identifier = $user->id() . '-' . $request->getClientIP();
    }

    $this->flood->clear('user.failed_login_user', $identifier);
    $this->flood->clear('user.http_login', $identifier);

    user_login_finalize($user);
    $this->logger->info('User %name used one-time login link at time %timestamp.', ['%name' => $user->getDisplayName(), '%timestamp' => $timestamp]);
    $this->messenger()->addStatus($this->t('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please set your password.'));
    // Let the user's password be changed without the current password     // check.     $token = Crypt::randomBytesBase64(55);
    $request->getSession()->set('pass_reset_' . $user->id()$token);
    // Clear any flood events for this user.     $this->flood->clear('user.password_request_user', $uid);
    return $this->redirect(
      'entity.user.edit_form',
      ['user' => $user->id()],
      [
        'query' => ['pass-reset-token' => $token],
        'absolute' => TRUE,
      ]
    );
  }

  public function get($collection$owner = NULL) {
    // Use the currently authenticated user ID or the active user ID unless     // the owner is overridden.     if (!isset($owner)) {
      $owner = $this->currentUser->id();
      if ($this->currentUser->isAnonymous()) {
        $owner = Crypt::randomBytesBase64();
        if ($this->requestStack->getCurrentRequest()->hasSession()) {
          // Store a random identifier for anonymous users if the session is           // available.           $owner = $this->requestStack->getCurrentRequest()->getSession()->get('core.tempstore.shared.owner', $owner);
        }
      }
    }

    // Store the data for this collection in the database.     $storage = $this->storageFactory->get("tempstore.shared.$collection");
    return new SharedTempStore($storage$this->lockBackend, $owner$this->requestStack, $this->currentUser, $this->expire);
  }
Home | Imprint | This part of the site doesn't use cookies.