CartLinkToken.php in Commerce Add To Cart Link 2.x
File
src/CartLinkToken.php
View source
<?php
namespace Drupal\commerce_add_to_cart_link;
use Drupal\commerce_product\Entity\ProductVariationInterface;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\PrivateKey;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Site\Settings;
class CartLinkToken implements CartLinkTokenInterface {
protected $config;
protected $currentUser;
protected $privateKey;
public function __construct(AccountInterface $current_user, ConfigFactoryInterface $config_factory, PrivateKey $private_key) {
$this->config = $config_factory
->get('commerce_add_to_cart_link.settings');
$this->currentUser = $current_user;
$this->privateKey = $private_key;
}
public function generate(ProductVariationInterface $variation) {
if (!$this
->needsCsrfProtection($this->currentUser)) {
return '';
}
$value = $this
->generateTokenValue($variation);
return substr(Crypt::hmacBase64($value, $this->privateKey
->get() . $this
->getHashSalt()), 0, 16);
}
public function validate(ProductVariationInterface $variation, string $token) {
if (!$this
->needsCsrfProtection($this->currentUser)) {
return TRUE;
}
$value = $this
->generate($variation);
return hash_equals($value, $token);
}
public function needsCsrfProtection(AccountInterface $account = NULL) {
if (is_null($account)) {
$account = $this->currentUser;
}
$csrf_protected_roles = $this->config
->get('csrf_token.roles');
if (empty($csrf_protected_roles)) {
return FALSE;
}
return !empty(array_intersect($csrf_protected_roles, $account
->getRoles()));
}
protected function generateTokenValue(ProductVariationInterface $variation) {
return sprintf('cart_link:%s:%s', $variation
->getProductId(), $variation
->id());
}
protected function getHashSalt() {
return Settings::getHashSalt();
}
}