forked from GoogleChromeLabs/credential-management-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
265 lines (203 loc) · 8.05 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/python
# Copyright Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# coding: -*- utf-8 -*-
from google.appengine.ext import vendor
vendor.add('lib')
import os
import sys
import binascii
import json
import urllib
from bcrypt import bcrypt
from flask import Flask, request, make_response, render_template, session
from oauth2client import client
from google.appengine.ext import ndb
from google.appengine.api import urlfetch
FACEBOOK_APPID=os.getenv('FACEBOOK_APPID')
FACEBOOK_APPTOKEN=os.getenv('FACEBOOK_APPTOKEN', None)
app = Flask(
__name__,
static_url_path='',
static_folder='static',
template_folder='templates'
)
app.debug = True
# Does `client_secrets.json` file exist?
if os.path.isfile('client_secrets.json') is False:
sys.exit('client_secrets.json not found.')
# Load `client_secrets.json` file
keys = json.loads(open('client_secrets.json', 'r').read())['web']
CLIENT_ID = keys['client_id']
# `SECRET_KEY` can be anything as long as it is hidden, but we use
# `client_secret` here for convenience
SECRET_KEY = keys['client_secret']
app.config.update(
SECRET_KEY=SECRET_KEY
)
# App Engine Datastore to save credentials
class CredentialStore(ndb.Model):
profile = ndb.JsonProperty()
@classmethod
def remove(cls, key):
ndb.Key(cls.__name__, key).delete()
@classmethod
def hash(cls, password):
return bcrypt.hashpw(password, bcrypt.gensalt())
@classmethod
def verify(cls, password, hashed):
if bcrypt.hashpw(password, hashed) == hashed:
return True
else:
return False
@app.before_request
def csrf_protect():
# All incoming POST requests will pass through this
if request.method == 'POST':
# Obtain the custom request header to check if this request
# is from a browser and is intentional.
header = request.headers.get('X-Requested-With', None)
if not header:
# Return 403 if empty or they are different
return make_response('', 403)
@app.route('/')
def index():
return render_template('index.html', client_id=CLIENT_ID,
FACEBOOK_APPID=FACEBOOK_APPID)
@app.route('/auth/password', methods=['POST'])
def pwauth():
# The POST should include `email`
email = request.form.get('email', None)[:32]
# The POST should include `password`
password = request.form.get('password', None)[:32]
# Validate the parameters POST'ed (intentionally not too strict)
if not email or not password:
return make_response('Bad Request', 400)
# Obtain Datastore entry by email address
store = CredentialStore.get_by_id(email)
# If the store doesn't exist, fail.
if store is None:
return make_response('Authentication failed.', 401)
profile = store.profile
# If the profile doesn't exist, fail.
if profile is None:
return make_response('Authentication failed.', 401)
# If the password doesn't match, fail.
if CredentialStore.verify(password, profile['password']) is False:
return make_response('Authentication failed.', 401)
# Get rid of password from profile
profile.pop('password')
# Not making a session for demo purpose/simplicity
return make_response(json.dumps(profile), 200)
@app.route('/auth/google', methods=['POST'])
def gauth():
# The POST should include `id_token`
id_token = request.form.get('id_token', '')[:3072]
# Verify the `id_token` using API Client Library
idinfo = client.verify_id_token(id_token, CLIENT_ID)
# Additional verification: See if `iss` matches Google issuer string
if idinfo['iss'] not in ['accounts.google.com',
'https://accounts.google.com']:
return make_response('Wrong Issuer.', 401)
# For now, we'll always store profile data after successfully
# verifying the token and consider the user authenticated.
store = CredentialStore(id=idinfo['sub'], profile=idinfo)
store.put()
# Construct a profile object
profile = {
'id': idinfo.get('sub', None),
'imageUrl': idinfo.get('picture', None),
'name': idinfo.get('name', None),
'email': idinfo.get('email', None)
}
# Not making a session for demo purpose/simplicity
return make_response(json.dumps(profile), 200)
@app.route('/auth/facebook', methods=['POST'])
def fblogin():
# The POST should include `access_token` from Facebook
access_token = request.form.get('access_token', None)[:3072]
# If the access_token is `None`, fail.
if access_token is None:
return make_response('Authentication failed.', 401)
app_token = FACEBOOK_APPTOKEN if FACEBOOK_APPTOKEN is not None else access_token
# Verify the access token using Facebook API
params = {
'input_token': access_token,
'access_token': app_token
}
r = urlfetch.fetch('https://graph.facebook.com/debug_token?' +
urllib.urlencode(params))
result = json.loads(r.content)
# If the response includes `is_valid` being false, fail
if result['data']['is_valid'] is False:
return make_response('Authentication failed.', 401)
# Make an API request to Facebook using OAuth
r = urlfetch.fetch('https://graph.facebook.com/me?fields=name,email',
headers={'Authorization': 'OAuth '+access_token})
idinfo = json.loads(r.content)
# Save the Facebook profile
store = CredentialStore(id=idinfo['id'], profile=idinfo)
store.put()
# Obtain the Facebook user's image
profile = idinfo
profile['imageUrl'] = 'https://graph.facebook.com/' + profile['id'] +\
'/picture?width=96&height=96'
# Not making a session for demo purpose/simplicity
return make_response(json.dumps(profile), 200)
@app.route('/register', methods=['POST'])
def register():
# The POST should include `email`
email = request.form.get('email', None)[:32]
# The POST should include `password`
_password = request.form.get('password', None)[:32]
# Validate the parameters POST'ed (intentionally not too strict)
if not email or not _password:
return make_response('Bad Request', 400)
# Hash password
password = CredentialStore.hash(_password)
# Perform relevant sanitization/validation on your own code.
# This demo omits them on purpose for simplicity.
profile = {
'id': email,
'email': email,
'name': request.form.get('name', ''),
'password': password,
'imageUrl': 'images/default_img.png'
}
# Overwrite existing user
store = CredentialStore(id=profile['id'], profile=profile)
store.put()
# Get rid of password from profile
profile.pop('password')
# Not making a session for demo purpose/simplicity
return make_response(json.dumps(profile), 200)
@app.route('/unregister', methods=['POST'])
def unregister():
if 'id' not in request.form:
make_response('User id not specified', 400)
id = request.form.get('id', '')
store = CredentialStore.get_by_id(str(id))
if store is None:
make_response('User not registered', 400)
if not hasattr(store, 'profile'):
return make_response('{"status":"failure"}', 400)
profile = store.profile
# Remove the user account
CredentialStore.remove(str(id))
# Not terminating a session for demo purpose/simplicity
return make_response('{"status":"success"}', 200)
@app.route('/signout', methods=['POST'])
def signout():
# Not terminating a session for demo purpose/simplicity
return make_response(json.dumps({}), 200)