105 lines
2.5 KiB
PHP
105 lines
2.5 KiB
PHP
<?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, copy this as you won\'t be able to see it again.');
|
|
$this->info($tokenString);
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|
|
}
|