2022-06-28 22:04:39 -07:00
< ? php
namespace App\Console\Commands ;
use App\Helpers\Helper ;
use Illuminate\Console\Command ;
use App\Models\User ;
use Laravel\Passport\TokenRepository ;
use Illuminate\Contracts\Validation\Factory as ValidationFactory ;
2022-06-28 23:13:25 -07:00
use DB ;
2022-06-28 22:04:39 -07:00
class GeneratePersonalAccessToken extends Command
{
/**
* The name and signature of the console command .
*
* @ var string
*/
protected $signature = ' snipeit : make - api - key
2022-06-28 22:26:37 -07:00
{ -- user_id = : The ID of the user to create the token for . }
2022-06-28 22:04:39 -07:00
{ -- name = : The name of the new API token }
2022-06-28 22:20:55 -07:00
{ -- key - only : Only return the value of the API key } ' ;
2022-06-28 22:04:39 -07:00
/**
* The console command description .
*
* @ var string
*/
2022-06-28 22:20:55 -07:00
protected $description = 'This console command allows you to generate Personal API tokens to be used with the Snipe-IT JSON REST API on behalf of a user.' ;
2022-06-28 22:04:39 -07:00
/**
* The token repository implementation .
*
* @ var \Laravel\Passport\TokenRepository
*/
protected $tokenRepository ;
/**
* Create a new command instance .
*
* @ return void
*/
public function __construct ( TokenRepository $tokenRepository , ValidationFactory $validation )
{
$this -> validation = $validation ;
$this -> tokenRepository = $tokenRepository ;
parent :: __construct ();
}
/**
* Execute the console command .
*
* @ return int
*/
public function handle ()
{
2022-06-28 22:11:46 -07:00
$accessTokenName = $this -> option ( 'name' );
if ( $accessTokenName == '' ) {
2022-06-28 22:04:39 -07:00
$accessTokenName = 'CLI Auth Token' ;
}
2022-06-28 22:26:37 -07:00
if ( $this -> option ( 'user_id' ) == '' ) {
return $this -> error ( 'ERROR: user_id cannot be blank.' );
2022-06-28 22:04:39 -07:00
}
2022-06-28 22:26:37 -07:00
if ( $user = User :: find ( $this -> option ( 'user_id' ))) {
2022-06-28 22:04:39 -07:00
2022-06-28 22:20:55 -07:00
if ( $this -> option ( 'key-only' )) {
2022-06-28 22:04:39 -07:00
$this -> info ( $user -> createToken ( $accessTokenName ) -> accessToken );
} else {
2022-06-28 23:13:25 -07:00
$token = DB :: table ( 'oauth_access_tokens' ) -> where ( 'user_id' , '=' , $user -> id ) -> where ( 'name' , '=' , $accessTokenName ) -> orderBy ( 'created_at' , 'desc' ) -> first ();
2022-06-28 22:04:39 -07:00
$this -> warn ( 'Your API Token has been created. Be sure to copy this token now, as it will not be accessible again.' );
2022-06-28 23:13:25 -07:00
$this -> info ( 'API Token ID: ' . $token -> id );
2022-06-28 22:06:46 -07:00
$this -> info ( 'API Token User: ' . $user -> present () -> fullName . ' (' . $user -> username . ')' );
2022-06-28 22:04:39 -07:00
$this -> info ( 'API Token Name: ' . $accessTokenName );
$this -> info ( 'API Token: ' . $user -> createToken ( $accessTokenName ) -> accessToken );
}
} else {
return $this -> error ( 'ERROR: Invalid user. API key was not created.' );
}
}
}