Skip to content

Commit 8844171

Browse files
authored
Merge pull request #19 from leafsphp/fix-session-lifetime-incorrect-when-string-provided
FIX: Session TTL incorrect when date string is provided in config
2 parents 4c299aa + 6178ac6 commit 8844171

File tree

3 files changed

+39
-5
lines changed

3 files changed

+39
-5
lines changed

composer.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@
4545
}
4646
},
4747
"require-dev": {
48-
"leafs/alchemy": "^1.0"
48+
"leafs/alchemy": "^1.0",
49+
"pestphp/pest": "^1.0 | ^2.0"
4950
},
5051
"scripts": {
5152
"test": "vendor/bin/pest --colors=always --coverage"

src/Auth.php

+15-4
Original file line numberDiff line numberDiff line change
@@ -585,12 +585,23 @@ private static function setUserToSession(array $user, string $token): void
585585
*/
586586
private static function setSessionTtl(): void
587587
{
588-
$sessionLifetime = is_int(static::config('SESSION_LIFETIME'))
589-
? static::config('SESSION_LIFETIME')
590-
: (int) strtotime(static::config('SESSION_LIFETIME'));
588+
$sessionLifetime = static::config('SESSION_LIFETIME');
591589

592-
if ($sessionLifetime > 0) {
590+
if ($sessionLifetime === 0) {
591+
return;
592+
}
593+
594+
if (is_int($sessionLifetime)) {
593595
static::$session->set('SESSION_TTL', time() + $sessionLifetime);
596+
return;
597+
}
598+
599+
$sessionLifetimeInTime = strtotime($sessionLifetime);
600+
601+
if (!$sessionLifetimeInTime) {
602+
throw new \Exception('Provided string could not be converted to time');
594603
}
604+
605+
static::$session->set('SESSION_TTL', $sessionLifetimeInTime);
595606
}
596607
}

tests/AuthSessionTest.php

+22
Original file line numberDiff line numberDiff line change
@@ -141,3 +141,25 @@
141141
sleep(2);
142142
expect($auth::status())->toBeFalse();
143143
});
144+
145+
test('Session lifetime should set correct session ttl when string is configured instead of timestamp', function () {
146+
$auth = new \Leaf\Auth();
147+
$auth::config(getAuthConfig(['SESSION_LIFETIME' => '1 day']));
148+
$auth::login(['username' => 'login-user', 'password' => 'login-pass']);
149+
150+
expect($auth::status())->not()->toBeNull();
151+
152+
$timestampOneDay = 60 * 60 * 24;
153+
$session = new \Leaf\Http\Session(false);
154+
$sessionTtl = $session->get('SESSION_TTL');
155+
156+
expect($sessionTtl)->toBe(time() + $timestampOneDay);
157+
});
158+
159+
test('Login should throw error when lifetime string is invalid', function () {
160+
$auth = new \Leaf\Auth();
161+
$auth::config(getAuthConfig(['SESSION_LIFETIME' => 'invalid string']));
162+
163+
expect(fn() => $auth::login(['username' => 'login-user', 'password' => 'login-pass']))
164+
->toThrow(Exception::class, 'Provided string could not be converted to time');
165+
});

0 commit comments

Comments
 (0)