Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: modules/rietveld/files/wrapper.py

Issue 6155422901731328: Run Rietveld using the AppEngine SDK (Closed)
Patch Set: Addressed comments and added proper configuration Created June 3, 2015, 3:31 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « modules/rietveld/files/site.conf ('k') | modules/rietveld/manifests/init.pp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(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 get(self):
79 def request(method, url, data):
80 if method != 'POST':
81 url += '?' + urllib.urlencode(data)
82 data = None
83 else:
84 data = urllib.urlencode(data)
85 response = urllib.urlopen(url, data)
86 try:
87 return json.loads(response.read())
88 finally:
89 response.close()
90
91 def error(text):
92 self.response.status = 200
93 self.response.headers['Content-Type'] = 'text/plain'
94 self.response.write(text.encode('utf-8'))
95
96 def redirect(url):
97 self.response.status = 302
98 self.response.status_message = 'Found'
99 self.response.headers['Location'] = url.encode('utf-8')
100
101 def logout(continue_url):
102 self.response.headers['Set-Cookie'] = login._clear_user_info_cookie()
103 redirect(continue_url)
104
105 def login_step1(continue_url):
106 # See https://stackoverflow.com/questions/10271110/python-oauth2-login-wit h-google
107 authorize_params = {
108 'response_type': 'code',
109 'client_id': client_id,
110 'redirect_uri': base_url + login.LOGIN_URL_RELATIVE,
111 'scope': OAUTH2_SCOPE,
112 'state': continue_url,
113 }
114 redirect(OAUTH2_AUTHURL + '?' + urllib.urlencode(authorize_params))
115
116 def login_step2(code, continue_url):
117 token_params = {
118 'code': code,
119 'client_id': client_id,
120 'client_secret': client_secret,
121 'redirect_uri': base_url + login.LOGIN_URL_RELATIVE,
122 'grant_type':'authorization_code',
123 }
124 data = request('POST', OAUTH2_TOKENURL, token_params)
125 token = data.get('access_token')
126 if not token:
127 error('No token in response: ' + str(data))
128 return
129
130 get_params = {
131 'access_token': token,
132 }
133 data = request('GET', OAUTH2_DATAURL, get_params)
134 emails = [e for e in data.get('emails') if e['type'] == 'account']
135 if not emails:
136 error('No email address in response: ' + str(data))
137 return
138
139 email = emails[0]['value']
140 is_admin = email in admins
141 self.response.headers['Set-Cookie'] = login._set_user_info_cookie(email, i s_admin)
142 redirect(continue_url)
143
144 action = self.request.get(login.ACTION_PARAM)
145 continue_url = self.request.get(login.CONTINUE_PARAM)
146 continue_url = re.sub(r'^http:', 'https:', continue_url)
147 base_url = 'https://%s/' % self.request.environ['HTTP_HOST']
148
149 if action.lower() == login.LOGOUT_ACTION.lower():
150 logout(continue_url or base_url)
151 elif self.request.get('error'):
152 error('Authorization failed: ' + self.request.get('error'))
153 else:
154 code = self.request.get('code')
155 if code:
156 login_step2(code, self.request.get('state') or base_url)
157 else:
158 login_step1(continue_url or base_url)
159
160 login.Handler.get = get
161
162
163 if __name__ == '__main__':
164 engine_dir = '/opt/google_appengine'
165 storage_path = '/var/lib/rietveld'
166
167 script_name, script_file = setup_paths(engine_dir)
168 adjust_server_id()
169 fix_request_scheme()
170
171 if script_name == 'dev_appserver.py':
172 config = read_config(os.path.join(storage_path, 'config.ini'))
173
174 set_storage_path(storage_path)
175 replace_runtime()
176 protect_cookies(config.get('main', 'cookie_secret'))
177 enable_oauth2(
178 config.get('oauth2', 'client_id'),
179 config.get('oauth2', 'client_secret'),
180 config.get('main', 'admins').split()
181 )
182
183 execfile(script_file)
OLDNEW
« no previous file with comments | « modules/rietveld/files/site.conf ('k') | modules/rietveld/manifests/init.pp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld