Last active
May 16, 2022 17:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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