| Left: | ||
| Right: |
| OLD | NEW |
|---|---|
| (Empty) | |
| 1 #!/usr/bin/env python | |
| 2 | |
| 3 from ConfigParser import SafeConfigParser | |
| 4 import hashlib | |
| 5 import hmac | |
| 6 import json | |
| 7 import os | |
| 8 import re | |
| 9 import sys | |
| 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 | |
| 18 | |
| 19 def setup_paths(engine_dir): | |
| 20 sys.path.append(engine_dir) | |
| 21 | |
| 22 import wrapper_util | |
| 23 paths = wrapper_util.Paths(engine_dir) | |
| 24 script_name = os.path.basename(__file__) | |
| 25 sys.path[0:0] = paths.script_paths(script_name) | |
| 26 return script_name, paths.script_file(script_name) | |
| 27 | |
| 28 def adjust_server_id(): | |
| 29 from google.appengine.tools.devappserver2 import http_runtime_constants | |
| 30 http_runtime_constants.SERVER_SOFTWARE = 'Production/2.0' | |
| 31 | |
| 32 def fix_request_scheme(): | |
| 33 from google.appengine.runtime.wsgi import WsgiRequest | |
| 34 orig_init = WsgiRequest.__init__ | |
| 35 def __init__(self, *args): | |
| 36 orig_init(self, *args) | |
| 37 self._environ['wsgi.url_scheme'] = self._environ.get('HTTP_X_FORWARDED_PROTO ', 'http') | |
| 38 self._environ['HTTPS'] = 'on' if self._environ['wsgi.url_scheme'] == 'https' else 'off' | |
| 39 WsgiRequest.__init__ = __init__ | |
| 40 | |
| 41 def read_config(path): | |
| 42 config = SafeConfigParser() | |
| 43 config.read(path) | |
| 44 return config | |
| 45 | |
| 46 def set_storage_path(storage_path): | |
| 47 sys.argv.extend(['--storage_path', storage_path]) | |
| 48 | |
| 49 def replace_runtime(): | |
| 50 from google.appengine.tools.devappserver2 import python_runtime | |
| 51 runtime_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '_pyth on_runtime.py') | |
| 52 python_runtime._RUNTIME_PATH = runtime_path | |
| 53 python_runtime._RUNTIME_ARGS = [sys.executable, runtime_path] | |
| 54 | |
| 55 def protect_cookies(cookie_secret): | |
| 56 from google.appengine.tools.devappserver2 import login | |
| 57 | |
| 58 def calculate_signature(message): | |
| 59 return hmac.new(cookie_secret, message, hashlib.sha256).hexdigest() | |
| 60 | |
| 61 def _get_user_info_from_dict(cookie_dict, cookie_name=login._COOKIE_NAME): | |
| 62 cookie_value = cookie_dict.get(cookie_name, '') | |
| 63 | |
| 64 email, admin, user_id, signature = (cookie_value.split(':') + ['', '', '', ' '])[:4] | |
| 65 if '@' not in email or signature != calculate_signature(':'.join([email, adm in, user_id])): | |
| 66 return '', False, '' | |
| 67 return email, (admin == 'True'), user_id | |
| 68 login._get_user_info_from_dict = _get_user_info_from_dict | |
| 69 | |
| 70 orig_create_cookie_data = login._create_cookie_data | |
| 71 def _create_cookie_data(email, admin): | |
| 72 result = orig_create_cookie_data(email, admin) | |
| 73 result += ':' + calculate_signature(result) | |
| 74 return result | |
| 75 login._create_cookie_data = _create_cookie_data | |
| 76 | |
| 77 def enable_oauth2(client_id, client_secret, admins): | |
| 78 from google.appengine.tools.devappserver2 import login | |
| 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 | |
| 114 def get(self): | |
| 115 def error(text): | |
| 116 self.response.status = 200 | |
| 117 self.response.headers['Content-Type'] = 'text/plain' | |
| 118 self.response.write(text.encode('utf-8')) | |
| 119 | |
| 120 def redirect(url): | |
| 121 self.response.status = 302 | |
| 122 self.response.status_message = 'Found' | |
| 123 self.response.headers['Location'] = url.encode('utf-8') | |
| 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 | |
| 166 if action.lower() == login.LOGOUT_ACTION.lower(): | |
| 167 logout(continue_url or base_url) | |
| 168 elif self.request.get('error'): | |
| 169 error('Authorization failed: ' + self.request.get('error')) | |
| 170 else: | |
| 171 code = self.request.get('code') | |
| 172 if code: | |
| 173 login_step2(code, self.request.get('state') or base_url) | |
| 174 else: | |
| 175 login_step1(continue_url or base_url) | |
| 176 | |
| 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 | |
| 205 | |
| 206 | |
| 207 if __name__ == '__main__': | |
| 208 engine_dir = '/opt/google_appengine' | |
| 209 storage_path = '/var/lib/rietveld' | |
| 210 | |
| 211 script_name, script_file = setup_paths(engine_dir) | |
| 212 adjust_server_id() | |
| 213 fix_request_scheme() | |
| 214 | |
| 215 if script_name == 'dev_appserver.py': | |
| 216 config = read_config(os.path.join(storage_path, 'config.ini')) | |
| 217 | |
| 218 set_storage_path(storage_path) | |
| 219 replace_runtime() | |
| 220 protect_cookies(config.get('main', 'cookie_secret')) | |
| 221 enable_oauth2( | |
| 222 config.get('oauth2', 'client_id'), | |
| 223 config.get('oauth2', 'client_secret'), | |
| 224 config.get('main', 'admins').split() | |
| 225 ) | |
| 226 | |
| 227 execfile(script_file) | |
| OLD | NEW |