def _set_account_info(self): with session_scope() as db_session: account = db_session.query(ImapAccount).get(self.account_id) # Refresh token if need be, for OAuthed accounts if AUTH_TYPES.get(account.provider) == 'OAuth': account = verify_imap_account(db_session, account) self.o_access_token = account.o_access_token self.email_address = account.email_address self.provider = account.provider
def verify_gmail_account(account): try: conn = IMAPClient(IMAP_HOST, use_uid=True, ssl=True) except IMAPClient.Error as e: raise socket.error(str(e)) conn.debug = False try: conn.oauth2_login(account.email_address, account.o_access_token) except IMAPClient.Error as e: if str(e) == '[ALERT] Invalid credentials (Failure)': # maybe refresh the access token with session_scope() as db_session: account = verify_imap_account(db_session, account) conn.oauth2_login(account.email_address, account.o_access_token) return conn
def _set_account_info(self): with session_scope() as db_session: account = db_session.query(ImapAccount).get(self.account_id) self.email_address = account.email_address self.provider = account.provider self.full_name = account.full_name if account.provider == 'Gmail'\ else '' self.sent_folder = account.sent_folder.name self.auth_type = AUTH_TYPES.get(account.provider) if self.auth_type == 'OAuth': # Refresh OAuth token if need be account = verify_imap_account(db_session, account) self.o_access_token = account.o_access_token else: assert self.auth_type == 'Password' self.password = account.password
def _get_google_client(self): """Return the Google API client.""" # TODO(emfree) figure out a better strategy for refreshing OAuth # credentials as needed with session_scope() as db_session: try: account = db_session.query(ImapAccount).get(self.account_id) account = verify_imap_account(db_session, account) two_legged_oauth_token = gdata.gauth.OAuth2Token( client_id=GOOGLE_OAUTH_CLIENT_ID, client_secret=GOOGLE_OAUTH_CLIENT_SECRET, scope=OAUTH_SCOPE, user_agent=SOURCE_APP_NAME, access_token=account.o_access_token, refresh_token=account.o_refresh_token) google_client = gdata.contacts.client.ContactsClient( source=SOURCE_APP_NAME) google_client.auth_token = two_legged_oauth_token return google_client except gdata.client.BadAuthentication: self.log.error('Invalid user credentials given') return None