From ba1e1dfea21c582f3470d20d58f323c446dbc77e Mon Sep 17 00:00:00 2001 From: Jakub Czajka Date: Wed, 29 Nov 2023 23:18:14 +0100 Subject: [PATCH] Catch RefreshError and obtain a new token. RefreshError has been expired or revoked. --- gdrive_knife.py | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/gdrive_knife.py b/gdrive_knife.py index 048986c..0e12c66 100644 --- a/gdrive_knife.py +++ b/gdrive_knife.py @@ -14,6 +14,7 @@ import zipfile from apiclient.http import MediaFileUpload from cryptography.fernet import Fernet from google.auth.transport.requests import Request +from google.auth.exceptions import RefreshError from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import Flow from googleapiclient.discovery import build @@ -147,6 +148,7 @@ class auth_server(): def auth(args): creds = None + write_token_to_file = False if os.path.exists(args.token): print(f'{args.token} exists. Trying to authenticate with it.') try: @@ -156,18 +158,23 @@ def auth(args): print(f'{args.token} is malformed. Reset permissions at ' 'https://myaccount.google.com/permissions and retry.') sys.exit(1) - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - print(f'{args.token} has expired. Refreshing.') + if creds and creds.expired and creds.refresh_token: + print(f'{args.token} has expired. Refreshing.') + try: creds.refresh(Request()) - else: - print(f'{args.token} does not exist. Obtaining a new token.') - flow = Flow.from_client_secrets_file(args.credentials, scopes=SCOPES, - redirect_uri=args.on_token) - # Run the server on localhost because wsgi does not use HTTPS. - auth_server(flow, args.on_success).handle_one_on('localhost', - args.port) - creds = flow.credentials + write_token_to_file = True + except RefreshError: + print(f'Could not refresh an invalid token. Obtaining a new one.') + os.remove(args.token) + if not creds or not creds.valid: + print(f'{args.token} does not exist. Obtaining a new token.') + flow = Flow.from_client_secrets_file(args.credentials, scopes=SCOPES, + redirect_uri=args.on_token) + # Run the server on localhost because wsgi does not use HTTPS. + auth_server(flow, args.on_success).handle_one_on('localhost', args.port) + creds = flow.credentials + write_token_to_file = True + if write_token_to_file: print(f'Writing new token to {args.token}.') with open(args.token, 'w') as token: token.write(creds.to_json()) -- 2.39.5