Skip to content

Commit

Permalink
Merge pull request #216 from kenjis/prevent-logged-in-user-login-again
Browse files Browse the repository at this point in the history
feat: prevent logged-in users from trying to log in again
  • Loading branch information
kenjis authored Jun 11, 2022
2 parents 8b4984f + 9c7b36a commit 00023ee
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Authentication/Authenticators/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,20 @@ private function checkRememberMeToken(string $remember)
*/
public function startLogin(User $user): void
{
/** @var int|string|null $userId */
$userId = $this->getSessionKey('id');

// Check if already logged in.
if ($userId !== null) {
throw new LogicException(
'The user has User Info in Session, so already logged in or in pending login state.'
. ' If a logged in user logs in again with other account, the session data of the previous'
. ' user will be used as the new user.'
. ' Fix your code to prevent users from logging in without logging out or delete the session data.'
. ' user_id: ' . $userId
);
}

$this->user = $user;

// Regenerate the session ID to help protect against session fixation
Expand Down
21 changes: 21 additions & 0 deletions tests/Authentication/Authenticators/SessionAuthenticatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Config\Auth;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Exceptions\LogicException;
use CodeIgniter\Shield\Models\RememberModel;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Shield\Result;
Expand Down Expand Up @@ -340,6 +341,26 @@ public function testAttemptSuccess(): void
]);
}

public function testAttemptUserHavingSessionDataAttemptsAgain(): void
{
$_SESSION['user']['id'] = '999';

$this->expectException(LogicException::class);
$this->expectExceptionMessage(
'The user has User Info in Session, so already logged in or in pending login state.'
);

$this->user->createEmailIdentity([
'email' => 'foo@example.com',
'password' => 'secret123',
]);

$this->auth->attempt([
'email' => $this->user->email,
'password' => 'secret123',
]);
}

public function testAttemptCaseInsensitive(): void
{
$this->user->createEmailIdentity([
Expand Down

0 comments on commit 00023ee

Please sign in to comment.