Skip to content

Commit 00023ee

Browse files
authored
Merge pull request #216 from kenjis/prevent-logged-in-user-login-again
feat: prevent logged-in users from trying to log in again
2 parents 8b4984f + 9c7b36a commit 00023ee

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
@@ -550,6 +550,20 @@ private function checkRememberMeToken(string $remember)
550550
*/
551551
public function startLogin(User $user): void
552552
{
553+
/** @var int|string|null $userId */
554+
$userId = $this->getSessionKey('id');
555+
556+
// Check if already logged in.
557+
if ($userId !== null) {
558+
throw new LogicException(
559+
'The user has User Info in Session, so already logged in or in pending login state.'
560+
. ' If a logged in user logs in again with other account, the session data of the previous'
561+
. ' user will be used as the new user.'
562+
. ' Fix your code to prevent users from logging in without logging out or delete the session data.'
563+
. ' user_id: ' . $userId
564+
);
565+
}
566+
553567
$this->user = $user;
554568

555569
// 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;
@@ -340,6 +341,26 @@ public function testAttemptSuccess(): void
340341
]);
341342
}
342343

344+
public function testAttemptUserHavingSessionDataAttemptsAgain(): void
345+
{
346+
$_SESSION['user']['id'] = '999';
347+
348+
$this->expectException(LogicException::class);
349+
$this->expectExceptionMessage(
350+
'The user has User Info in Session, so already logged in or in pending login state.'
351+
);
352+
353+
$this->user->createEmailIdentity([
354+
'email' => 'foo@example.com',
355+
'password' => 'secret123',
356+
]);
357+
358+
$this->auth->attempt([
359+
'email' => $this->user->email,
360+
'password' => 'secret123',
361+
]);
362+
}
363+
343364
public function testAttemptCaseInsensitive(): void
344365
{
345366
$this->user->createEmailIdentity([

0 commit comments

Comments
 (0)