Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james2doyle/65033d0ee7968b4b4c5724fed484d90c to your computer and use it in GitHub Desktop.
Save james2doyle/65033d0ee7968b4b4c5724fed484d90c to your computer and use it in GitHub Desktop.
A Laravel Artisan command to get an auth token from a User using UUID or email of that user. Validates UUID or email. Handy for testing authentication with Postman or CLI
<?php
declare(strict_types=1);
use App\Models\User;
use Illuminate\Support\Facades\Artisan;
use Ramsey\Uuid\Rfc4122\Validator;
/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/
Artisan::command('user-token {emailOrId}', function (string $emailOrId): void {
$validator = new Validator();
$isUuid = $validator->validate($emailOrId);
$user = User::where($isUuid ? 'id' : 'email', $emailOrId)->firstOrFail();
$token = $user->createToken('default')->plainTextToken;
/**
* @psalm-suppress InvalidScope
*/
$this->comment(sprintf('Authorization bearer token for %s is now "%s"', $user->email, $token));
})->purpose('Display a valid token for the given user');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment