]> git.cworth.org Git - turbot/commitdiff
gsheets-authenticate: Change to using base64 to encode the pickled token
authorCarl Worth <cworth@cworth.org>
Sat, 17 Oct 2020 14:48:29 +0000 (07:48 -0700)
committerCarl Worth <cworth@cworth.org>
Mon, 19 Oct 2020 21:43:17 +0000 (14:43 -0700)
This allows the final token to be used in places where arbitrary
binary data cannot be (such as an environment variable, etc.).

.gitignore
gsheets-authenticate.py

index 4bbd19965276f14e4abba950fa095bb00a513ce0..0ed8177b3f8cc4277a4278474c5e60c7dbf253ad 100644 (file)
@@ -1,5 +1,5 @@
 turbot.wsgi
 .slack-creds.env
 .gsheets-creds.json
-.gsheets-token.pickle
+.gsheets-pickle.base64
 __pycache__
index 0fddf679bae5339774e8111fe33aed3afcebcba4..2d0a60984ab528c58e571b7fa494e39fa8860c47 100755 (executable)
@@ -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()