Skip to content

Commit 92156a7

Browse files
committed
feat: prevent logged in user tries to login again
If a logged-in user logs in with a different user account, the session data of the previous user is carried over.
1 parent b78990e commit 92156a7

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/Authentication/Authenticators/Session.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,20 @@ private function checkRememberMeToken(string $remember)
527527
*/
528528
public function startLogin(User $user): void
529529
{
530+
/** @var int|string|null $userId */
531+
$userId = $this->getSessionKey('id');
532+
533+
// Check if already logged in.
534+
if ($userId !== null) {
535+
throw new LogicException(
536+
'The user has User Info in Session, so already logged in or in pending login state.'
537+
. ' If a logged in user logs in again with other account, the session data of the previous'
538+
. ' user will be used as the new user.'
539+
. ' Fix your code to prevent users from logging in without logging out or delete the session data.'
540+
. ' user_id: ' . $userId
541+
);
542+
}
543+
530544
$this->user = $user;
531545

532546
// Regenerate the session ID to help protect against session fixation

tests/Authentication/Authenticators/SessionAuthenticatorTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use CodeIgniter\Shield\Authentication\Authenticators\Session;
88
use CodeIgniter\Shield\Config\Auth;
99
use CodeIgniter\Shield\Entities\User;
10+
use CodeIgniter\Shield\Exceptions\LogicException;
1011
use CodeIgniter\Shield\Models\RememberModel;
1112
use CodeIgniter\Shield\Models\UserModel;
1213
use CodeIgniter\Shield\Result;
@@ -292,6 +293,26 @@ public function testAttemptSuccess(): void
292293
]);
293294
}
294295

296+
public function testAttemptUserHavingSessionDataAttemptsAgain(): void
297+
{
298+
$_SESSION['user']['id'] = '999';
299+
300+
$this->expectException(LogicException::class);
301+
$this->expectExceptionMessage(
302+
'The user has User Info in Session, so already logged in or in pending login state.'
303+
);
304+
305+
$this->user->createEmailIdentity([
306+
'email' => '[email protected]',
307+
'password' => 'secret123',
308+
]);
309+
310+
$result = $this->auth->attempt([
311+
'email' => $this->user->email,
312+
'password' => 'secret123',
313+
]);
314+
}
315+
295316
public function testAttemptCaseInsensitive(): void
296317
{
297318
$this->user->createEmailIdentity([

0 commit comments

Comments
 (0)