add command to clean token

This commit is contained in:
Jethro Lin 2024-12-04 12:55:07 +08:00
parent ae4ef60215
commit ae5a7662ca
2 changed files with 63 additions and 0 deletions

View file

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use App\Models\AuthToken;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class CleanupExpiredTokens extends Command
{
protected $signature = 'auth:cleanup-expired-tokens';
protected $description = 'Clean up expired auth tokens from the database';
public function handle(): void
{
try {
$count = AuthToken::where('expires_at', '<', now())->delete();
if ($count > 0) {
Log::info("Cleaned up {$count} expired auth tokens");
$this->info("Successfully cleaned up {$count} expired auth tokens.");
} else {
$this->info('No expired auth tokens found.');
}
} catch (\Exception $e) {
Log::error('Error cleaning up expired auth tokens', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
$this->error('Failed to clean up expired auth tokens.');
}
}
}

28
app/Console/Kernel.php Normal file
View file

@ -0,0 +1,28 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
// Clean up expired auth tokens daily
$schedule->command('auth:cleanup-expired-tokens')->daily();
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}