46 lines
1.2 KiB
PHP
46 lines
1.2 KiB
PHP
<?php
|
|
/**
|
|
* File: UnsubscribeTokenHelper.php
|
|
* Version: 1.0
|
|
* Path: app/Utilities/
|
|
* Purpose: Provides secure token generation and validation for unsubscribe links.
|
|
*/
|
|
|
|
namespace WizdomNetworks\WizeWeb\Utilities;
|
|
|
|
class UnsubscribeTokenHelper
|
|
{
|
|
/**
|
|
* Generate a secure token for an email + timestamp
|
|
*
|
|
* @param string $email
|
|
* @param int $timestamp
|
|
* @return string
|
|
*/
|
|
public static function generate(string $email, int $timestamp): string
|
|
{
|
|
$secret = $_ENV['UNSUBSCRIBE_SECRET'] ?? 'changeme';
|
|
return hash_hmac('sha256', $email . $timestamp, $secret);
|
|
}
|
|
|
|
/**
|
|
* Validate a token with an expiration window (default 24h)
|
|
*
|
|
* @param string $email
|
|
* @param int $timestamp
|
|
* @param string $token
|
|
* @param int $validForSeconds
|
|
* @return bool
|
|
*/
|
|
public static function isValid(string $email, int $timestamp, string $token, int $validForSeconds = 86400): bool
|
|
{
|
|
$expected = self::generate($email, $timestamp);
|
|
if (!hash_equals($expected, $token)) {
|
|
return false;
|
|
}
|
|
|
|
// Check timestamp freshness
|
|
return abs(time() - $timestamp) <= $validForSeconds;
|
|
}
|
|
}
|