php-samples icon indicating copy to clipboard operation
php-samples copied to clipboard

Command-line / Offline app token token keeps expiring even though there's refresh token

Open lordspace opened this issue 6 years ago • 0 comments

I think i found a bug in : https://github.com/gsuitedevs/php-samples/blob/master/drive/quickstart/quickstart.php

Sample: https://youtu.be/NMGaXlq0qAk

Expected Behavior

the token to auto renew

Actual Behavior

the token doesn't renew and I am prompted for auth url again

Steps to Reproduce the Problem

run the example https://github.com/gsuitedevs/php-samples/blob/master/drive/quickstart/quickstart.php

Specifications

Windows 10 Home/ 64

C:\Users\User>php -v PHP 7.2.22 (cli) (built: Aug 28 2019 09:29:01) ( ZTS MSVC15 (Visual C++ 2017) x64 ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies with Xdebug v2.7.2, Copyright (c) 2002-2019, by Derick Rethans

Code example (fix)

			$renewed = 0;

			// Refresh the token if possible, else fetch a new one.
			if ( $client->getRefreshToken() ) {
				$client->fetchAccessTokenWithRefreshToken( $client->getRefreshToken() );
				$renewed = 1;
			} else {
				// Request authorization from the user.
				$authUrl = $client->createAuthUrl();
				printf( "Open the following link in your browser:\n%s\n", $authUrl );
				print 'Enter verification code: ';
				$authCode = trim( fgets( STDIN ) );

				// Exchange authorization code for an access token.
				$accessToken = $client->fetchAccessTokenWithAuthCode( $authCode );
				$client->setAccessToken( $accessToken );

				// Check to see if there was an error.
				if ( array_key_exists( 'error', $accessToken ) ) {
					throw new Exception( join( ', ', $accessToken ) );
				}
			}

			if (! $renewed) {
				// Save the token to a file.
				if ( ! file_exists( dirname( $tokenPath ) ) ) {
					$mkdir_res = mkdir( dirname( $tokenPath ), 0700, true );

					if ( empty( $mkdir_res ) ) {
						throw new Exception( "Cannot create parent directory for file: " . $tokenPath );
					}
				}

				$save_res = file_put_contents( $tokenPath, json_encode( $client->getAccessToken() ), LOCK_EX );

				if ( empty( $save_res ) ) {
					throw new Exception( "Cannot save file: " . $tokenPath );
				}
			}

lordspace avatar Sep 21 '19 09:09 lordspace