Files
php-com-cen/src/Security/TokenHandler.php
T
2026-03-06 11:06:19 +01:00

59 lines
1.9 KiB
PHP

<?php
namespace ComCen\Security;
class TokenHandler
{
private static ?self $instance = null;
private static $tokens = [];
private static int $iterations = 0;
private static function random32Characters(): string {
$data = random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
return bin2hex($data);
}
public static function doesUserHaveToken(string $username): bool
{
return array_any(self::$tokens, fn($token) => $token[0] === $username);
}
public static function getNewTokenForUser(string $username): string
{
$tokenBody = self::random32Characters() . str_pad(self::$iterations++, 5, '0');
if (self::$iterations >= 99999) {
self::$iterations = 0;
}
$timestamp = microtime(true) * 10000;
self::$tokens[] = [$username, $timestamp, $tokenBody];
return $timestamp . $tokenBody;
}
public static function getTokenOwnership(string $controlledToken): string | null
{
for ($i = 0; $i < count(self::$tokens); ++$i) {
$token = self::$tokens[$i];
if ($token[1] . $token[2] === $controlledToken) {
return $token[0];
}
}
return null;
}
public static function deleteOldTokens(): void
{
for ($i = 0; $i < count(self::$tokens); ++$i) {
$token = self::$tokens[$i];
// 1 hour
if (time() - ($token[1] / 10000) > 3600) {
array_splice(self::$tokens, $i, 1);
}
}
}
public static function deleteTokensForUser(string $user): void
{
for ($i = 0; $i < count(self::$tokens); ++$i) {
if (self::$tokens[$i][0] === $user) {
array_splice(self::$tokens, $i, 1);
}
}
}
}