Skip to content

Instantly share code, notes, and snippets.

@butschster
Last active July 3, 2020 12:53
Show Gist options
  • Save butschster/42f58eb3fb16d32e56b21b02358ec7fd to your computer and use it in GitHub Desktop.
Save butschster/42f58eb3fb16d32e56b21b02358ec7fd to your computer and use it in GitHub Desktop.
<?php
class TemporarySignature implements TemporarySignatureInterface
{
private string $hashKey;
private int $ttl;
/**
* @param string $hashKey
* @param int $ttl Время жизни токена в минутах
*/
public function __construct(string $hashKey, int $ttl)
{
$this->hashKey = $hashKey;
$this->ttl = $ttl;
}
public function generate($product, $price): string
{
$timestamp = Carbon::now()->addMinutes($this->ttl)->getTimestamp();
// TIMESTAMP|SIGNATURE
return $timestamp . '|' . $this->sign($product, $price, $timestamp);
}
public function isValid(string $signature, $product, $price): bool
{
if (empty($signature)) {
return false;
}
if (strpos($signature, '|') === false) {
return false;
}
[$timestamp, $signature] = explode('|', $signature, 2);
return hash_equals($this->sign($product, $price, $timestamp), $signature)
&& !$this->isExpired((int)$timestamp);
}
protected function sign($product, $price, int $timestamp): string
{
return hash_hmac('sha256', $product.$price . $timestamp, $this->hashKey);
}
protected function isExpired(int $timestamp): bool
{
return $timestamp < Carbon::now()->getTimestamp();
}
}
<?php
// Регистрируем сервис в ServiceProvider
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(
TemporarySignatureInterface::class,
function () {
return new TemporarySignature('secret-word', 10);
}
);
}
}
<?php
// И используем в контроллере
class ShowProductPriceAction extends Controller
{
public function __invoke(TemporarySignatureInterface $signatureService)
{
$product = 'abstract product';
$price = '1000 RUB';
$signature = $signatureService->generate($product, $price);
return [
'product' => $product,
'price' => $price,
'signature' => $hash
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment