Implement token refresh
This commit is contained in:
parent
22db125fe6
commit
f7d69d7f04
@ -2,13 +2,18 @@
|
||||
|
||||
namespace Intuit\Providers\Socialite;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use GuzzleHttp\RequestOptions;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Laravel\Passport\Exceptions\InvalidAuthTokenException;
|
||||
use Laravel\Socialite\Two\InvalidStateException;
|
||||
use Laravel\Socialite\Two\ProviderInterface;
|
||||
use Laravel\Socialite\Two\AbstractProvider;
|
||||
use Laravel\Socialite\Two\User as SocialUser;
|
||||
|
||||
use App\Models\{ProviderOauth,ProviderToken};
|
||||
|
||||
class IntuitProvider extends AbstractProvider implements ProviderInterface
|
||||
{
|
||||
private const hosts = [
|
||||
@ -79,4 +84,54 @@ class IntuitProvider extends AbstractProvider implements ProviderInterface
|
||||
->setRefreshToken(Arr::get($details,'refresh_token'))
|
||||
->setExpiresIn(Arr::get($details,'expires_in'));
|
||||
}
|
||||
|
||||
/* METHODS */
|
||||
|
||||
public function getAuthorisationHeader(ProviderOauth $po): array
|
||||
{
|
||||
return [
|
||||
'Accept' => 'application/json',
|
||||
'Authorization' => sprintf('Basic %s',base64_encode($this->clientId.':'.$this->clientSecret)),
|
||||
'Content-Type' => 'application/x-www-form-urlencoded'
|
||||
];
|
||||
}
|
||||
|
||||
public function getRefreshTokenFields(string $refreshtoken): array
|
||||
{
|
||||
return [
|
||||
'grant_type' => 'refresh_token',
|
||||
'refresh_token' => $refreshtoken,
|
||||
];
|
||||
}
|
||||
|
||||
public function refreshtoken(ProviderToken $to): bool
|
||||
{
|
||||
$response = $this->getHttpClient()->post($this->getTokenUrl(), [
|
||||
RequestOptions::HEADERS => $this->getAuthorisationHeader($to->provider),
|
||||
RequestOptions::FORM_PARAMS => $this->getRefreshTokenFields($to->refresh_token),
|
||||
]);
|
||||
|
||||
switch ($response->getStatusCode()) {
|
||||
case '200':
|
||||
$body = json_decode($response->getBody(), true);
|
||||
|
||||
if (Arr::get($body,'token_type') !== 'bearer')
|
||||
throw new InvalidAuthTokenException(sprintf('Invalid response [%d] didnt get a bearer token for [%s] (%s)',$response->getStatusCode(),$to->user->email,$body));
|
||||
|
||||
$to->access_token = Arr::get($body,'access_token');
|
||||
$to->access_token_expires_at = Carbon::now()->addSeconds(Arr::get($body,'expires_in'));
|
||||
|
||||
// If the refresh token changed
|
||||
if (($x=Arr::get($body,'refresh_token')) !== $to->refresh_token) {
|
||||
$to->refresh_token = $x;
|
||||
$to->refresh_token_expires_at = Carbon::now()->addSeconds(Arr::get($body,'x_refresh_token_expires_in'));
|
||||
}
|
||||
$to->save();
|
||||
|
||||
return TRUE;
|
||||
|
||||
default:
|
||||
throw new InvalidAuthTokenException(sprintf('Invalid response [%d] refreshing token for [%s] (%s)',$response->getStatusCode(),$to->user->email,$response->getBody()));
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user