getHashSalt example

// Store the selection settings in the key/value store and pass a hashed key     // in the route parameters.     $selection_settings = $element['#selection_settings'] ?? [];
    // Don't serialize the entity, it will be added explicitly afterwards.     if (isset($selection_settings['entity']) && ($selection_settings['entity'] instanceof EntityInterface)) {
      $element['#autocomplete_query_parameters']['entity_type'] = $selection_settings['entity']->getEntityTypeId();
      $element['#autocomplete_query_parameters']['entity_id'] = $selection_settings['entity']->id();
      unset($selection_settings['entity']);
    }
    $data = serialize($selection_settings) . $element['#target_type'] . $element['#selection_handler'];
    $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());

    $key_value_storage = \Drupal::keyValue('entity_autocomplete');
    if (!$key_value_storage->has($selection_settings_key)) {
      $key_value_storage->set($selection_settings_key$selection_settings);
    }

    $element['#autocomplete_route_name'] = 'system.entity_autocomplete';
    $element['#autocomplete_route_parameters'] = [
      'target_type' => $element['#target_type'],
      'selection_handler' => $element['#selection_handler'],
      'selection_settings_key' => $selection_settings_key,
    ];
foreach ($this->getEffects() as $effect) {
      $extension = $effect->getDerivativeExtension($extension);
    }
    return $extension;
  }

  /** * {@inheritdoc} */
  public function getPathToken($uri) {
    // Return the first 8 characters.     return substr(Crypt::hmacBase64($this->id() . ':' . $this->addExtension($uri)$this->getPrivateKey() . $this->getHashSalt()), 0, 8);
  }

  /** * {@inheritdoc} */
  public function deleteImageEffect(ImageEffectInterface $effect) {
    $this->getEffects()->removeInstanceId($effect->getUuid());
    $this->save();
    return $this;
  }

  
