Left: | ||
Right: |
OLD | NEW |
---|---|
(Empty) | |
1 #!/usr/bin/env python | |
2 | |
3 import hashlib | |
4 import hmac | |
5 import json | |
6 import os | |
7 import re | |
8 import sys | |
9 import urllib | |
10 | |
11 def setup_paths(engine_dir): | |
12 sys.path.append(engine_dir) | |
13 | |
14 import wrapper_util | |
15 paths = wrapper_util.Paths(engine_dir) | |
16 script_name = os.path.basename(__file__) | |
17 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) | |
19 | |
20 def adjust_server_id(): | |
21 from google.appengine.tools.devappserver2 import http_runtime_constants | |
22 http_runtime_constants.SERVER_SOFTWARE = 'Production/2.0' | |
23 | |
24 def fix_request_scheme(): | |
25 from google.appengine.runtime.wsgi import WsgiRequest | |
26 orig_init = WsgiRequest.__init__ | |
27 def __init__(self, *args): | |
28 orig_init(self, *args) | |
29 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' | |
31 WsgiRequest.__init__ = __init__ | |
32 | |
33 def set_storage_path(storage_path): | |
34 sys.argv.extend(['--storage_path', storage_path]) | |
35 | |
36 def replace_runtime(): | |
37 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') | |
39 python_runtime._RUNTIME_PATH = runtime_path | |
40 python_runtime._RUNTIME_ARGS = [sys.executable, runtime_path] | |
41 | |
42 def protect_cookies(secret_path): | |
43 from google.appengine.tools.devappserver2 import login | |
44 | |
45 with open(secret_path) as file: | |
46 cookie_secret = file.read().strip() | |
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 | |
51 def _get_user_info_from_dict(cookie_dict, cookie_name=login._COOKIE_NAME): | |
52 cookie_value = cookie_dict.get(cookie_name, '') | |
53 | |
54 email, admin, user_id, signature = (cookie_value.split(':') + ['', '', '', ' '])[:4] | |
55 if '@' not in email or signature != calculate_signature(':'.join([email, adm in, user_id])): | |
56 return '', False, '' | |
57 return email, (admin == 'True'), user_id | |
58 login._get_user_info_from_dict = _get_user_info_from_dict | |
59 | |
60 orig_create_cookie_data = login._create_cookie_data | |
61 def _create_cookie_data(email, admin): | |
62 result = orig_create_cookie_data(email, admin) | |
63 result += ':' + calculate_signature(result) | |
64 return result | |
65 login._create_cookie_data = _create_cookie_data | |
66 | |
67 def enable_oauth2(): | |
68 from google.appengine.tools.devappserver2 import login | |
69 | |
70 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): | |
81 self.response.status = 200 | |
82 self.response.headers['Content-Type'] = 'text/plain' | |
83 self.response.write(text.encode('utf-8')) | |
84 | |
85 def redirect(url): | |
86 self.response.status = 302 | |
87 self.response.status_message = 'Found' | |
88 self.response.headers['Location'] = url.encode('utf-8') | |
89 | |
90 if action.lower() == login.LOGOUT_ACTION.lower(): | |
91 self.response.headers['Set-Cookie'] = login._clear_user_info_cookie() | |
92 redirect(continue_url or base_url) | |
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.
| |
93 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') | |
100 if code: | |
101 # User is back and authorized | |
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: | |
127 # User needs to authorize first | |
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 | |
137 login.Handler.get = get | |
138 | |
139 | |
140 if __name__ == '__main__': | |
141 engine_dir = '/opt/google_appengine' | |
142 storage_path = '/var/lib/rietveld' | |
143 | |
144 script_name, script_file = setup_paths(engine_dir) | |
145 adjust_server_id() | |
146 fix_request_scheme() | |
147 | |
148 if script_name == 'dev_appserver.py': | |
149 set_storage_path(storage_path) | |
150 replace_runtime() | |
151 protect_cookies(os.path.join(storage_path, 'cookie_secret')) | |
152 enable_oauth2() | |
153 | |
154 execfile(script_file) | |
OLD | NEW |