mercredi 27 septembre 2023

Why do Refresh Token expires after every 7 days ? Does it affects the file upload on production

I implemented a Laravel web-app with Google Drive's API used for storage. I used this tutorial https://gist.github.com/sergomet/f234cc7a8351352170eb547cccd65011. When i am trying to upload file on google drive i am facing the issue of refresh token expiration every 7 days .So if refresh token is being expired it affects the file upload on google drive I need to deploy on production.

I tried with this code, moral of the story is that whether access token expires or refresh token expires , while file upload flow should not give error

public function uploadFile(UploadedFile $uploadedFile, string $file,string $folderId)
    {
        $client = new Google_Client();
        $client->setClientId(env('GOOGLE_DRIVE_CLIENT_ID'));
       $client->setClientSecret(env('GOOGLE_DRIVE_CLIENT_SECRET'));
       $client->refreshToken(env('GOOGLE_DRIVE_REFRESH_TOKEN'));
        $this->refreshTokenIfNeeded($client);
        $fileName = $uploadedFile->getClientOriginalName();
        $mimeType = $uploadedFile->getClientMimeType();
        $fileContent = file_get_contents($uploadedFile);
        $fileMetadata = new Google_Service_Drive_DriveFile(array(
            'name' => $fileName,
            'parents' => array($folderId)
        ));
        //file upload code
}
 public function refreshTokenIfNeeded(Google_Client $client): void
    {

        if ($client->isAccessTokenExpired()) {
          $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
           $newAccessToken = $client->getAccessToken();
            $this->saveAccessTokenToStorage($newAccessToken);
    }
 else {
            $oldAccessToken = $client->getAccessToken();
            $this->saveAccessTokenToStorage($oldAccessToken);
        }
    }

    public function saveAccessTokenToStorage($newAccessToken): void
   {
       $accessTokenJson = json_encode($newAccessToken);
        $credentialsFilePath = env('GOOGLE_CREDENTIALS_FILE');
       Storage::put("$credentialsFilePath", $accessTokenJson);
    }
}


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/dVLKeEx
via IFTTT

Aucun commentaire:

Enregistrer un commentaire