| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
import os |
| 27 |
import sys |
| 28 |
import json |
| 29 |
import argparse |
| 30 |
import time |
| 31 |
import urllib.request as urllibrequest |
| 32 |
import urllib.parse as urllibparse |
| 33 |
import urllib.error as urlliberror |
| 34 |
from http.server import HTTPServer, BaseHTTPRequestHandler |
| 35 |
urlparse = urllibparse |
| 36 |
def codebytes(b): return b.encode("utf8") |
| 37 |
|
| 38 |
force_local_redirect = True |
| 39 |
|
| 40 |
def get_code(url): |
| 41 |
urlparsed = urlparse.urlparse(url) |
| 42 |
query_parsed = urlparse.parse_qs(urlparsed.query) |
| 43 |
try: |
| 44 |
code = query_parsed["code"][0] |
| 45 |
except KeyError: |
| 46 |
code = query_parsed["approvalCode"][0] |
| 47 |
return code |
| 48 |
|
| 49 |
|
| 50 |
class OAuthRedirectHandler(BaseHTTPRequestHandler): |
| 51 |
def do_GET(self): |
| 52 |
code = get_code(self.path) |
| 53 |
self.server.oauth_code = code |
| 54 |
self.send_response(200) |
| 55 |
self.send_header("Content-type", "text/html") |
| 56 |
self.end_headers() |
| 57 |
self.wfile.write(b"<html><head></head><body><h2>Your json file is updated.</h2></body></html>") |
| 58 |
|
| 59 |
class OAuthRedirectServer(HTTPServer): |
| 60 |
def __init__(self, port): |
| 61 |
self.oauth_code = None |
| 62 |
HTTPServer.__init__(self, ("localhost", int(port)), OAuthRedirectHandler) |
| 63 |
self.timeout = None |
| 64 |
|
| 65 |
class OAuth2(object): |
| 66 |
|
| 67 |
def __init__(self, token_data_path): |
| 68 |
self.token_data_path = token_data_path |
| 69 |
|
| 70 |
with open(self.token_data_path) as f: |
| 71 |
self.data = json.load(f) |
| 72 |
|
| 73 |
def copy(self, *keys): |
| 74 |
data = {} |
| 75 |
for k in keys: |
| 76 |
try: |
| 77 |
data[k] = self.data[k] |
| 78 |
except KeyError: |
| 79 |
pass |
| 80 |
return data |
| 81 |
|
| 82 |
def query(self, params): |
| 83 |
lst = [] |
| 84 |
for param in sorted(params.items(), key=lambda x: x[0]): |
| 85 |
escaped = urllibparse.quote(param[1], safe='~-._') |
| 86 |
lst.append('%s=%s' % (param[0], escaped)) |
| 87 |
return '&'.join(lst) |
| 88 |
|
| 89 |
def code_url(self, port): |
| 90 |
params = self.copy('scope', 'client_id', 'redirect_uri') |
| 91 |
if 'redirect_uri' not in params or force_local_redirect: |
| 92 |
params['redirect_uri'] = 'http://localhost:' + str(port) + '/' |
| 93 |
params['response_type'] = 'code' |
| 94 |
params['access_type'] = 'offline' |
| 95 |
if 'prompt' in self.data: |
| 96 |
params['prompt'] = self.data['prompt'] |
| 97 |
else: |
| 98 |
params['prompt'] = 'consent' |
| 99 |
return '%s?%s' % (self.data['auth_uri'], self.query(params)) |
| 100 |
|
| 101 |
def get_response(self, url, params): |
| 102 |
try: |
| 103 |
encoded = urllibparse.urlencode(params).encode('ascii') |
| 104 |
response = urllibrequest.urlopen(url, encoded).read() |
| 105 |
return json.loads(response) |
| 106 |
except urlliberror.HTTPError as httpError: |
| 107 |
error = httpError.read().decode() |
| 108 |
print("error: " + error) |
| 109 |
sys.exit(1) |
| 110 |
|
| 111 |
def update_config(self, d): |
| 112 |
self.data['access_token'] = d['access_token'] |
| 113 |
self.data['expires_at'] = time.time() + d['expires_in'] - 100 |
| 114 |
|
| 115 |
refresh_token = d.get('refresh_token') |
| 116 |
if refresh_token is not None: |
| 117 |
self.data['refresh_token'] = refresh_token |
| 118 |
|
| 119 |
with open(self.token_data_path, "w") as f: |
| 120 |
json.dump(self.data, f) |
| 121 |
|
| 122 |
def init_tokens(self, code, port): |
| 123 |
params = self.copy('user', 'client_id', 'client_secret', 'redirect_uri') |
| 124 |
if 'redirect_uri' not in params or force_local_redirect: |
| 125 |
params['redirect_uri'] = 'http://localhost:' + str(port) + '/' |
| 126 |
params['code'] = code |
| 127 |
params['grant_type'] = 'authorization_code' |
| 128 |
|
| 129 |
d = self.get_response(self.data['token_uri'], params) |
| 130 |
self.update_config(d) |
| 131 |
|
| 132 |
def refresh_tokens(self): |
| 133 |
params = self.copy('client_id', 'client_secret', 'refresh_token') |
| 134 |
params['grant_type'] = 'refresh_token' |
| 135 |
|
| 136 |
d = self.get_response(self.data['token_uri'], params) |
| 137 |
self.update_config(d) |
| 138 |
|
| 139 |
def token(self): |
| 140 |
if time.time() >= self.data.get('expires_at'): |
| 141 |
self.refresh_tokens() |
| 142 |
|
| 143 |
return self.data['access_token'] |
| 144 |
|
| 145 |
|
| 146 |
if __name__ == '__main__': |
| 147 |
parser = argparse.ArgumentParser() |
| 148 |
parser.add_argument("-i", "--init", action="store_true", default=False, |
| 149 |
help="initialize access and refresh tokens") |
| 150 |
parser.add_argument('tokenfile', metavar='<token data file path>', |
| 151 |
help="location of the token data file") |
| 152 |
parser.add_argument("-p", "--port", default=None, |
| 153 |
help="local port to use for receiving oauth2 redirect (default 8083)") |
| 154 |
|
| 155 |
args = parser.parse_args() |
| 156 |
|
| 157 |
if not args.port: |
| 158 |
force_local_redirect = False |
| 159 |
args.port = 8083 |
| 160 |
|
| 161 |
auth = OAuth2(args.tokenfile) |
| 162 |
|
| 163 |
if args.init: |
| 164 |
interrupted = False |
| 165 |
print("Visit this url to obtain a verification code:") |
| 166 |
print(" %s\n" % auth.code_url(args.port)) |
| 167 |
if not auth.copy('redirect_uri') or force_local_redirect: |
| 168 |
print("Press Ctrl+C if you are installing getmail on a device without a browser.") |
| 169 |
oauthd = OAuthRedirectServer(args.port) |
| 170 |
try: |
| 171 |
oauthd.handle_request() |
| 172 |
auth.init_tokens(oauthd.oauth_code, args.port) |
| 173 |
except: |
| 174 |
interrupted = True |
| 175 |
finally: |
| 176 |
oauthd.server_close() |
| 177 |
if (auth.copy('redirect_uri') and not force_local_redirect) or interrupted: |
| 178 |
print("Please paste the response from the address bar of the browser you used for the url above:") |
| 179 |
urlinput = input() |
| 180 |
code = get_code(urlinput) |
| 181 |
auth.init_tokens(code,args.port) |
| 182 |
print("\naccess token\n") |
| 183 |
|
| 184 |
print("%s" % auth.token()) |
| 185 |
|
| 186 |
sys.exit(0) |