From 6178ac6f593ce7052e166e1255917285a8aca1c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Rosa?= Date: Fri, 6 Oct 2023 14:46:07 +0100 Subject: [PATCH] FIX: Session TTL incorrect when date string is provided in config --- composer.json | 3 ++- src/Auth.php | 19 +++++++++++++++---- tests/AuthSessionTest.php | 22 ++++++++++++++++++++++ 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index d354e92..661f552 100644 --- a/composer.json +++ b/composer.json @@ -45,7 +45,8 @@ } }, "require-dev": { - "leafs/alchemy": "^1.0" + "leafs/alchemy": "^1.0", + "pestphp/pest": "^1.0 | ^2.0" }, "scripts": { "test": "vendor/bin/pest --colors=always --coverage" diff --git a/src/Auth.php b/src/Auth.php index ff78a26..58c38fa 100644 --- a/src/Auth.php +++ b/src/Auth.php @@ -585,12 +585,23 @@ private static function setUserToSession(array $user, string $token): void */ private static function setSessionTtl(): void { - $sessionLifetime = is_int(static::config('SESSION_LIFETIME')) - ? static::config('SESSION_LIFETIME') - : (int) strtotime(static::config('SESSION_LIFETIME')); + $sessionLifetime = static::config('SESSION_LIFETIME'); - if ($sessionLifetime > 0) { + if ($sessionLifetime === 0) { + return; + } + + if (is_int($sessionLifetime)) { static::$session->set('SESSION_TTL', time() + $sessionLifetime); + return; + } + + $sessionLifetimeInTime = strtotime($sessionLifetime); + + if (!$sessionLifetimeInTime) { + throw new \Exception('Provided string could not be converted to time'); } + + static::$session->set('SESSION_TTL', $sessionLifetimeInTime); } } diff --git a/tests/AuthSessionTest.php b/tests/AuthSessionTest.php index 22fcdc9..54224ef 100644 --- a/tests/AuthSessionTest.php +++ b/tests/AuthSessionTest.php @@ -141,3 +141,25 @@ sleep(2); expect($auth::status())->toBeFalse(); }); + +test('Session lifetime should set correct session ttl when string is configured instead of timestamp', function () { + $auth = new \Leaf\Auth(); + $auth::config(getAuthConfig(['SESSION_LIFETIME' => '1 day'])); + $auth::login(['username' => 'login-user', 'password' => 'login-pass']); + + expect($auth::status())->not()->toBeNull(); + + $timestampOneDay = 60 * 60 * 24; + $session = new \Leaf\Http\Session(false); + $sessionTtl = $session->get('SESSION_TTL'); + + expect($sessionTtl)->toBe(time() + $timestampOneDay); +}); + +test('Login should throw error when lifetime string is invalid', function () { + $auth = new \Leaf\Auth(); + $auth::config(getAuthConfig(['SESSION_LIFETIME' => 'invalid string'])); + + expect(fn() => $auth::login(['username' => 'login-user', 'password' => 'login-pass'])) + ->toThrow(Exception::class, 'Provided string could not be converted to time'); +});