Skip to content

Commit

Permalink
optimize auth requests
Browse files Browse the repository at this point in the history
increases the performance of HTTP requests requiring sanctum authentication
  • Loading branch information
k2so-dev committed Aug 24, 2024
1 parent f163cc8 commit ba1a43f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
30 changes: 30 additions & 0 deletions app/Models/PersonalAccessToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace App\Models;

use Laravel\Sanctum\PersonalAccessToken as SanctumPersonalAccessToken;

class PersonalAccessToken extends SanctumPersonalAccessToken
{
/**
* @param array $options
* @return void
*/
public function save(array $options = []): void
{
$changes = $this->getDirty();

/**
* Update the last_used_at field no more than 1 time per minute.
* This change increases the performance of HTTP requests requiring sanctum authentication.
*/
if (
!array_key_exists('last_used_at', $changes) ||
count($changes) > 1 ||
!$this->getOriginal('last_used_at') ||
$this->getOriginal('last_used_at') < now()->parse($changes['last_used_at'])->subMinute()
) {
parent::save();
}
}
}
6 changes: 6 additions & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Providers;

use App\Helpers\Image;
use App\Models\PersonalAccessToken;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Auth\Notifications\VerifyEmail;
Expand All @@ -13,6 +14,7 @@
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Laravel\Sanctum\Sanctum;

class AppServiceProvider extends ServiceProvider
{
Expand Down Expand Up @@ -108,5 +110,9 @@ public function boot(): void
trim(implode(' ', [$device->getClient('name'), $device->getClient('version')])),
])) ?? 'Unknown';
});

Sanctum::usePersonalAccessTokenModel(
PersonalAccessToken::class
);
}
}

0 comments on commit ba1a43f

Please sign in to comment.