How to use gpg encrypted oauth files via Python for offlineimap

I played with oauth2 to better understand it. For this reason, I installed offlineimap, which should act as a third-party application. I found a good way to read encrypted credentials here on stackexchange .

Based on the related post, I modified / copied the following python script:

import subprocess
import os
import json

def passwd(file_name):
  acct = os.path.basename(file_name)
  path = "/PATHTOFILE/%s" % file_name
  args = ["gpg", "--use-agent", "--quiet", "--batch", "-d", path]
  try:
    return subprocess.check_output(args).strip()
  except subprocess.CalledProcessError:
    return ""

def oauthpasswd(acct, key):
  acct = os.path.basename(acct)
  path = "/PATHTOFILE/%s_oauth2.gpg" % acct
  args = ["gpg", "--use-agent", "--quiet", "--batch", "-d", path]
  try:
    return str(json.loads(subprocess.check_output(args).strip())['installed'][key])
  except subprocess.CalledProcessError:
    return ""

def prime_gpg_agent():
  ret = False
  i = 1
  while not ret:
    ret = (passwd("prime.gpg") == "prime")
    if i > 2:
      from offlineimap.ui import getglobalui
      sys.stderr.write("Error reading in passwords. Terminating.\n")
      getglobalui().terminate()
    i += 1
  return ret

prime_gpg_agent()

In the corresponding offlineimaprc file, I call the function with the correct arguments:

oauth2_client_id = oauthpasswd('gmail', 'client_id')
oauth2_client_secret = oauthpasswd('gmail', 'client_secret')
oauth2_request_url = https://accounts.google.com/o/oauth2/token
oauth2_refresh_token = passwd('gmail_rf_token.gpg')

Please note that the parameter is PATHTOFILEset correctly in the local file . What I did was uploaded by a JSON file from Google, including oauth2 credentials and encrypted. I saved the update token in a separate file. However, if I run offlineimap, I get an authentication error:

 ERROR: While attempting to sync account 'gmail'
  ('http error', 401, 'Unauthorized', <httplib.HTTPMessage instance at 0x7f488c214320>) (configuration is: {'client_secret': "oauthpasswd('gmail', 'client_secret')", 'grant_type': 'refresh_token', 'refresh_token': "passwd('gmail_rf_token.gpg')", 'client_id': "oauthpasswd('gmail', 'client_id')"})

python passwd oauthpasswd python. . , python offlineimaprc, Gmail. , , offlineimap , , .

Gmail, . , - , Google (client_id, client_secret ). , .

oauthpasswd('gmail', 'client_id')
oauthpasswd('gmail', 'client_secret')
passwd('gmail_rf_token.gpg')

python offlineimaprc, .

+6
1

, , . answer offlineimap offlinemaprc. python .

+1

All Articles