Add console command
This commit is contained in:
parent
bc44418152
commit
1733f2cbc9
103
app/Console/Commands/AuthTokenCommand.php
Normal file
103
app/Console/Commands/AuthTokenCommand.php
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user