Add console command

This commit is contained in:
Daniel_I_Am 2020-08-29 14:37:50 +02:00
parent bc44418152
commit 1733f2cbc9
No known key found for this signature in database
GPG Key ID: 80C428FCC9743E84

View File

@ -0,0 +1,103 @@
<?php
namespace App\Console\Commands;
use App\AuthToken;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
class AuthTokenCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'chaosbot:token';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Helper function for API tokens';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
while (true) {
$option = $this->choice('Subcommand', ['list', 'create', 'revoke', 'exit']);
switch ($option) {
case 'list':
$this->listTokens();
break;
case 'create':
$this->createToken();
break;
case 'revoke':
$this->revokeToken();
break;
case 'exit':
break 2;
}
}
return 0;
}
private function listTokens() {
$tokens = AuthToken::all(['name']);
if (sizeof($tokens) == 0) {
$this->info("No tokens found");
} else {
$this->table(["Token Name"], $tokens);
}
}
private function createToken() {
$tokens = AuthToken::all();
$name = $this->ask('name');
if ($tokens->where('name', $name)->first() !== null) {
$this->error('There\'s already a token by that name');
return;
}
$tokenString = Str::random(config('chaosapi.token-length', 60));
AuthToken::create([
'name' => $name,
'token' => $tokenString
]);
$this->info('Token created');
}
private function revokeToken() {
$tokens = AuthToken::all();
$name = $this->anticipate('Name?', $tokens->pluck('name')->toArray());
$token = $tokens->where('name', $name)->first();
if ($token === null) {
$this->warn('There\'s no token authorized by that name');
} else {
$this->info('Token \''.$name.'\' revoked');
$token->delete();
}
}
}