]> git.cworth.org Git - turbot/blob - gsheets-authenticate.py
gsheets-authenticate: Change to using base64 to encode the pickled token
[turbot] / gsheets-authenticate.py
1 #!/usr/bin/env python3
2
3 import pickle
4 import base64
5 import os.path
6 from google_auth_oauthlib.flow import InstalledAppFlow
7 from google.auth.transport.requests import Request
8
9 TOKEN_FILE = ".gsheets-pickle.base64"
10
11 # If modifying these scopes, delete the token file
12 SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
13
14 def main():
15     """Allows user to authenticate for the Sheets API.
16
17     Resulting authorization token is stored in token.pickle.
18     """
19     creds = None
20     # The token file stores the user's access and refresh tokens, and is
21     # created automatically when the authorization flow completes for the first
22     # time.
23     if os.path.exists(TOKEN_FILE):
24         with open(TOKEN_FILE, 'rb') as token_file:
25             creds_base64 = token_file.read()
26             creds_pickle = base64.b64decode(creds_base64)
27             creds = pickle.loads(creds_pickle)
28
29     # If there are no (valid) credentials available, let the user log in.
30     if not creds or not creds.valid:
31         if creds and creds.expired and creds.refresh_token:
32             print("Token seems to have expired. Refreshing.")
33             creds.refresh(Request())
34         else:
35             flow = InstalledAppFlow.from_client_secrets_file(
36                 '.gsheets-creds.json', SCOPES)
37             creds = flow.run_local_server(port=0)
38         # Save the credentials for the next run
39         with open(TOKEN_FILE, 'wb') as token_file:
40             creds_pickle = pickle.dumps(creds)
41             creds_base64 = base64.b64encode(creds_pickle)
42             token_file.write(creds_base64)
43             print("Token now saved in {}".format(TOKEN_FILE))
44     else:
45         print("Valid token in {} left unchanged.".format(TOKEN_FILE))
46
47 if __name__ == '__main__':
48     main()