/** * Creates a contextual ID token. * * @param string $id * The contextual ID to create a token for. * * @return string * The contextual ID token. */
  protected function createContextualIdToken($id) {
    return Crypt::hmacBase64($id, Settings::getHashSalt() . $this->container->get('private_key')->get());
  }

}

  protected function computeToken($seed$value = '') {
    return Crypt::hmacBase64($value$seed . $this->privateKey->get() . Settings::getHashSalt());
  }

}
public function testBlockContextualLinks() {
    $this->drupalLogin($this->drupalCreateUser([
      'administer views',
      'access contextual links',
      'administer blocks',
    ]));
    $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1');
    $cached_block = $this->drupalPlaceBlock('views_block:test_view_block-block_1');
    $this->drupalGet('test-page');

    $id = 'block:block=' . $block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en';
    $id_token = Crypt::hmacBase64($id, Settings::getHashSalt() . $this->container->get('private_key')->get());
    $cached_id = 'block:block=' . $cached_block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en';
    $cached_id_token = Crypt::hmacBase64($cached_id, Settings::getHashSalt() . $this->container->get('private_key')->get());
    // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:assertContextualLinkPlaceHolder()     // Check existence of the contextual link placeholders.     $this->assertSession()->responseContains('<div' . new Attribute(['data-contextual-id' => $id, 'data-contextual-token' => $id_token, 'data-drupal-ajax-container' => '']) . '></div>');
    $this->assertSession()->responseContains('<div' . new Attribute(['data-contextual-id' => $cached_id, 'data-contextual-token' => $cached_id_token, 'data-drupal-ajax-container' => '']) . '></div>');

    // Get server-rendered contextual links.     // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:renderContextualLinks()     $post = ['ids[0]' => $id, 'ids[1]' => $cached_id, 'tokens[0]' => $id_token, 'tokens[1]' => $cached_id_token];
    $url = 'contextual/render?_format=json,destination=test-page';
    
if ($file->getOwnerId() != \Drupal::currentUser()->id()) {
                  $force_default = TRUE;
                  break;
                }
                // Since file ownership can't be determined for anonymous users,                 // they are not allowed to reuse temporary files at all. But                 // they do need to be able to reuse their own files from earlier                 // submissions of the same form, so to allow that, check for the                 // token added by $this->processManagedFile().                 elseif (\Drupal::currentUser()->isAnonymous()) {
                  $token = NestedArray::getValue($form_state->getUserInput()array_merge($element['#parents']['file_' . $file->id(), 'fid_token']));
                  $file_hmac = Crypt::hmacBase64('file-' . $file->id(), \Drupal::service('private_key')->get() . Settings::getHashSalt());
                  if ($token === NULL || !hash_equals($file_hmac$token)) {
                    $force_default = TRUE;
                    break;
                  }
                }
              }
            }
          }
          if ($force_default) {
            $fids = [];
          }
        }
    // does not contain only the entity label.     $fields = $view->displayHandlers->get('entity_reference_1')->getOption('fields');
    $fields['type']['exclude'] = FALSE;
    $view->displayHandlers->get('entity_reference_1')->setOption('fields', $fields);
    $view->save();

    // Prepare the selection settings key needed by the entity reference     // autocomplete route.     $target_type = 'node';
    $selection_handler = 'views';
    $selection_settings = $this->handlerSettings;
    $selection_settings_key = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
    \Drupal::keyValue('entity_autocomplete')->set($selection_settings_key$selection_settings);

    $result = Json::decode($this->drupalGet('entity_reference_autocomplete/' . $target_type . '/' . $selection_handler . '/' . $selection_settings_key['query' => ['q' => 't']]));

    $expected = [
      0 => [
        'value' => $this->nodes[1]->bundle() . ': ' . $this->nodes[1]->label() . ' (' . $this->nodes[1]->id() . ')',
        'label' => '<span class="views-field views-field-type"><span class="field-content">' . $this->nodes[1]->bundle() . '</span></span>: <span class="views-field views-field-title"><span class="field-content">' . Html::escape($this->nodes[1]->label()) . '</span></span>',
      ],
      1 => [
        'value' => $this->nodes[2]->bundle() . ': ' . $this->nodes[2]->label() . ' (' . $this->nodes[2]->id() . ')',
        
public function handleAutocomplete(Request $request$target_type$selection_handler$selection_settings_key) {
    $matches = [];
    // Get the typed string from the URL, if it exists.     if ($input = $request->query->get('q')) {
      $tag_list = Tags::explode($input);
      $typed_string = !empty($tag_list) ? mb_strtolower(array_pop($tag_list)) : '';

      // Selection settings are passed in as a hashed key of a serialized array       // stored in the key/value store.       $selection_settings = $this->keyValue->get($selection_settings_key, FALSE);
      if ($selection_settings !== FALSE) {
        $selection_settings_hash = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
        if (!hash_equals($selection_settings_hash$selection_settings_key)) {
          // Disallow access when the selection settings hash does not match the           // passed-in key.           throw new AccessDeniedHttpException('Invalid selection settings key.');
        }
      }
      else {
        // Disallow access when the selection settings key is not found in the         // key/value store.         throw new AccessDeniedHttpException();
      }

      
throw new BadRequestHttpException('No contextual ids specified.');
    }
    $ids = $request->request->all('ids');

    if (!$request->request->has('tokens')) {
      throw new BadRequestHttpException('No contextual ID tokens specified.');
    }
    $tokens = $request->request->all('tokens');

    $rendered = [];
    foreach ($ids as $key => $id) {
      if (!isset($tokens[$key]) || !hash_equals($tokens[$key], Crypt::hmacBase64($id, Settings::getHashSalt() . \Drupal::service('private_key')->get()))) {
        throw new BadRequestHttpException('Invalid contextual ID specified.');
      }
      $element = [
        '#type' => 'contextual_links',
        '#contextual_links' => _contextual_id_to_links($id),
      ];
      $rendered[$id] = $this->renderer->renderRoot($element);
    }

    return new JsonResponse($rendered);
  }

}
$configuration = [];
    $overrides = Settings::get('php_storage');
    if (isset($overrides[$name])) {
      $configuration = $overrides[$name];
    }
    elseif (isset($overrides['default'])) {
      $configuration = $overrides['default'];
    }
    // Make sure all the necessary configuration values are set.     $class = $configuration['class'] ?? 'Drupal\Component\PhpStorage\MTimeProtectedFileStorage';
    if (!isset($configuration['secret'])) {
      $configuration['secret'] = Settings::getHashSalt();
    }
    if (!isset($configuration['bin'])) {
      $configuration['bin'] = $name;
    }
    if (!isset($configuration['directory'])) {
      $configuration['directory'] = PublicStream::basePath() . '/php';
    }
    return new $class($configuration);
  }

}
$normalized['asset_group']['items'][$key] = array_diff_key($asset$group_keys$omit_keys);
      // If the version is set to -1, this means there is no version in the       // library definition. To ensure unique hashes when unversioned files       // change, replace the version with a hash of the file contents.       if ($asset['version'] === -1) {
        $normalized['asset_group']['items'][$key]['version'] = hash('xxh64', file_get_contents($asset['data']));
      }
    }
    // The asset array ensures that a valid hash can only be generated via the     // same code base. Additionally use the hash salt to ensure that hashes are     // not re-usable between different installations.     return Crypt::hmacBase64(serialize($normalized), Settings::getHashSalt());
  }

}
/** * Hashes the given string. * * @param string $identifier * The string to be hashed. * * @return string * The hash. */
  protected function hash($identifier) {
    return hash('sha256', $this->privateKey->get() . Settings::getHashSalt() . $identifier);
  }

}
public function testGetInstance() {
    $singleton = $this->settings->getInstance();
    $this->assertEquals($singleton$this->settings);
  }

  /** * Tests Settings::getHashSalt(). * * @covers ::getHashSalt */
  public function testGetHashSalt() {
    $this->assertSame($this->config['hash_salt']$this->settings->getHashSalt());
  }

  /** * Tests Settings::getHashSalt() with no hash salt value. * * @covers ::getHashSalt * * @dataProvider providerTestGetHashSaltEmpty */
  public function testGetHashSaltEmpty(array $config) {
    // Re-create settings with no 'hash_salt' key.
$entity_reference_controller->handleAutocomplete($request$this->entityType, 'default', $selection_settings_key);

      $this->fail('Non-existent selection settings key throws an exception.');
    }
    catch (AccessDeniedHttpException $e) {
      // Expected exception; just continue testing.     }

    try {
      // Generate a valid hash key but store a modified settings array.       $selection_settings = [];
      $selection_settings_key = Crypt::hmacBase64(serialize($selection_settings) . $this->entityType . 'default', Settings::getHashSalt());

      $selection_settings[$this->randomMachineName()] = $this->randomString();
      \Drupal::keyValue('entity_autocomplete')->set($selection_settings_key$selection_settings);

      $entity_reference_controller->handleAutocomplete($request$this->entityType, 'default', $selection_settings_key);
    }
    catch (AccessDeniedHttpException $e) {
      $this->assertSame('Invalid selection settings key.', $e->getMessage());
    }

  }

  

  public function getHash($url$max_width = NULL, $max_height = NULL) {
    return Crypt::hmacBase64("$url:$max_width:$max_height", $this->privateKey->get() . Settings::getHashSalt());
  }

  /** * Checks if an oEmbed URL can be securely displayed in an frame. * * @param string $url * The URL to check. * * @return bool * TRUE if the URL is considered secure, otherwise FALSE. */
  
Home | Imprint | This part of the site doesn't use cookies.