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
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:
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())