| Left: | ||
| Right: |
| LEFT | RIGHT |
|---|---|
| 1 #!/usr/bin/env python | 1 #!/usr/bin/env python |
| 2 | 2 |
| 3 from ConfigParser import SafeConfigParser | |
| 3 import hashlib | 4 import hashlib |
| 4 import hmac | 5 import hmac |
| 5 import json | 6 import json |
| 6 import os | 7 import os |
| 7 import re | 8 import re |
| 8 import sys | 9 import sys |
| 9 import urllib | 10 import urllib |
| 11 | |
| 12 OAUTH2_AUTHURL = 'https://accounts.google.com/o/oauth2/auth' | |
| 13 OAUTH2_TOKENURL = 'https://accounts.google.com/o/oauth2/token' | |
| 14 OAUTH2_DATAURL = 'https://www.googleapis.com/plus/v1/people/me' | |
| 15 OAUTH2_SCOPE = 'email' | |
| 16 | |
| 17 OAUTH2_TOKEN_EXPIRATION = 5 * 60 | |
| 10 | 18 |
| 11 def setup_paths(engine_dir): | 19 def setup_paths(engine_dir): |
| 12 sys.path.append(engine_dir) | 20 sys.path.append(engine_dir) |
| 13 | 21 |
| 14 import wrapper_util | 22 import wrapper_util |
| 15 paths = wrapper_util.Paths(engine_dir) | 23 paths = wrapper_util.Paths(engine_dir) |
| 16 script_name = os.path.basename(__file__) | 24 script_name = os.path.basename(__file__) |
| 17 sys.path[0:0] = paths.script_paths(script_name) | 25 sys.path[0:0] = paths.script_paths(script_name) |
|
Sebastian Noack
2015/06/02 21:32:06
Nit: sys.path.insert(0, ..)
Wladimir Palant
2015/06/03 15:42:35
The App Engine is inserting tons of paths here, no
Sebastian Noack
2015/06/03 15:58:49
Sorry, just realized that you insert multiple item
| |
| 18 return script_name, paths.script_file(script_name) | 26 return script_name, paths.script_file(script_name) |
| 19 | 27 |
| 20 def adjust_server_id(): | 28 def adjust_server_id(): |
| 21 from google.appengine.tools.devappserver2 import http_runtime_constants | 29 from google.appengine.tools.devappserver2 import http_runtime_constants |
| 22 http_runtime_constants.SERVER_SOFTWARE = 'Production/2.0' | 30 http_runtime_constants.SERVER_SOFTWARE = 'Production/2.0' |
| 23 | 31 |
| 24 def fix_request_scheme(): | 32 def fix_request_scheme(): |
| 25 from google.appengine.runtime.wsgi import WsgiRequest | 33 from google.appengine.runtime.wsgi import WsgiRequest |
| 26 orig_init = WsgiRequest.__init__ | 34 orig_init = WsgiRequest.__init__ |
| 27 def __init__(self, *args): | 35 def __init__(self, *args): |
| 28 orig_init(self, *args) | 36 orig_init(self, *args) |
| 29 self._environ['wsgi.url_scheme'] = self._environ.get('HTTP_X_FORWARDED_PROTO ', 'http') | 37 self._environ['wsgi.url_scheme'] = self._environ.get('HTTP_X_FORWARDED_PROTO ', 'http') |
| 30 self._environ['HTTPS'] = 'on' if self._environ['wsgi.url_scheme'] == 'https' else 'off' | 38 self._environ['HTTPS'] = 'on' if self._environ['wsgi.url_scheme'] == 'https' else 'off' |
| 31 WsgiRequest.__init__ = __init__ | 39 WsgiRequest.__init__ = __init__ |
| 32 | 40 |
| 41 def read_config(path): | |
| 42 config = SafeConfigParser() | |
| 43 config.read(path) | |
| 44 return config | |
| 45 | |
| 33 def set_storage_path(storage_path): | 46 def set_storage_path(storage_path): |
| 34 sys.argv.extend(['--storage_path', storage_path]) | 47 sys.argv.extend(['--storage_path', storage_path]) |
| 35 | 48 |
| 36 def replace_runtime(): | 49 def replace_runtime(): |
| 37 from google.appengine.tools.devappserver2 import python_runtime | 50 from google.appengine.tools.devappserver2 import python_runtime |
| 38 runtime_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '_pyth on_runtime.py') | 51 runtime_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '_pyth on_runtime.py') |
| 39 python_runtime._RUNTIME_PATH = runtime_path | 52 python_runtime._RUNTIME_PATH = runtime_path |
| 40 python_runtime._RUNTIME_ARGS = [sys.executable, runtime_path] | 53 python_runtime._RUNTIME_ARGS = [sys.executable, runtime_path] |
| 41 | 54 |
| 42 def protect_cookies(secret_path): | 55 def protect_cookies(cookie_secret): |
| 43 from google.appengine.tools.devappserver2 import login | 56 from google.appengine.tools.devappserver2 import login |
| 44 | 57 |
| 45 with open(secret_path) as file: | 58 def calculate_signature(message): |
| 46 cookie_secret = file.read().strip() | 59 return hmac.new(cookie_secret, message, hashlib.sha256).hexdigest() |
| 47 | |
| 48 def calculate_signature(str): | |
|
Sebastian Noack
2015/06/02 21:32:06
Nit: Please don't override built-in symbols like "
Wladimir Palant
2015/06/03 15:42:35
Interesting that you seem to be fine with overridi
Sebastian Noack
2015/06/03 15:58:49
I just waited for the day, you notice that. ;P The
| |
| 49 return hmac.new(cookie_secret, str, hashlib.sha256).hexdigest() | |
| 50 | 60 |
| 51 def _get_user_info_from_dict(cookie_dict, cookie_name=login._COOKIE_NAME): | 61 def _get_user_info_from_dict(cookie_dict, cookie_name=login._COOKIE_NAME): |
| 52 cookie_value = cookie_dict.get(cookie_name, '') | 62 cookie_value = cookie_dict.get(cookie_name, '') |
| 53 | 63 |
| 54 email, admin, user_id, signature = (cookie_value.split(':') + ['', '', '', ' '])[:4] | 64 email, admin, user_id, signature = (cookie_value.split(':') + ['', '', '', ' '])[:4] |
| 55 if '@' not in email or signature != calculate_signature(':'.join([email, adm in, user_id])): | 65 if '@' not in email or signature != calculate_signature(':'.join([email, adm in, user_id])): |
| 56 return '', False, '' | 66 return '', False, '' |
| 57 return email, (admin == 'True'), user_id | 67 return email, (admin == 'True'), user_id |
| 58 login._get_user_info_from_dict = _get_user_info_from_dict | 68 login._get_user_info_from_dict = _get_user_info_from_dict |
| 59 | 69 |
| 60 orig_create_cookie_data = login._create_cookie_data | 70 orig_create_cookie_data = login._create_cookie_data |
| 61 def _create_cookie_data(email, admin): | 71 def _create_cookie_data(email, admin): |
| 62 result = orig_create_cookie_data(email, admin) | 72 result = orig_create_cookie_data(email, admin) |
| 63 result += ':' + calculate_signature(result) | 73 result += ':' + calculate_signature(result) |
| 64 return result | 74 return result |
| 65 login._create_cookie_data = _create_cookie_data | 75 login._create_cookie_data = _create_cookie_data |
| 66 | 76 |
| 67 def enable_oauth2(): | 77 def enable_oauth2(client_id, client_secret, admins): |
| 68 from google.appengine.tools.devappserver2 import login | 78 from google.appengine.tools.devappserver2 import login |
| 69 | 79 |
| 80 def request(method, url, data): | |
| 81 if method != 'POST': | |
| 82 url += '?' + urllib.urlencode(data) | |
| 83 data = None | |
| 84 else: | |
| 85 data = urllib.urlencode(data) | |
| 86 response = urllib.urlopen(url, data) | |
| 87 try: | |
| 88 return json.loads(response.read()) | |
| 89 finally: | |
| 90 response.close() | |
| 91 | |
| 92 token_cache = {} | |
| 93 def get_user_info(access_token): | |
| 94 email, is_admin, expiration = token_cache.get(access_token, (None, None, 0)) | |
| 95 now = time.mktime(time.gmtime()) | |
| 96 if now > expiration: | |
| 97 get_params = { | |
| 98 'access_token': access_token, | |
| 99 } | |
| 100 data = request('GET', OAUTH2_DATAURL, get_params) | |
| 101 emails = [e for e in data.get('emails') if e['type'] == 'account'] | |
| 102 if not emails: | |
| 103 return None, None | |
| 104 | |
| 105 email = emails[0]['value'] | |
| 106 is_admin = email in admins | |
| 107 | |
| 108 for token, (_, _, expiration) in token_cache.items(): | |
| 109 if now > expiration: | |
| 110 del token_cache[token] | |
| 111 token_cache[access_token] = (email, is_admin, now + OAUTH2_TOKEN_EXPIRATIO N) | |
| 112 return email, is_admin | |
| 113 | |
| 70 def get(self): | 114 def get(self): |
| 71 action = self.request.get(login.ACTION_PARAM) | |
| 72 continue_url = self.request.get(login.CONTINUE_PARAM) | |
| 73 continue_url = re.sub(r'^http:', 'https:', continue_url) | |
| 74 | |
| 75 base_url = 'https://%s/' % self.request.environ['HTTP_HOST'] | |
| 76 | |
| 77 client_id = '513968628653-95pc63l111it9srihkktkjuvv82ub17s.apps.googleuserco ntent.com' | |
| 78 client_secret = 'G6mHhxjv48gwNSshSyXmNCLi' | |
| 79 | |
| 80 def error(text): | 115 def error(text): |
| 81 self.response.status = 200 | 116 self.response.status = 200 |
| 82 self.response.headers['Content-Type'] = 'text/plain' | 117 self.response.headers['Content-Type'] = 'text/plain' |
| 83 self.response.write(text.encode('utf-8')) | 118 self.response.write(text.encode('utf-8')) |
| 84 | 119 |
| 85 def redirect(url): | 120 def redirect(url): |
| 86 self.response.status = 302 | 121 self.response.status = 302 |
| 87 self.response.status_message = 'Found' | 122 self.response.status_message = 'Found' |
| 88 self.response.headers['Location'] = url.encode('utf-8') | 123 self.response.headers['Location'] = url.encode('utf-8') |
| 89 | 124 |
| 125 def logout(continue_url): | |
| 126 self.response.headers['Set-Cookie'] = login._clear_user_info_cookie() | |
| 127 redirect(continue_url) | |
| 128 | |
| 129 def login_step1(continue_url): | |
| 130 # See https://stackoverflow.com/questions/10271110/python-oauth2-login-wit h-google | |
| 131 authorize_params = { | |
| 132 'response_type': 'code', | |
| 133 'client_id': client_id, | |
| 134 'redirect_uri': base_url + login.LOGIN_URL_RELATIVE, | |
| 135 'scope': OAUTH2_SCOPE, | |
| 136 'state': continue_url, | |
| 137 } | |
| 138 redirect(OAUTH2_AUTHURL + '?' + urllib.urlencode(authorize_params)) | |
| 139 | |
| 140 def login_step2(code, continue_url): | |
| 141 token_params = { | |
| 142 'code': code, | |
| 143 'client_id': client_id, | |
| 144 'client_secret': client_secret, | |
| 145 'redirect_uri': base_url + login.LOGIN_URL_RELATIVE, | |
| 146 'grant_type':'authorization_code', | |
| 147 } | |
| 148 data = request('POST', OAUTH2_TOKENURL, token_params) | |
| 149 token = data.get('access_token') | |
| 150 if not token: | |
| 151 error('No token in response: ' + str(data)) | |
| 152 return | |
| 153 | |
| 154 email, is_admin = get_user_info(token) | |
| 155 if not email: | |
| 156 error('No email address in response: ' + str(data)) | |
| 157 return | |
| 158 self.response.headers['Set-Cookie'] = login._set_user_info_cookie(email, i s_admin) | |
| 159 redirect(continue_url) | |
| 160 | |
| 161 action = self.request.get(login.ACTION_PARAM) | |
| 162 continue_url = self.request.get(login.CONTINUE_PARAM) | |
| 163 continue_url = re.sub(r'^http:', 'https:', continue_url) | |
| 164 base_url = 'https://%s/' % self.request.environ['HTTP_HOST'] | |
| 165 | |
| 90 if action.lower() == login.LOGOUT_ACTION.lower(): | 166 if action.lower() == login.LOGOUT_ACTION.lower(): |
| 91 self.response.headers['Set-Cookie'] = login._clear_user_info_cookie() | 167 logout(continue_url or base_url) |
| 92 redirect(continue_url or base_url) | 168 elif self.request.get('error'): |
|
Sebastian Noack
2015/06/02 21:32:06
It seems inconsistent that you return after error(
Wladimir Palant
2015/06/03 15:42:35
Not really, the three branches here represent the
Sebastian Noack
2015/06/03 15:58:49
Fair enough.
| |
| 169 error('Authorization failed: ' + self.request.get('error')) | |
| 93 else: | 170 else: |
| 94 # See https://stackoverflow.com/questions/10271110/python-oauth2-login-wit h-google | |
| 95 if self.request.get('error'): | |
| 96 error('Authorization failed: ' + self.request.get('error')) | |
| 97 return | |
| 98 | |
| 99 code = self.request.get('code') | 171 code = self.request.get('code') |
| 100 if code: | 172 if code: |
| 101 # User is back and authorized | 173 login_step2(code, self.request.get('state') or base_url) |
| 102 token_params = { | |
| 103 'code': code, | |
| 104 'client_id': client_id, | |
| 105 'client_secret': client_secret, | |
| 106 'redirect_uri': base_url + login.LOGIN_URL_RELATIVE, | |
| 107 'grant_type':'authorization_code', | |
| 108 } | |
| 109 data = urllib.urlopen('https://accounts.google.com/o/oauth2/token', urll ib.urlencode(token_params)).read() | |
|
Sebastian Noack
2015/06/02 21:41:06
Please close the file-like object returned by urlo
Wladimir Palant
2015/06/03 15:42:35
Done.
| |
| 110 token = json.loads(data).get('access_token') | |
| 111 if not token: | |
| 112 error('No token in response: ' + data) | |
| 113 return | |
| 114 | |
| 115 get_params = { | |
| 116 'access_token': token, | |
| 117 } | |
| 118 data = urllib.urlopen('https://www.googleapis.com/plus/v1/people/me?' + urllib.urlencode(get_params)).read() | |
| 119 emails = filter(lambda e: e["type"] == "account", json.loads(data).get(' emails')) | |
|
Sebastian Noack
2015/06/02 21:32:06
I'd rather use a list comprehension here.
Wladimir Palant
2015/06/03 15:42:35
Done.
| |
| 120 if not emails: | |
| 121 error('No email address in response: ' + data) | |
| 122 return | |
| 123 | |
| 124 self.response.headers['Set-Cookie'] = login._set_user_info_cookie(emails [0]["value"], False) | |
| 125 redirect(self.request.get('state') or base_url) | |
| 126 else: | 174 else: |
| 127 # User needs to authorize first | 175 login_step1(continue_url or base_url) |
| 128 authorize_params = { | |
| 129 'response_type': 'code', | |
| 130 'client_id': client_id, | |
| 131 'redirect_uri': base_url + login.LOGIN_URL_RELATIVE, | |
| 132 'scope': 'email', | |
| 133 'state': continue_url, | |
| 134 } | |
| 135 redirect('https://accounts.google.com/o/oauth2/auth?' + urllib.urlencode (authorize_params)) | |
|
Sebastian Noack
2015/06/02 21:32:06
How about a global for 'https://accounts.google.co
Wladimir Palant
2015/06/03 15:42:35
Done.
| |
| 136 | 176 |
| 137 login.Handler.get = get | 177 login.Handler.get = get |
| 178 | |
| 179 from google.appengine.api import user_service_stub, user_service_pb | |
| 180 from google.appengine.runtime import apiproxy_errors | |
| 181 def _Dynamic_GetOAuthUser(self, request, response, request_id): | |
| 182 environ = self.request_data.get_request_environ(request_id) | |
| 183 match = re.search(r'^OAuth (\S+)', environ.get('HTTP_AUTHORIZATION', '')) | |
| 184 if not match: | |
| 185 raise apiproxy_errors.ApplicationError( | |
| 186 user_service_pb.UserServiceError.OAUTH_INVALID_REQUEST) | |
| 187 | |
| 188 email, is_admin = get_user_info(match.group(1)) | |
| 189 if not email: | |
| 190 raise apiproxy_errors.ApplicationError( | |
| 191 user_service_pb.UserServiceError.OAUTH_INVALID_TOKEN) | |
| 192 | |
| 193 # User ID is based on email address, see appengine.tools.devappserver2.login | |
| 194 user_id_digest = hashlib.md5(email.lower()).digest() | |
| 195 user_id = '1' + ''.join(['%02d' % ord(x) for x in user_id_digest])[:20] | |
|
Sebastian Noack
2015/06/04 21:51:43
WTF this algorithm, but I suppose we have to use i
Wladimir Palant
2015/06/04 23:19:54
Luckily, it doesn't seem to matter - Rietveld work
| |
| 196 | |
| 197 response.set_email(email) | |
| 198 response.set_user_id(user_id) | |
| 199 response.set_auth_domain(user_service_stub._DEFAULT_AUTH_DOMAIN) | |
| 200 response.set_is_admin(is_admin) | |
| 201 response.set_client_id(client_id) | |
| 202 response.add_scopes(OAUTH2_SCOPE) | |
| 203 | |
| 204 user_service_stub.UserServiceStub._Dynamic_GetOAuthUser = _Dynamic_GetOAuthUse r | |
| 138 | 205 |
| 139 | 206 |
| 140 if __name__ == '__main__': | 207 if __name__ == '__main__': |
| 141 engine_dir = '/opt/google_appengine' | 208 engine_dir = '/opt/google_appengine' |
| 142 storage_path = '/var/lib/rietveld' | 209 storage_path = '/var/lib/rietveld' |
| 143 | 210 |
| 144 script_name, script_file = setup_paths(engine_dir) | 211 script_name, script_file = setup_paths(engine_dir) |
| 145 adjust_server_id() | 212 adjust_server_id() |
| 146 fix_request_scheme() | 213 fix_request_scheme() |
| 147 | 214 |
| 148 if script_name == 'dev_appserver.py': | 215 if script_name == 'dev_appserver.py': |
| 216 config = read_config(os.path.join(storage_path, 'config.ini')) | |
| 217 | |
| 149 set_storage_path(storage_path) | 218 set_storage_path(storage_path) |
| 150 replace_runtime() | 219 replace_runtime() |
| 151 protect_cookies(os.path.join(storage_path, 'cookie_secret')) | 220 protect_cookies(config.get('main', 'cookie_secret')) |
| 152 enable_oauth2() | 221 enable_oauth2( |
| 222 config.get('oauth2', 'client_id'), | |
| 223 config.get('oauth2', 'client_secret'), | |
| 224 config.get('main', 'admins').split() | |
| 225 ) | |
| 153 | 226 |
| 154 execfile(script_file) | 227 execfile(script_file) |
| LEFT | RIGHT |