Skip to content

Commit

Permalink
Merge pull request #19 from leafsphp/fix-session-lifetime-incorrect-w…
Browse files Browse the repository at this point in the history
…hen-string-provided

FIX: Session TTL incorrect when date string is provided in config
  • Loading branch information
crosa7 committed Oct 6, 2023
2 parents 4c299aa + 6178ac6 commit 8844171
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 5 deletions.
3 changes: 2 additions & 1 deletion composer.json
Expand Up @@ -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"
Expand Down
19 changes: 15 additions & 4 deletions src/Auth.php
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
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 8844171

Please sign in to comment.