Repository navigation
Expand file tree
/
Copy pathapi.py
More file actions
514 lines (412 loc) · 21.5 KB
/
Copy pathapi.py
File metadata and controls
514 lines (412 loc) · 21.5 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
from flask import Flask, request, abort, url_for, render_template, session, Response, redirect
from flask import g
from flask_cors import CORS, cross_origin
from flask_restful import Resource, Api
from passlib.hash import sha512_crypt
from database import DatabaseManager
from myemail import *
from validate_email import validate_email
import time
import ssl
import json
from urllib.request import urlopen
# Config
SECRET_KEY = "development key"
# Encryption config
SECURITY_PASSWORD_SALT = 'securitykey'
app = Flask(__name__)
CORS(app)
app.config.from_object(__name__)
api = Api(app)
app.config['CORS_HEADERS'] = 'Content-Type'
# Set caching header
def response_cache_header(response, cache_control="max-age=120"):
r = Response(response)
r.headers['Cache-Control'] = cache_control # Two minutes by default
return r
@app.route('/')
def redirect_homepage():
return redirect("https://woording.com")
# Register
@app.route('/register', methods = ['POST'])
def register():
db_manager = DatabaseManager()
username = request.json.get('username')
password = sha512_crypt.encrypt(request.json.get('password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000)
email = request.json.get('email')
email = email.lower()
if not validate_email(email):
return response_cache_header(json.dumps({"response":"Not a valid email address", "success": False}), cache_control="no-cache")
# Check if everything filled in
elif username is None or password is None or email is None:
return abort(400) # missing arguments
# Check if already exists
elif db_manager.username_exists(username) or db_manager.email_exists(email):
# username and/or email do already exist
return response_cache_header(json.dumps({"response":"ERROR, username and/or email already exist", "success": False}), cache_control="no-cache")
else:
db_manager.create_user(username=username, password_hash=password, email=email, email_verified=False)
# Email verification
token = generate_confirmation_token(email)
confirm_url = 'https://api.woording.com/verify/' + token
html = render_template('email.html', confirm_url=confirm_url)
subject = "Please confirm your email"
send_email(email, subject, html)
return response_cache_header(json.dumps({"response":"Succesfully created user, please verify email.", "success": True}), cache_control="no-cache")
# Verify email
@app.route('/verify/<token>')
def verify_email(token):
db_manager = DatabaseManager()
email = confirm_token(token)
if db_manager.email_is_verified(email):
return response_cache_header("Email already verified.\n", cache_control="no-cache")
else:
# Verify
db_manager.verify_email(email)
return response_cache_header("Email Successfully verified.\n", cache_control="no-cache")
# Authenticate user
@app.route('/authenticate', methods=['POST'])
def authenticate():
db_manager = DatabaseManager()
username = request.json.get('username')
password = sha512_crypt.encrypt(request.json.get('password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000)
if username and password:
if db_manager.get_user(username):
if db_manager.get_user(username).get('email_verified'):
# Check password
if db_manager.check_password(username, password):
token = db_manager.generate_auth_token(username.lower(), password).decode("utf-8")
user_id = db_manager.get_user(username).get("id")
return response_cache_header(json.dumps({
"token": token,
"success": True
}))
else:
return response_cache_header( json.dumps({ "error":"Incorrect password and/or username", "success":False }), cache_control="no-cache")
else:
return response_cache_header(json.dumps({"error":"Email not verified", "success":False}), cache_control="no-cache")
else:
return response_cache_header(json.dumps({"error":"User does not exist", "success":False}), cache_control="no-cache")
else:
return Response('Login!', 401, {'WWW-Authenticate': 'Basic realm="Login!"'})
@app.route('/storeSession', methods=['POST'])
def store():
db_manager = DatabaseManager()
token = request.json.get('token')
# password = sha512_crypt.encrypt(request.json.get('password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000)
selector = request.json.get('selector')
if selector:
db_manager.add_auth_token(selector, token)
return response_cache_header(json.dumps({"response":"Stored session", "success":True}), cache_control="no-cache")
else:
return response_cache_header(json.dumps({"error":"Not satisfied", "success":False}), cache_control="no-cache")
@app.route('/removeSession', methods=['POST'])
def remove():
db_manager = DatabaseManager()
selector = request.json.get('selector')
if selector:
db_manager.remove_auth_token(selector)
return response_cache_header(json.dumps({"response":"Removed Session", "success":True}), cache_control="no-cache")
else:
return response_cache_header(json.dumps({"response":"Did not remove session", "success":False}), cache_control="no-cache")
@app.route('/retrieveSession', methods=['POST'])
def remember():
db_manager = DatabaseManager()
selector = request.json.get('selector')
if selector:
data = db_manager.get_auth_id(selector)
if data:
token = json.loads(data)['token']
return response_cache_header(json.dumps({"token":token, "success":True}), cache_control="no-cache")
else:
return response_cache_header(json.dumps({"error":"no session", "success":False}), cache_control="no-cache")
else:
return response_cache_header(json.dumps({"error":"no session", "success":False}), cache_control="no-cache")
# Validate Captcha
@app.route('/validateCaptcha', methods=['POST'])
def validate():
url = request.json.get('url')
if url == None:
abort(400)
else:
response = urlopen(url)
data = response.read()
success = json.loads(data.decode('utf-8'))['success']
return response_cache_header(json.dumps({'answer':success}), cache_control="no-cache")
# Save list
@app.route('/savelist', methods=['POST'])
def save_list():
db_manager = DatabaseManager()
username = request.json.get('username').lower()
list_data = request.json.get('list_data')
token = request.json.get('token')
if username == None or list_data == None or token == None:
abort(400)
# Verifiy token
token_credentials = db_manager.verify_auth_token(token=token)
if token_credentials is None:
abort(401)
elif not db_manager.check_password(token_credentials[0], token_credentials[1]):
abort(401)
elif token_credentials[0] != username:
abort(401)
if len(list_data.get('listname')) > 20:
print(list_data['listname'][:20])
list_data['listname'] = list_data['listname'][:20]
if list_data.get('listname') is None or list_data.get('language_1_tag') is None or list_data.get('language_2_tag') is None or list_data.get('shared_with') is None:
abort(400)
if list_data.get('listname') is "" or list_data.get('language_1_tag') is "" or list_data.get('language_2_tag') is "" or list_data.get('shared_with') is "":
abort(400)
if db_manager.listname_exists_for_user(username, list_data.get('listname')):
old_list = db_manager.get_list(username, list_data['listname'])
old_words = db_manager.get_translations_for_list(username, list_data['listname'])
db_manager.delete_list(username, list_data.get('listname'))
db_manager.create_list(username, list_data.get('listname'), list_data.get('language_1_tag'), list_data.get('language_2_tag'), list_data.get('shared_with'))
words = list_data.get('words')
for i in range(len(words)):
word = words[i]
if word.get('language_1_text') is u'' or word.get('language_2_text') is u'':
continue
db_manager.create_translation(username, list_data.get('listname'), word.get('language_1_text'), word.get('language_2_text'))
return response_cache_header(json.dumps( { 'response' : 'List exists', 'old_list':old_list, 'old_words':old_words } ), cache_control="no-cache")
db_manager.create_list(username, list_data.get('listname'), list_data.get('language_1_tag'), list_data.get('language_2_tag'), list_data.get('shared_with'))
words = list_data.get('words')
for i in range(len(words)):
word = words[i]
if word.get('language_1_text') is u'' or word.get('language_2_text') is u'':
continue
db_manager.create_translation(username, list_data.get('listname'), word.get('language_1_text'), word.get('language_2_text'))
return response_cache_header(json.dumps( { 'response' : 'Saved list!', 'listname' : list_data.get('listname') } ), cache_control="no-cache")
@app.route('/deleteList', methods=['POST'])
def delete_list():
db_manager = DatabaseManager()
username = request.json.get('username').lower()
listname = request.json.get('listname')
token = request.json.get('token')
if username == None or listname == None or token == None:
abort(400)
# Verifiy token
token_credentials = db_manager.verify_auth_token(token=token)
if token_credentials is None:
abort(401)
elif not db_manager.check_password(token_credentials[0], token_credentials[1]):
abort(401)
elif token_credentials[0] != username:
abort(401)
if not db_manager.listname_exists_for_user(username, listname):
return response_cache_header("No list found", cache_control="no-cache")
if db_manager.listname_exists_for_user(username, listname):
db_manager.delete_list(username, listname)
return response_cache_header(json.dumps( { 'response':'Successfully deleted list' } ), cache_control="no-cache")
return abort(401)
# Friends
@app.route('/friendRequest', methods=['POST'])
def friend_request():
db_manager = DatabaseManager()
username = request.json.get('username')
friendname = request.json.get('friendname')
if username == None or friendname == None:
abort(400)
if db_manager.username_exists(username) and db_manager.username_exists(friendname):
if not db_manager.users_are_friends(username, friendname):
email = db_manager.get_user(friendname).get("email")
# Email request
token = generate_confirmation_token([ username, friendname])
confirm_url = 'https://api.woording.com/acceptFriend/' + token
html = render_template('friend.html', confirm_url=confirm_url, name=username)
subject = "New friend request"
send_email(email, subject, html)
return response_cache_header("Email sent", cache_control="no-cache")
else:
return response_cache_header("ERROR, already friends", cache_control="no-cache")
@app.route('/acceptFriend/<token>')
def accept_friend(token):
db_manager = DatabaseManager()
names = confirm_token(token)
if db_manager.users_are_friends(names[0], names[1]):
return response_cache_header("Already friends", cache_control="no-cache")
else:
db_manager.create_friendship(names[0], names[1])
return response_cache_header("Now friends", cache_control="no-cache")
@app.route('/getFriends', methods=['POST'])
def get_friends():
db_manager = DatabaseManager()
username = request.json.get('username').lower()
token = request.json.get('token')
if username == None or token == None:
abort(400)
# Verifiy token
token_credentials = db_manager.verify_auth_token(token=token)
if token_credentials is None:
abort(401)
elif not db_manager.check_password(token_credentials[0], token_credentials[1]):
abort(401)
elif token_credentials[0] != username:
abort(401)
friends = db_manager.get_friends_for_user(username)
# It is unsafe to send your friends password hash to the browser... email_verified and id aren't needed
for friend in friends:
if friend == None:
friends.remove(friend)
continue
del friend['password_hash']; del friend['email_verified']; del friend['id']
return response_cache_header(json.dumps({"friends":friends}))
@app.route('/changePassword', methods=['POST'])
def change_password():
db_manager = DatabaseManager()
username = request.json.get('username')
old_password = sha512_crypt.encrypt(request.json.get('old_password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000)
new_password = sha512_crypt.encrypt(request.json.get('new_password'), salt=app.config['SECURITY_PASSWORD_SALT'], rounds=5000)
token = request.json.get('token')
# Not everything filled in
if username == None or old_password == None or new_password == None or token == None:
abort(400)
# Verifiy token
token_credentials = db_manager.verify_auth_token(token=token)
if token_credentials is None:
abort(401)
elif not db_manager.check_password(token_credentials[0], token_credentials[1]):
abort(401)
elif token_credentials[0] != username:
abort(401)
if db_manager.check_password(username, old_password):
db_manager.change_password(username, old_password, new_password)
return response_cache_header("Changed password", cache_control="no-cache")
else:
return response_cache_header("ERROR, Wrong password", cache_control="no-cache")
# REST Recource with app.route
@app.route('/<username>', methods=["POST"])
def get(username):
db_manager = DatabaseManager()
username = username.lower()
token = request.json.get('token')
if token is None or token is "":
return abort(401)
# Verifiy token
token_credentials = db_manager.verify_auth_token(token=token)
if token_credentials is None:
return abort(401)
elif not db_manager.check_password(token_credentials[0], token_credentials[1]):
return abort(401)
if db_manager.username_exists(username):
# Return all lists
if token_credentials[0] == username:
user_info = db_manager.get_user(username)
list_lists = db_manager.get_lists_for_user(username)
for l in list_lists: del l['user_id']; del l['id']
return response_cache_header(json.dumps({
'username': user_info.get("username"),
'email' : user_info.get("email"),
'lists' : list_lists
}))
# Return friend lists if you are friends
elif db_manager.users_are_friends(username, token_credentials[0]):
user_info = db_manager.get_user(username)
list_lists = db_manager.get_lists_for_user(username)
for l in list_lists[:]: # Make a slice copy of the entire list
if l['shared_with'] == "0":
list_lists.remove(l)
del l['user_id']
del l['id']
return response_cache_header(json.dumps({
'username': user_info.get("username"),
'email' : user_info.get("email"),
'lists' : list_lists
}))
# Return everyone shared lists
else:
user_info = db_manager.get_user(username)
list_lists = db_manager.get_lists_for_user(username)
for l in list_lists[:]: # Make a slice copy of the entire list
if l['shared_with'] != "2":
list_lists.remove(l)
del l['user_id']
del l['id']
return response_cache_header(json.dumps({
'username': user_info.get("username"),
'email' : user_info.get("email"),
'lists' : list_lists
}))
else:
return response_cache_header(json.dumps({"error":"User not found" + username}), cache_control="no-cache")
@app.route('/<username>/<listname>', methods=['POST'])
def show_user_list(username, listname):
db_manager = DatabaseManager()
username = username.lower()
token = request.json.get("token")
if token is None or token is "" and db_manager.username_exists(username) and db_manager.listname_exists_for_user(username, listname):
list_data = db_manager.get_list(username, listname)
shared_with = list_data.get("shared_with")
translations = db_manager.get_translations_for_list(username, listname)
for translation in translations: del translation['id']; del translation['list_id']
return response_cache_header(json.dumps({
'listname' : listname,
'language_1_tag' : list_data.get("language_1_tag"),
'language_2_tag' : list_data.get("language_2_tag"),
'words' : translations,
'shared_with' : shared_with
}))
else:
return abort(401)
# Verifiy token
token_credentials = db_manager.verify_auth_token(token=token)
if token_credentials is None:
return abort(401)
elif not db_manager.check_password(token_credentials[0], token_credentials[1]):
return abort(401)
if db_manager.username_exists(username):
if db_manager.listname_exists_for_user(username, listname):
list_data = db_manager.get_list(username, listname)
shared_with = list_data.get("shared_with")
translations = db_manager.get_translations_for_list(username, listname)
for translation in translations: del translation['id']; del translation['list_id']
# Check if is owner
if username == token_credentials[0]:
return response_cache_header(json.dumps({
'listname' : listname,
'language_1_tag' : list_data.get("language_1_tag"),
'language_2_tag' : list_data.get("language_2_tag"),
'words' : translations,
'shared_with' : shared_with
}))
# Check if is friend
elif shared_with == '1' and db_manager.users_are_friends(username, token_credentials[0]):
return response_cache_header(json.dumps({
'listname' : listname,
'language_1_tag' : list_data.get("language_1_tag"),
'language_2_tag' : list_data.get("language_2_tag"),
'words' : translations,
'shared_with' : shared_with
}))
elif shared_with == '2':
return response_cache_header(json.dumps({
'listname' : listname,
'language_1_tag' : list_data.get("language_1_tag"),
'language_2_tag' : list_data.get("language_2_tag"),
'words' : translations,
'shared_with' : shared_with
}))
else:
abort(401)
else:
return response_cache_header(json.dumps({"error":"List not found"}), cache_control="no-cache")
else:
return response_cache_header(json.dumps({"error":"User not found"}), cache_control="no-cache")
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
return response
# LOEN PLS FIX SSL API KEY STUFF
# |
# |
# V
# context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
# context.load_cert_chain('apicert.crt', 'apikey.key')
# Run app
# if __name__ == '__main__':
# app.run(host='0.0.0.0', port=5000)
# Run app no ssl
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=True)