From: Carl Worth Date: Sat, 17 Oct 2020 14:48:29 +0000 (-0700) Subject: gsheets-authenticate: Change to using base64 to encode the pickled token X-Git-Url: https://git.cworth.org/git?a=commitdiff_plain;h=879b8581e5abc91c87ef8a537dac158f3ac04cf4;p=turbot gsheets-authenticate: Change to using base64 to encode the pickled token This allows the final token to be used in places where arbitrary binary data cannot be (such as an environment variable, etc.). --- diff --git a/.gitignore b/.gitignore index 4bbd199..0ed8177 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ turbot.wsgi .slack-creds.env .gsheets-creds.json -.gsheets-token.pickle +.gsheets-pickle.base64 __pycache__ diff --git a/gsheets-authenticate.py b/gsheets-authenticate.py index 0fddf67..2d0a609 100755 --- a/gsheets-authenticate.py +++ b/gsheets-authenticate.py @@ -1,14 +1,15 @@ #!/usr/bin/env python3 import pickle +import base64 import os.path from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request -# If modifying these scopes, delete the file token.pickle. -SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] +TOKEN_FILE = ".gsheets-pickle.base64" -TOKEN_FILE = ".gsheets-token.pickle" +# If modifying these scopes, delete the token file +SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] def main(): """Allows user to authenticate for the Sheets API. @@ -20,22 +21,28 @@ def main(): # created automatically when the authorization flow completes for the first # time. if os.path.exists(TOKEN_FILE): - with open(TOKEN_FILE, 'rb') as token: - creds = pickle.load(token) + with open(TOKEN_FILE, 'rb') as token_file: + creds_base64 = token_file.read() + creds_pickle = base64.b64decode(creds_base64) + creds = pickle.loads(creds_pickle) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: + print("Token seems to have expired. Refreshing.") creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) + '.gsheets-creds.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run - with open(TOKEN_FILE, 'wb') as token: - pickle.dump(creds, token) - - print("Token now saved in {}".format(TOKEN_FILE)) + with open(TOKEN_FILE, 'wb') as token_file: + creds_pickle = pickle.dumps(creds) + creds_base64 = base64.b64encode(creds_pickle) + token_file.write(creds_base64) + print("Token now saved in {}".format(TOKEN_FILE)) + else: + print("Valid token in {} left unchanged.".format(TOKEN_FILE)) if __name__ == '__main__': main()