Last active
December 26, 2017 08:13
-
-
Save dickwu/6838e01e7c8dec3e3efdfa0efaa843ab to your computer and use it in GitHub Desktop.
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
use App\Models\User; | |
use Carbon\Carbon; | |
use Illuminate\Events\Dispatcher; | |
use Laravel\Passport\Bridge\AccessTokenRepository; | |
use Laravel\Passport\Bridge\Client; | |
use Laravel\Passport\Bridge\Scope; | |
use Laravel\Passport\TokenRepository; | |
use League\OAuth2\Server\CryptKey; | |
use Laravel\Passport\Bridge\AccessToken; | |
/** | |
* Get custom Token from Passpord | |
* @param User $user | |
* @param int $expireTime | |
* @return array | |
*/ | |
function getToken(User $user,int $expireTime = 3600){ | |
$token = new AccessToken($user->id); | |
$token->setIdentifier(generateUniqueIdentifier()); | |
$token->setClient(new Client(2, null, null)); | |
$token->setExpiryDateTime(Carbon::now()->addSeconds($expireTime)); | |
$token->addScope(new Scope('activity')); | |
$privateKey = new CryptKey('file://'.storage_path('oauth-private.key')); | |
$accessTokenRepository = new AccessTokenRepository(new TokenRepository, new Dispatcher); | |
$accessTokenRepository->persistNewAccessToken($token); | |
$jwtAccessToken = $token->convertToJWT($privateKey); | |
$user_arr = $user->toArray(); | |
/* | |
* Add params to $user_arr | |
*/ | |
return [ | |
'token_type' => 'Bearer', | |
'expires_in' => $expireTime, | |
'access_token' => (string) $jwtAccessToken, | |
'user' => $user_arr | |
]; | |
} | |
/** | |
* Get unique Token Id | |
* @param int $length | |
* @return string | |
*/ | |
function generateUniqueIdentifier($length = 40) | |
{ | |
try { | |
$id = bin2hex(random_bytes($length)); | |
if(DB::table('oauth_access_tokens')->where('id',$id)->exists()){ | |
return $this->generateUniqueIdentifier($length); | |
} | |
return $id; | |
}catch (\Exception $e) { | |
return $this->generateUniqueIdentifier($length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment