]> git.cworth.org Git - turbot/blob - gsheets-authenticate.py
Add notes on how to update the Google sheets credentials
[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 = [
13     'https://www.googleapis.com/auth/spreadsheets',
14     'https://www.googleapis.com/auth/drive'
15 ]
16
17 def main():
18     """Allows user to authenticate for the Sheets API.
19
20     Resulting authorization token is stored in token.pickle.
21     """
22     creds = None
23     # The token file stores the user's access and refresh tokens, and is
24     # created automatically when the authorization flow completes for the first
25     # time.
26     if os.path.exists(TOKEN_FILE):
27         with open(TOKEN_FILE, 'rb') as token_file:
28             creds_base64 = token_file.read()
29             creds_pickle = base64.b64decode(creds_base64)
30             creds = pickle.loads(creds_pickle)
31
32     # If there are no (valid) credentials available, let the user log in.
33     if not creds or not creds.valid:
34         if creds and creds.expired and creds.refresh_token:
35             print("Token seems to have expired. Refreshing.")
36             creds.refresh(Request())
37         else:
38             flow = InstalledAppFlow.from_client_secrets_file(
39                 '.gsheets-creds.json', SCOPES)
40             creds = flow.run_local_server(port=0)
41         # Save the credentials for the next run
42         with open(TOKEN_FILE, 'wb') as token_file:
43             creds_pickle = pickle.dumps(creds)
44             creds_base64 = base64.b64encode(creds_pickle)
45             token_file.write(creds_base64)
46             print("Token now saved in {}".format(TOKEN_FILE))
47     else:
48         print("Valid token in {} left unchanged.".format(TOKEN_FILE))
49
50 if __name__ == '__main__':
51     main()