]> git.ekhem.eu.org Git - gdrive_knife.git/commitdiff
Catch RefreshError and obtain a new token.
authorJakub Czajka <jakub@ekhem.eu.org>
Wed, 29 Nov 2023 22:18:14 +0000 (23:18 +0100)
committerJakub Czajka <jakub@ekhem.eu.org>
Wed, 29 Nov 2023 22:18:14 +0000 (23:18 +0100)
RefreshError has been expired or revoked.

gdrive_knife.py

index 048986c511400ea0af88162cea0b75ca94c85fac..0e12c6675b9c8bd14fdf5e7490826105c9af9a40 100644 (file)
@@ -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())