Skip to content

Commit

Permalink
Fix cases where user returned by Auth facade was null (using authenti…
Browse files Browse the repository at this point in the history
…catable model from Authenticated and TokenAuthenticated events)
  • Loading branch information
alajusticia committed Oct 25, 2024
1 parent 8b3d557 commit 9f380a6
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 9 deletions.
17 changes: 10 additions & 7 deletions src/CurrentLogin.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace ALajusticia\Logins;

use ALajusticia\Logins\Models\Login;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;

Expand All @@ -15,19 +16,21 @@ public function __construct()
$this->loadCurrentLogin();
}

public function loadCurrentLogin(): void
public function loadCurrentLogin(?Authenticatable $user = null): void
{
if (Auth::user() && Logins::tracked(Auth::user()) && ! $this->currentLogin) {
if (Auth::user()->isAuthenticatedBySession()) {
$user = $user ?? Auth::user();

$this->currentLogin = Auth::user()->logins()
if ($user && Logins::tracked($user) && ! $this->currentLogin) {
if ($user->isAuthenticatedBySession()) {

$this->currentLogin = $user->logins()
->where('session_id', session()->getId())
->first();

} elseif (Config::get('logins.sanctum_token_tracking') && Auth::user()->isAuthenticatedBySanctumToken()) {
} elseif (Config::get('logins.sanctum_token_tracking') && $user->isAuthenticatedBySanctumToken()) {

$this->currentLogin = Auth::user()->logins()
->where('personal_access_token_id', Auth::user()->currentAccessToken()->getKey())
$this->currentLogin = $user->logins()
->where('personal_access_token_id', $user->currentAccessToken()->getKey())
->first();

}
Expand Down
2 changes: 1 addition & 1 deletion src/Listeners/SanctumEventSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class SanctumEventSubscriber
public function handlePersonalAccessTokenAuthentication(TokenAuthenticated $event): void
{
if (Logins::tracked($event->token->tokenable)) {
app(CurrentLogin::class)->loadCurrentLogin();
app(CurrentLogin::class)->loadCurrentLogin($event->token->tokenable);

Logins::updateLastActivity();
}
Expand Down
2 changes: 1 addition & 1 deletion src/Logins.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public static function checkSessionId($user)
}
}

app(CurrentLogin::class)->loadCurrentLogin();
app(CurrentLogin::class)->loadCurrentLogin($user);

if ($updated === 0) {
self::updateLastActivity();
Expand Down

0 comments on commit 9f380a6

Please sign in to comment.