-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
556 lines (402 loc) · 16.4 KB
/
api.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
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
from flask import Flask, request, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
import uuid
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
import datetime
from functools import wraps
from dotenv import load_dotenv
import os
app = Flask(__name__)
load_dotenv()
# Obfuscation of sensitive information using environment variables.
app.config["SECRET_KEY"] = os.getenv("STUDYCARDS_SECRET_KEY")
POSTGRES_URL = os.getenv("POSTGRES_URL")
POSTGRES_USER = os.getenv("POSTGRES_USER")
POSTGRES_PW = os.getenv("POSTGRES_PW")
POSTGRES_DB = os.getenv("POSTGRES_DB")
JWT_DECODE_ALG = os.getenv("JWT_DECODE_ALG")
PASSWORD_HASH_METHOD = os.getenv("PASSWORD_HASH_METHOD")
app.config["SQLALCHEMY_DATABASE_URI"] = f"postgresql+psycopg2://{POSTGRES_USER}:{POSTGRES_PW}@{POSTGRES_URL}/{POSTGRES_DB}"
db = SQLAlchemy(app)
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# ***** Database Tables *****
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
class User(db.Model):
__tablename__ = "User"
id = db.Column(db.Integer, primary_key=True, nullable=False)
public_id = db.Column(db.String, unique=True)
username = db.Column(db.String, unique=True)
password = db.Column(db.String)
admin = db.Column(db.Boolean)
studysets = db.relationship('StudySet', backref='owner_user', lazy=True, cascade='all, delete-orphan')
class StudySet(db.Model):
__tablename__ = "StudySet"
id = db.Column(db.Integer, primary_key=True, nullable=False)
name = db.Column(db.String)
owner_user_id = db.Column(db.Integer, db.ForeignKey('User.id', ondelete='CASCADE'), nullable=False)
termdefs = db.relationship('TermDefinition', backref='owner_set', lazy=True, cascade='all, delete-orphan')
class TermDefinition(db.Model):
__tablename__ = "TermDefinition"
id = db.Column(db.Integer, primary_key=True, nullable=False)
owner_set_id = db.Column(db.Integer, db.ForeignKey('StudySet.id', ondelete='CASCADE'), nullable=False)
term = db.Column(db.String)
definition = db.Column(db.String)
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# ***** JSON Token Implementation for User Authentication *****
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
if 'x-access-token' in request.headers:
token = request.headers["x-access-token"]
if not token:
return jsonify({"message": "Token is missing."}), 401
try:
data = jwt.decode(token, app.config["SECRET_KEY"], algorithms=[JWT_DECODE_ALG])
current_user = User.query.filter_by(public_id=data["public_id"]).first()
except jwt.ExpiredSignatureError:
return jsonify({"message": "Token has expired."}), 401
except:
return jsonify({"message": "Token is invalid."}), 401
return f(current_user, *args, **kwargs)
return decorated
@app.route("/api/login/verify", methods=["GET"])
@token_required
def check_login(current_user):
return jsonify({"message": "Token is valid."})
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# ***** User Implementation *****
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# REQUIRES:
# * Must be logged in as a user with admin=True
# MODIFIES:
# * N/A
# EFFECTS:
# * Returns a list of all users in the database
@app.route("/api/user", methods=["GET"])
@token_required
def get_all_users(current_user):
if not current_user.admin:
return jsonify({"message": "Cannot perform that function. "})
users = User.query.all()
output = []
for user in users:
user_data = {}
user_data["public_id"] = user.public_id
user_data["username"] = user.username
user_data["admin"] = user.admin
output.append(user_data)
return jsonify({"users": output})
# REQUIRES:
# * Must be logged in as a user with admin=True
# MODIFIES:
# * N/A
# EFFECTS:
# * Returns information about the specified user from the database
@app.route("/api/user/<public_id>", methods=["GET"])
@token_required
def get_one_user(current_user, public_id):
if not current_user.admin:
return jsonify({"message": "Cannot perform that function. "})
user = User.query.filter_by(public_id=public_id).first()
if not user:
return jsonify({"message": "No user found."})
user_data = {}
user_data["public_id"] = user.public_id
user_data["username"] = user.username
user_data["admin"] = user.admin
return jsonify({"user": user_data})
# REQUIRES:
# * Body of HTTP request must be in JSON format containing the following keys:
# * "username"
# * "password"
# MODIFIES:
# * User table in database
# EFFECTS:
# * Registers a new user account.
# * Creates a new instance of User and adds it as a row to the User table in the database.
@app.route("/api/user", methods=["POST"])
def create_user():
data = request.get_json()
if not ("username" in data and "password" in data):
return jsonify({"message": "Insufficient data. Have 'username' and 'password' in request body."})
user = User.query.filter_by(username=data["username"]).first()
if not user == None:
return jsonify({"message": "username already taken"})
hashed_password = generate_password_hash(data["password"], method=PASSWORD_HASH_METHOD, salt_length=8)
new_user = User(public_id=str(uuid.uuid4()), username=data["username"], password=hashed_password, admin=False)
db.session.add(new_user)
db.session.commit()
return jsonify({"message" : "New user created."})
@app.route("/api/username/<username>", methods=["GET"])
def check_username_availability(username):
user = User.query.filter_by(username=username).first()
if not user == None:
return jsonify({"message": "username already taken"})
return jsonify({"message" : "username available."})
# REQUIRES:
# * Must be logged in as a user with admin=True
# MODIFIES:
# * .admin member of User with specified public_id
# EFFECTS:
# * Promotes the specified user to admin status.
@app.route("/api/user/<public_id>", methods=["PUT"])
@token_required
def promote_user(public_id):
if not current_user.admin:
return jsonify({"message": "Cannot perform that function. "})
user = User.query.filter_by(public_id=public_id).first()
if not user:
return jsonify({"message": "No user found."})
user.admin = True
db.session.commit()
return jsonify({"message": "The user has been promoted."})
# REQUIRES:
# * Must be logged in as a user with admin=True or as the user to be deleted
# MODIFIES:
# * User table in database.
# EFFECTS:
# * Deletes the user with the specified public_id.
@app.route("/api/user/<public_id>", methods=["DELETE"])
@token_required
def delete_user(current_user, public_id):
if not current_user.admin or not current_user.public_id == public_id:
return jsonify({"message": "Cannot perform that function. "})
user = User.query.filter_by(public_id=public_id).first()
if not user:
return jsonify({"message": "No user found."})
db.session.delete(user)
db.session.commit()
return jsonify({"message": "The user has been deleted."})
# REQUIRES:
# * HTTP request must use Basic Authorization to fill in username and password info.
# MODIFIES:
# * N/A
# EFFECTS:
# * Logins in user by returning a JSON web token
# * Any route decorated with @token_requires needs
# the provided JSON token in a header as the value
# of a key named "x-access-token"
@app.route("/api/login")
def login():
auth = request.authorization
if not auth or not auth.username or not auth.password:
return make_response("Could not verify", 401, {"WWW-Authenticate": "Basic realm='Login required.'"})
user = User.query.filter_by(username=auth.username).first()
if not user:
return make_response("Could not verify", 401, {"WWW-Authenticate": "Basic realm='Login required.'"})
if check_password_hash(user.password, auth.password):
token = jwt.encode({"public_id" : user.public_id, "exp" : datetime.datetime.utcnow() + datetime.timedelta(minutes=120)}, app.config["SECRET_KEY"])
return jsonify({"token": token})
return make_response("Could not verify", 401, {"WWW-Authenticate": "Basic realm='Login required.'"})
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# ***** StudySet Implementation *****
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
@app.route("/api/my-study-sets", methods=["GET"])
@token_required
def get_all_studysets(current_user):
sets = []
for set in current_user.studysets:
set_data = {}
set_data["id"] = set.id
set_data["name"] = set.name
set_data["owner_user_id"] = set.owner_user_id
sets.append(set_data)
return jsonify({"StudySets": sets})
@app.route("/api/my-study-sets", methods=["POST"])
@token_required
def create_studyset(current_user):
data = request.get_json()
new_studyset = StudySet(name=data["studyset_name"], owner_user_id=current_user.id)
db.session.add(new_studyset)
db.session.commit()
return jsonify({"message": "New StudySet created", "studyset_id": f"{new_studyset.id}"})
@app.route("/api/my-study-sets/<studyset_id>", methods=["DELETE"])
@token_required
def delete_studyset(current_user, studyset_id):
try:
study_set_id = int(studyset_id)
except:
return jsonify({"message": "StudySet ID could not be converted to integer.",
"ID": study_set_id})
studyset = None
for set in current_user.studysets:
if set.id == study_set_id:
studyset = set
break
if not studyset:
return jsonify({"message": "No StudySet found."})
db.session.delete(studyset)
db.session.commit()
return jsonify({"message": "StudySet deleted"})
@app.route("/api/my-study-sets/<studyset_id>", methods=["PUT"])
@token_required
def modify_studyset(current_user, studyset_id):
data = request.get_json()
try:
study_set_id = int(study_set_id)
except:
return jsonify({"message": "No StudySet found."})
studyset = None
for set in current_user.studysets:
if set.id == study_set_id:
studyset = set
break
if not studyset:
return jsonify({"message": "No StudySet found."})
studyset.name = data["new_name"]
db.session.commit()
return jsonify({"message": "StudySet modified"})
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# ***** TermDefinition Implementation *****
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
@app.route("/api/my-study-sets/<study_set_id>", methods=["GET"])
@token_required
def get_all_termdefs(current_user, study_set_id):
try:
study_set_id = int(study_set_id)
except:
return jsonify({"message": "No StudySet found."})
studyset = None
for set in current_user.studysets:
if set.id == study_set_id:
studyset = set
break
if not studyset:
return jsonify({"message": "No StudySet found."})
termdefs = []
for termdef in studyset.termdefs:
data = {}
data["id"] = termdef.id
data["term"] = termdef.term
data["definition"] = termdef.definition
termdefs.append(data)
return jsonify({"message": "StudySet found.",
"Terms in StudySet": termdefs,
"StudySet Name": studyset.name})
@app.route("/api/my-study-sets/<study_set_id>", methods=["POST"])
@token_required
def create_termdef(current_user, study_set_id):
try:
study_set_id = int(study_set_id)
except:
return jsonify({"message": "No StudySet found."})
studyset = None
for set in current_user.studysets:
if set.id == study_set_id:
studyset = set
break
if not studyset:
return jsonify({"message": "No StudySet found."})
data = request.get_json()
new_termdefs = data["new_termdefs"]
for termdef in new_termdefs:
db.session.add(TermDefinition(term=termdef["term"], definition=termdef["definition"], owner_set=studyset))
db.session.commit()
return jsonify({"message": "New TermDef(s) created"})
@app.route("/api/my-study-sets/<study_set_id>/all-contents", methods=["DELETE"])
@token_required
def bulk_delete_termdefs(current_user, study_set_id):
try:
study_set_id = int(study_set_id)
except:
return jsonify({"message": "No StudySet found."})
studyset = None
for set in current_user.studysets:
if set.id == study_set_id:
studyset = set
break
if not studyset:
return jsonify({"message": "No StudySet found."})
for termdef in studyset.termdefs:
db.session.delete(termdef)
db.session.commit()
return jsonify({"message": "All termdefs deleted"})
@app.route("/api/my-study-sets/<study_set_id>/all-contents", methods=["PUT"])
@token_required
def bulk_edit(current_user, study_set_id):
try:
study_set_id = int(study_set_id)
except:
return jsonify({"message": "No StudySet found."})
studyset = None
for set in current_user.studysets:
if set.id == study_set_id:
studyset = set
break
if not studyset:
return jsonify({"message": "No StudySet found."})
for termdef in studyset.termdefs:
db.session.delete(termdef)
data = request.get_json()
new_termdefs = data["new_termdefs"]
for termdef in new_termdefs:
db.session.add(TermDefinition(term=termdef["term"], definition=termdef["definition"], owner_set=studyset))
studyset.name = data["new_name"]
db.session.commit()
return jsonify({"message": "StudySet recreated in bulk"})
@app.route("/api/my-study-sets/<study_set_id>/<termdef_id>", methods=["DELETE"])
@token_required
def delete_termdef(current_user, study_set_id, termdef_id):
try:
study_set_id = int(study_set_id)
except:
return jsonify({"message": "No StudySet found."})
studyset = None
for set in current_user.studysets:
if set.id == study_set_id:
studyset = set
break
if not studyset:
return jsonify({"message": "No StudySet found."})
data = request.get_json()
termdef = None
for td in studyset.termdefs:
if td.id == int(termdef_id):
termdef = td
break
if not termdef:
return jsonify({"message": "No TermDef found."})
db.session.delete(termdef)
db.session.commit()
return jsonify({"message": "TermDef deleted"})
@app.route("/api/my-study-sets/<study_set_id>/<termdef_id>", methods=["PUT"])
@token_required
def modify_termdef(current_user, study_set_id, termdef_id):
try:
study_set_id = int(study_set_id)
except:
return jsonify({"message": "No StudySet found."})
studyset = None
for set in current_user.studysets:
if set.id == study_set_id:
studyset = set
break
if not studyset:
return jsonify({"message": "No StudySet found."})
data = request.get_json()
termdef = None
for td in studyset.termdefs:
if td.id == int(termdef_id):
termdef = td
break
if not termdef:
return jsonify({"message": "No TermDef found."})
termdef.term = data["new_term"]
termdef.definition = data["new_definition"]
db.session.commit()
return jsonify({"message": "TermDef modified"})
if __name__ == "__main__":
app.run(debug=True)