From 67858d34d97c28356f55eed46bf6a0c56df1461d Mon Sep 17 00:00:00 2001 From: Tom Hempel Date: Wed, 24 Jun 2026 10:23:19 +0200 Subject: [PATCH] enhanced token management by adding optional expiry refresh in token_get_record and updated session API documentation --- common.php | 25 ++++++++++++++++++++----- handlers/session.php | 5 +---- lib/api_log.php | 2 +- tests/Integration/TokenTest.php | 21 +++++++++++++++++++++ 4 files changed, 43 insertions(+), 10 deletions(-) diff --git a/common.php b/common.php index 85dc345..b019ae8 100644 --- a/common.php +++ b/common.php @@ -178,14 +178,29 @@ function token_add(string $token, int $ttlSeconds = 86400, array $extra = []): v qdb_save($tmpDb, $lockFp); } -function token_get_record(string $token): ?array { +function token_get_record(string $token, bool $refreshExpiry = true): ?array { require_once __DIR__ . '/db_init.php'; - [$pdo, $tmpDb, $lockFp] = qdb_open(false); + require_once __DIR__ . '/lib/settings.php'; + [$pdo, $tmpDb, $lockFp] = qdb_open($refreshExpiry); + $now = time(); $stmt = $pdo->prepare("SELECT * FROM session WHERE token = :t AND expiresAt >= :now"); - $stmt->execute([':t' => token_storage_key($token), ':now' => time()]); + $storedToken = token_storage_key($token); + $stmt->execute([':t' => $storedToken, ':now' => $now]); $row = $stmt->fetch(PDO::FETCH_ASSOC); - qdb_discard($tmpDb, $lockFp); - if (!$row) return null; + if (!$row) { + qdb_discard($tmpDb, $lockFp); + return null; + } + if ($refreshExpiry) { + $settings = qdb_settings_get_on_pdo($pdo); + $newExpiry = $now + qdb_session_ttl_seconds($settings, !empty($row['temp'])); + $pdo->prepare('UPDATE session SET expiresAt = :exp WHERE token = :t') + ->execute([':exp' => $newExpiry, ':t' => $storedToken]); + $row['expiresAt'] = $newExpiry; + qdb_save($tmpDb, $lockFp); + } else { + qdb_discard($tmpDb, $lockFp); + } // Map DB columns to the keys the rest of the codebase expects return [ 'token' => $row['token'], diff --git a/handlers/session.php b/handlers/session.php index e204d2f..226a054 100644 --- a/handlers/session.php +++ b/handlers/session.php @@ -1,7 +1,7 @@ assertGreaterThanOrEqual(2, $n); $this->assertNull(token_get_record($t1)); } + + public function testTokenLookupRefreshesExpiry(): void + { + $token = bin2hex(random_bytes(32)); + $f = $this->fixture(); + token_add($token, 3600, [ + 'userID' => $f->adminUserId, + 'role' => 'admin', + 'entityID' => 'ent', + ]); + + [$pdo, $tmpDb, $lockFp] = qdb_open(true); + $oldExpiry = time() + 60; + $pdo->prepare('UPDATE session SET expiresAt = :exp WHERE token = :t') + ->execute([':exp' => $oldExpiry, ':t' => token_storage_key($token)]); + qdb_save($tmpDb, $lockFp); + + $rec = token_get_record($token); + $this->assertNotNull($rec); + $this->assertGreaterThan($oldExpiry + 3000, $rec['exp']); + } }