WizdomWeb/app/Services/TokenService.php

49 lines
1.4 KiB
PHP

<?php
/**
* File: TokenService.php
* Version: 1.0
* Path: app/Services/
* Purpose: Provides generic token generation and validation using HMAC.
*/
namespace WizdomNetworks\WizeWeb\Services;
class TokenService
{
/**
* Generate an HMAC token from a string payload.
*
* @param string $data The string to sign (e.g. email+timestamp).
* @param string $secret Secret key.
* @return string HMAC token.
*/
public function generate(string $data, string $secret): string
{
return hash_hmac('sha256', $data, $secret);
}
/**
* Validate a token against expected data, with optional TTL enforcement.
*
* @param string $data Original payload used to generate token.
* @param string $token Supplied token.
* @param string $secret Secret key used to validate.
* @param int|null $timestamp Unix timestamp used in original payload.
* @param int $ttlSeconds Time-to-live in seconds (default 86400 = 1 day).
* @return bool
*/
public function isValid(string $data, string $token, string $secret, ?int $timestamp = null, int $ttlSeconds = 86400): bool
{
$expected = $this->generate($data, $secret);
if (!hash_equals($expected, $token)) {
return false;
}
if ($timestamp !== null && abs(time() - $timestamp) > $ttlSeconds) {
return false;
}
return true;
}
}