Skip to content

Commit

Permalink
FIX: Session TTL incorrect when date string is provided in config
Browse files Browse the repository at this point in the history
  • Loading branch information
crosa7 committed Oct 6, 2023
1 parent 4c299aa commit b079f7f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -585,12 +585,24 @@ 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) {
trigger_error('Provided string could not be converted to time');
return;
}

static::$session->set('SESSION_TTL', $sessionLifetimeInTime);
}
}
22 changes: 22 additions & 0 deletions tests/AuthSessionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});

0 comments on commit b079f7f

Please sign in to comment.