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 337bab0
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 5 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
}
},
"require-dev": {
"leafs/alchemy": "^1.0"
"leafs/alchemy": "^1.0",
"pestphp/pest": "^2.0"
},
"scripts": {
"test": "vendor/bin/pest --colors=always --coverage"
Expand Down
19 changes: 15 additions & 4 deletions src/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
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 337bab0

Please sign in to comment.