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 def setup_paths(engine_dir): |
| 18 sys.path.append(engine_dir) |
| 19 |
| 20 import wrapper_util |
| 21 paths = wrapper_util.Paths(engine_dir) |
| 22 script_name = os.path.basename(__file__) |
| 23 sys.path[0:0] = paths.script_paths(script_name) |
| 24 return script_name, paths.script_file(script_name) |
| 25 |
| 26 def adjust_server_id(): |
| 27 from google.appengine.tools.devappserver2 import http_runtime_constants |
| 28 http_runtime_constants.SERVER_SOFTWARE = 'Production/2.0' |
| 29 |
| 30 def fix_request_scheme(): |
| 31 from google.appengine.runtime.wsgi import WsgiRequest |
| 32 orig_init = WsgiRequest.__init__ |
| 33 def __init__(self, *args): |
| 34 orig_init(self, *args) |
| 35 self._environ['wsgi.url_scheme'] = self._environ.get('HTTP_X_FORWARDED_PROTO
', 'http') |
| 36 self._environ['HTTPS'] = 'on' if self._environ['wsgi.url_scheme'] == 'https'
else 'off' |
| 37 WsgiRequest.__init__ = __init__ |
| 38 |
| 39 def read_config(path): |
| 40 config = SafeConfigParser() |
| 41 config.read(path) |
| 42 return config |
| 43 |
| 44 def set_storage_path(storage_path): |
| 45 sys.argv.extend(['--storage_path', storage_path]) |
| 46 |
| 47 def replace_runtime(): |
| 48 from google.appengine.tools.devappserver2 import python_runtime |
| 49 runtime_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '_pyth
on_runtime.py') |
| 50 python_runtime._RUNTIME_PATH = runtime_path |
| 51 python_runtime._RUNTIME_ARGS = [sys.executable, runtime_path] |
| 52 |
| 53 def protect_cookies(cookie_secret): |
| 54 from google.appengine.tools.devappserver2 import login |
| 55 |
| 56 def calculate_signature(message): |
| 57 return hmac.new(cookie_secret, message, hashlib.sha256).hexdigest() |
| 58 |
| 59 def _get_user_info_from_dict(cookie_dict, cookie_name=login._COOKIE_NAME): |
| 60 cookie_value = cookie_dict.get(cookie_name, '') |
| 61 |
| 62 email, admin, user_id, signature = (cookie_value.split(':') + ['', '', '', '
'])[:4] |
| 63 if '@' not in email or signature != calculate_signature(':'.join([email, adm
in, user_id])): |
| 64 return '', False, '' |
| 65 return email, (admin == 'True'), user_id |
| 66 login._get_user_info_from_dict = _get_user_info_from_dict |
| 67 |
| 68 orig_create_cookie_data = login._create_cookie_data |
| 69 def _create_cookie_data(email, admin): |
| 70 result = orig_create_cookie_data(email, admin) |
| 71 result += ':' + calculate_signature(result) |
| 72 return result |
| 73 login._create_cookie_data = _create_cookie_data |
| 74 |
| 75 def enable_oauth2(client_id, client_secret, admins): |
| 76 from google.appengine.tools.devappserver2 import login |
| 77 |
| 78 def request(method, url, data): |
| 79 if method != 'POST': |
| 80 url += '?' + urllib.urlencode(data) |
| 81 data = None |
| 82 else: |
| 83 data = urllib.urlencode(data) |
| 84 response = urllib.urlopen(url, data) |
| 85 try: |
| 86 return json.loads(response.read()) |
| 87 finally: |
| 88 response.close() |
| 89 |
| 90 def get_user_info(access_token): |
| 91 get_params = { |
| 92 'access_token': access_token, |
| 93 } |
| 94 data = request('GET', OAUTH2_DATAURL, get_params) |
| 95 emails = [e for e in data.get('emails') if e['type'] == 'account'] |
| 96 if not emails: |
| 97 return None, None |
| 98 |
| 99 email = emails[0]['value'] |
| 100 return email, email in admins |
| 101 |
| 102 def get(self): |
| 103 def error(text): |
| 104 self.response.status = 200 |
| 105 self.response.headers['Content-Type'] = 'text/plain' |
| 106 self.response.write(text.encode('utf-8')) |
| 107 |
| 108 def redirect(url): |
| 109 self.response.status = 302 |
| 110 self.response.status_message = 'Found' |
| 111 self.response.headers['Location'] = url.encode('utf-8') |
| 112 |
| 113 def logout(continue_url): |
| 114 self.response.headers['Set-Cookie'] = login._clear_user_info_cookie() |
| 115 redirect(continue_url) |
| 116 |
| 117 def login_step1(continue_url): |
| 118 # See https://stackoverflow.com/questions/10271110/python-oauth2-login-wit
h-google |
| 119 authorize_params = { |
| 120 'response_type': 'code', |
| 121 'client_id': client_id, |
| 122 'redirect_uri': base_url + login.LOGIN_URL_RELATIVE, |
| 123 'scope': OAUTH2_SCOPE, |
| 124 'state': continue_url, |
| 125 } |
| 126 redirect(OAUTH2_AUTHURL + '?' + urllib.urlencode(authorize_params)) |
| 127 |
| 128 def login_step2(code, continue_url): |
| 129 token_params = { |
| 130 'code': code, |
| 131 'client_id': client_id, |
| 132 'client_secret': client_secret, |
| 133 'redirect_uri': base_url + login.LOGIN_URL_RELATIVE, |
| 134 'grant_type':'authorization_code', |
| 135 } |
| 136 data = request('POST', OAUTH2_TOKENURL, token_params) |
| 137 token = data.get('access_token') |
| 138 if not token: |
| 139 error('No token in response: ' + str(data)) |
| 140 return |
| 141 |
| 142 email, is_admin = get_user_info(token) |
| 143 if not email: |
| 144 error('No email address in response: ' + str(data)) |
| 145 return |
| 146 self.response.headers['Set-Cookie'] = login._set_user_info_cookie(email, i
s_admin) |
| 147 redirect(continue_url) |
| 148 |
| 149 action = self.request.get(login.ACTION_PARAM) |
| 150 continue_url = self.request.get(login.CONTINUE_PARAM) |
| 151 continue_url = re.sub(r'^http:', 'https:', continue_url) |
| 152 base_url = 'https://%s/' % self.request.environ['HTTP_HOST'] |
| 153 |
| 154 if action.lower() == login.LOGOUT_ACTION.lower(): |
| 155 logout(continue_url or base_url) |
| 156 elif self.request.get('error'): |
| 157 error('Authorization failed: ' + self.request.get('error')) |
| 158 else: |
| 159 code = self.request.get('code') |
| 160 if code: |
| 161 login_step2(code, self.request.get('state') or base_url) |
| 162 else: |
| 163 login_step1(continue_url or base_url) |
| 164 |
| 165 login.Handler.get = get |
| 166 |
| 167 from google.appengine.api.user_service_stub import UserServiceStub |
| 168 from google.appengine.api import user_service_pb |
| 169 from google.appengine.runtime import apiproxy_errors |
| 170 def _Dynamic_GetOAuthUser(self, request, response, request_id): |
| 171 environ = self.request_data.get_request_environ(request_id) |
| 172 match = re.search(r'^OAuth (\S+)', environ.get('HTTP_AUTHORIZATION', '')) |
| 173 if not match: |
| 174 raise apiproxy_errors.ApplicationError( |
| 175 user_service_pb.UserServiceError.OAUTH_INVALID_REQUEST) |
| 176 |
| 177 email, is_admin = get_user_info(match.group(1)) |
| 178 if not email: |
| 179 raise apiproxy_errors.ApplicationError( |
| 180 user_service_pb.UserServiceError.OAUTH_INVALID_TOKEN) |
| 181 |
| 182 response.set_email(email) |
| 183 response.set_user_id(0) |
| 184 response.set_auth_domain(environ.get('HTTP_HOST')) |
| 185 response.set_is_admin(is_admin) |
| 186 response.set_client_id(client_id) |
| 187 response.add_scopes(OAUTH2_SCOPE) |
| 188 |
| 189 UserServiceStub._Dynamic_GetOAuthUser = _Dynamic_GetOAuthUser |
| 190 |
| 191 |
| 192 if __name__ == '__main__': |
| 193 engine_dir = '/opt/google_appengine' |
| 194 storage_path = '/var/lib/rietveld' |
| 195 |
| 196 script_name, script_file = setup_paths(engine_dir) |
| 197 adjust_server_id() |
| 198 fix_request_scheme() |
| 199 |
| 200 if script_name == 'dev_appserver.py': |
| 201 config = read_config(os.path.join(storage_path, 'config.ini')) |
| 202 |
| 203 set_storage_path(storage_path) |
| 204 replace_runtime() |
| 205 protect_cookies(config.get('main', 'cookie_secret')) |
| 206 enable_oauth2( |
| 207 config.get('oauth2', 'client_id'), |
| 208 config.get('oauth2', 'client_secret'), |
| 209 config.get('main', 'admins').split() |
| 210 ) |
| 211 |
| 212 execfile(script_file) |
OLD | NEW |