From 21be48f8e3b0fcd47b25cbb00e2b4ba9c2915128 Mon Sep 17 00:00:00 2001 From: redxef Date: Thu, 13 Oct 2022 00:47:08 +0200 Subject: [PATCH] Change google adapter to use service account. --- adapters/google.py | 37 +++++++++++++------------------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/adapters/google.py b/adapters/google.py index 062a3ec..83883a2 100644 --- a/adapters/google.py +++ b/adapters/google.py @@ -3,47 +3,36 @@ import tempfile import datetime +import logging import os.path import json from google.auth.transport.requests import Request -from google.oauth2.credentials import Credentials +#from google.oauth2.credentials import Credentials +from google.oauth2.service_account import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError +logger = logging.getLogger(f"wp_cal.{__name__}") + # If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/calendar'] +SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] class Google(): def __init__(self, calendar_id, *, credentials, token_file): - _, credentials_file = tempfile.mkstemp() - with open(credentials_file, 'w') as fp: - json.dump(credentials, fp) - self.calendar_id = calendar_id - self.credentials_file = credentials_file - self.token_file = token_file + self.credentials_info = credentials self.credentials = None def login(self): - if os.path.exists(self.token_file): - self.credentials = Credentials.from_authorized_user_file(self.token_file, SCOPES) - if self.credentials is None or not self.credentials.valid: - if self.credentials is not None \ - and self.credentials.expired \ - and self.credentials.refresh_token: - self.credentials.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - self.credentials_file, - SCOPES, - ) - self.credentials = flow.run_local_server(port=0) - with open(self.token_file, 'w') as token: - token.write(self.credentials.to_json()) + self.credentials = Credentials.from_service_account_info(self.credentials_info, scopes=SCOPES) + if not self.credentials.valid: + self.credentials.refresh(Request()) + logger.debug('credentials.valid = %s', repr(self.credentials.valid)) + def get_events(self, start: datetime.datetime | None=None, until: datetime.timedelta | None=None, limit=None): until = until if until else datetime.timedelta(days=365) @@ -59,7 +48,7 @@ class Google(): maxResults=limit, ).execute() except HttpError: - print('an error occured') + logger.exception("a http error occured") raise events = events.get('items', []) return events