Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2.x] Add sanctum:prune-expired command for removing expired tokens. #348

Merged
merged 3 commits into from
Mar 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"require": {
"php": "^7.2|^8.0",
"ext-json": "*",
"illuminate/console": "^6.9|^7.0|^8.0|^9.0",
"illuminate/contracts": "^6.9|^7.0|^8.0|^9.0",
"illuminate/database": "^6.9|^7.0|^8.0|^9.0",
"illuminate/support": "^6.9|^7.0|^8.0|^9.0"
Expand Down
43 changes: 43 additions & 0 deletions src/Console/Commands/PruneExpired.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Laravel\Sanctum\Console\Commands;

use Illuminate\Console\Command;
use Laravel\Sanctum\Sanctum;

class PruneExpired extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sanctum:prune-expired {--hours=24 : The number of hours to retain expired Sanctum tokens}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Prune tokens expired for more than specified number of hours.';

/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
if ($expiration = config('sanctum.expiration')) {
$model = Sanctum::$personalAccessTokenModel;

$hours = $this->option('hours');

$model::where('created_at', '<', now()->subMinutes($expiration + ($hours * 60)))->delete();

$this->info("Tokens expired for more than {$hours} hours pruned successfully.");
}

$this->warn('Expiration value not specified in configuration file.');
}
}
5 changes: 5 additions & 0 deletions src/SanctumServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Laravel\Sanctum\Console\Commands\PruneExpired;
use Laravel\Sanctum\Http\Controllers\CsrfCookieController;
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

Expand Down Expand Up @@ -48,6 +49,10 @@ public function boot()
$this->publishes([
__DIR__.'/../config/sanctum.php' => config_path('sanctum.php'),
], 'sanctum-config');

$this->commands([
PruneExpired::class,
]);
}

$this->defineRoutes();
Expand Down
108 changes: 108 additions & 0 deletions tests/PruneExpiredTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
<?php

namespace Laravel\Sanctum\Tests;

use Illuminate\Foundation\Auth\User;
use Laravel\Sanctum\Contracts\HasApiTokens as HasApiTokensContract;
use Laravel\Sanctum\HasApiTokens;
use Laravel\Sanctum\PersonalAccessToken;
use Laravel\Sanctum\SanctumServiceProvider;
use Orchestra\Testbench\TestCase;

class PruneExpiredTest extends TestCase
{
protected function getEnvironmentSetUp($app)
{
$app['config']->set('database.default', 'testbench');

$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
}

public function test_can_delete_expired_tokens_with_integer_expiration()
{
$this->loadLaravelMigrations(['--database' => 'testbench']);
$this->artisan('migrate', ['--database' => 'testbench'])->run();

config(['sanctum.expiration' => 60]);

$user = UserForPruneExpiredTest::forceCreate([
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
]);

$token_1 = PersonalAccessToken::forceCreate([
'tokenable_id' => $user->id,
'tokenable_type' => get_class($user),
'name' => 'Test_1',
'token' => hash('sha256', 'test_1'),
'created_at' => now()->subMinutes(181),
]);

$token_2 = PersonalAccessToken::forceCreate([
'tokenable_id' => $user->id,
'tokenable_type' => get_class($user),
'name' => 'Test_2',
'token' => hash('sha256', 'test_2'),
'created_at' => now()->subMinutes(179),
]);

$token_3 = PersonalAccessToken::forceCreate([
'tokenable_id' => $user->id,
'tokenable_type' => get_class($user),
'name' => 'Test_3',
'token' => hash('sha256', 'test_3'),
'created_at' => now()->subMinutes(121),
]);

$this->artisan('sanctum:prune-expired --hours=2')
->expectsOutput('Tokens expired for more than 2 hours pruned successfully.');

$this->assertDatabaseMissing('personal_access_tokens', ['name' => 'Test_1']);
$this->assertDatabaseHas('personal_access_tokens', ['name' => 'Test_2']);
$this->assertDatabaseHas('personal_access_tokens', ['name' => 'Test_3']);
}

public function test_cant_delete_expired_tokens_with_null_expiration()
{
$this->loadLaravelMigrations(['--database' => 'testbench']);
$this->artisan('migrate', ['--database' => 'testbench'])->run();

config(['sanctum.expiration' => null]);

$user = UserForPruneExpiredTest::forceCreate([
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
]);

$token = PersonalAccessToken::forceCreate([
'tokenable_id' => $user->id,
'tokenable_type' => get_class($user),
'name' => 'Test',
'token' => hash('sha256', 'test'),
'created_at' => now()->subMinutes(70),
]);

$this->artisan('sanctum:prune-expired --hours=2')
->expectsOutput('Expiration value not specified in configuration file.');

$this->assertDatabaseHas('personal_access_tokens', ['name' => 'Test']);
}

protected function getPackageProviders($app)
{
return [SanctumServiceProvider::class];
}
}

class UserForPruneExpiredTest extends User implements HasApiTokensContract
{
use HasApiTokens;

protected $table = 'users';
}