-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1892 lines (1672 loc) · 70.3 KB
/
app.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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# MIT License
#
# Copyright (c) 2020-2023 Send A Hug
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# The provided Software is separate from the idea behind its website. The Send A Hug
# website and its underlying design and ideas are owned by Send A Hug group and
# may not be sold, sub-licensed or distributed in any way. The Software itself may
# be adapted for any purpose and used freely under the given conditions.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import json
import math
import sys
import http.client
from datetime import datetime
from flask import Flask, request, abort, jsonify
from flask_cors import CORS
from pywebpush import webpush, WebPushException
from models import (
create_db,
Post,
User,
Message,
Thread,
Report,
Notification,
NotificationSub,
Filter,
add as db_add,
update as db_update,
delete_object as db_delete,
delete_all as db_delete_all,
update_multiple as db_update_multi,
joined_query,
)
from auth import (
AuthError,
requires_auth,
check_mgmt_api_token,
get_management_api_token,
AUTH0_DOMAIN,
)
from filter import WordFilter
from validator import Validator, ValidationError
from utils.push_notifications import generate_push_data, generate_vapid_claims
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__)
create_db(app)
CORS(app, origins="")
word_filter = WordFilter()
validator = Validator(
{
"post": {"max": 480, "min": 1},
"message": {"max": 480, "min": 1},
"user": {"max": 60, "min": 1},
"report": {"max": 120, "min": 1},
}
)
# CORS Setup
@app.after_request
def after_request(response):
response.headers.add("Access-Control-Allow-Origin", os.environ.get("FRONTEND"))
response.headers.add(
"Access-Control-Allow-Methods",
"GET, POST,\
PATCH, DELETE, OPTIONS",
)
response.headers.add(
"Access-Control-Allow-Headers",
"Authorization,\
Content-Type",
)
return response
# Paginates posts / messages
def paginate(items, page):
items_per_page = 5
start_index = (page - 1) * items_per_page
paginated_items = items[start_index : (start_index + 5)]
total_pages = math.ceil(len(items) / 5)
return [paginated_items, total_pages]
# Send push notification
def send_push_notification(user_id, data):
vapid_key = os.environ.get("PRIVATE_KEY")
notification_data = generate_push_data(data)
vapid_claims = generate_vapid_claims()
subscriptions = NotificationSub.query.filter(
NotificationSub.user == user_id
).all()
# Try to send the push notification
try:
for subscription in subscriptions:
sub_data = json.loads(subscription.subscription_data)
webpush(
subscription_info=sub_data,
data=json.dumps(notification_data),
vapid_private_key=vapid_key,
vapid_claims=vapid_claims,
)
# If there's an error, print the details
except WebPushException as e:
print(e)
# Routes
# -----------------------------------------------------------------
# Endpoint: GET /
# Description: Gets recent and suggested posts.
# Parameters: None.
# Authorization: None.
@app.route("/")
def index():
# Gets the ten most recent posts
recent_posts = joined_query("main new")["return"]
# Gets the ten posts with the least hugs
suggested_posts = joined_query("main suggested")["return"]
return jsonify(
{"success": True, "recent": recent_posts, "suggested": suggested_posts}
)
# Endpoint: POST /
# Description: Run a search.
# Parameters: None.
# Authorization: None.
@app.route("/", methods=["POST"])
def search():
search_query = json.loads(request.data)["search"]
current_page = request.args.get("page", 1, type=int)
# Check if the search query is empty; if it is, abort
validator.check_length(search_query, "Search query")
# Check if the search query isn't a string; if it isn't, abort
validator.check_type(search_query, "Search query")
# Get the users with the search query in their display name
users = User.query.filter(
User.display_name.ilike("%" + search_query + "%")
).all()
posts = joined_query("post search", {"query": search_query})["return"]
formatted_users = []
# Get the total number of items
user_results = len(users)
post_results = len(posts)
# Formats the users' data
for user in users:
formatted_users.append(user.format())
# Paginates posts
paginated_data = paginate(posts, current_page)
paginated_posts = paginated_data[0]
total_pages = paginated_data[1]
return jsonify(
{
"success": True,
"users": formatted_users,
"posts": paginated_posts,
"user_results": user_results,
"post_results": post_results,
"current_page": current_page,
"total_pages": total_pages,
}
)
# Endpoint: POST /posts
# Description: Add a new post to the database.
# Parameters: None.
# Authorization: post:post.
@app.route("/posts", methods=["POST"])
@requires_auth(["post:post"])
def add_post(token_payload):
current_user = User.query.filter(
User.auth0_id == token_payload["sub"]
).one_or_none()
# If the user is currently blocked, raise an AuthError
if current_user.blocked is True:
raise AuthError(
{
"code": 403,
"description": "You cannot create posts while being blocked.",
},
403,
)
new_post_data = json.loads(request.data)
blacklist_check = word_filter.blacklisted(new_post_data["text"])
# If there's no blacklisted word, add the new post to the database
if blacklist_check["blacklisted"] is False:
# Check the length adn type of the post's text
validator.check_length(new_post_data["text"], "post")
validator.check_type(new_post_data["text"], "post text")
# Create a new post object
new_post = Post(
user_id=new_post_data["userId"],
text=new_post_data["text"],
date=new_post_data["date"],
given_hugs=new_post_data["givenHugs"],
sent_hugs="",
)
# Try to add the post to the database
try:
added_post = db_add(new_post)["added"]
# If there's an error, abort
except Exception:
abort(500)
# If there's a blacklisted word / phrase, alert the user
else:
num_issues = len(blacklist_check["indexes"])
forbidden_words = "".join(
[str(word["badword"]) + ", " for word in blacklist_check["indexes"]]
)
raise ValidationError(
{
"code": 400,
"description": "Your text contains "
+ str(num_issues)
+ " \
forbidden term(s). The following word(s) is/ \
are not allowed: "
+ forbidden_words[0:-2]
+ ". Please fix your post's \
text and try again.",
},
400,
)
return jsonify({"success": True, "posts": added_post})
# Endpoint: PATCH /posts/<post_id>
# Description: Updates a post (either its text or its hugs) in the
# database.
# Parameters: post_id - ID of the post to update.
# Authorization: patch:my-post or patch:any-post.
@app.route("/posts/<post_id>", methods=["PATCH"])
@requires_auth(["patch:my-post", "patch:any-post"])
def edit_post(token_payload, post_id):
# If there's no ID provided
if post_id is None:
abort(404)
# Check if the post ID isn't an integer; if it isn't, abort
validator.check_type(post_id, "Post ID")
updated_post = json.loads(request.data)
original_post = Post.query.filter(Post.id == post_id).one_or_none()
# Gets the user's ID
current_user = User.query.filter(
User.auth0_id == token_payload["sub"]
).one_or_none()
# If there's no post with that ID
if original_post is None:
abort(404)
post_author = User.query.filter(User.id == original_post.user_id).one_or_none()
# If the user's permission is 'patch my' the user can only edit
# their own posts.
if "patch:my-post" in token_payload["permissions"]:
# Compares the user's ID to the user_id of the post
if original_post.user_id != current_user.id:
# If the user attempted to edit the text of a post that doesn't
# belong to them, throws an auth error
if original_post.text != updated_post["text"]:
raise AuthError(
{
"code": 403,
"description": "You do not have permission to edit \
this post.",
},
403,
)
# Otherwise, the user attempted to edit their own post, which
# is allowed
else:
# If the text was changed
if original_post.text != updated_post["text"]:
blacklist_check = word_filter.blacklisted(updated_post["text"])
# If there's no blacklisted word, add the new post to the database
if blacklist_check["blacklisted"] is False:
# Check the length adn type of the post's text
validator.check_length(updated_post["text"], "post")
validator.check_type(updated_post["text"], "post text")
original_post.text = updated_post["text"]
# If there's a blacklisted word / phrase, alert the user
else:
num_issues = len(blacklist_check["indexes"])
forbidden_words = "".join(
[
str(word["badword"]) + ", "
for word in blacklist_check["indexes"]
]
)
raise ValidationError(
{
"code": 400,
"description": "Your text contains "
+ str(num_issues)
+ " forbidden \
term(s). The following word(s) is/ \
are not allowed: "
+ forbidden_words[0:-2]
+ ". Please fix your post's \
text and try again.",
},
400,
)
# Otherwise, the user is allowed to edit any post, and thus text
# editing is allowed
else:
# If the text was changed
if original_post.text != updated_post["text"]:
blacklist_check = word_filter.blacklisted(updated_post["text"])
# If there's no blacklisted word, add the new post to the database
if blacklist_check["blacklisted"] is False:
# Check the length adn type of the post's text
validator.check_length(updated_post["text"], "post")
validator.check_type(updated_post["text"], "post text")
original_post.text = updated_post["text"]
# If there's a blacklisted word / phrase, alert the user
else:
num_issues = len(blacklist_check["indexes"])
forbidden_words = "".join(
[
str(word["badword"]) + ", "
for word in blacklist_check["indexes"]
]
)
raise ValidationError(
{
"code": 400,
"description": "Your text contains "
+ str(num_issues)
+ " forbidden \
term(s). The following word(s) is/ \
are not allowed: "
+ forbidden_words[0:-2]
+ ". Please fix your post's \
text and try again.",
},
400,
)
# If a hug was added
# Since anyone can give hugs, this doesn't require a permissions check
if "givenHugs" in updated_post:
original_hugs = original_post.given_hugs
if original_post.given_hugs != updated_post["givenHugs"]:
hugs = original_post.sent_hugs.split(" ")
sent_hugs = list(filter(None, hugs))
# If the current user already sent a hug on this post, abort
if str(current_user.id) in sent_hugs:
abort(409)
# Otherwise, continue adding the new hug
original_post.given_hugs = updated_post["givenHugs"]
current_user.given_hugs += 1
post_author.received_hugs += 1
sent_hugs.append(current_user.id)
original_post.sent_hugs = "".join([str(e) + " " for e in sent_hugs])
# Create a notification for the user getting the hug
today = datetime.now()
notification = Notification(
for_id=post_author.id,
from_id=current_user.id,
type="hug",
text="You got a hug",
date=today,
)
push_notification = {
"type": "hug",
"text": current_user.display_name + " sent you a hug",
}
notification_for = post_author.id
# If there's a 'closeReport' value, this update is the result of
# a report, which means the report with the given ID needs to be
# closed.
if "closeReport" in updated_post:
# Check the user has permission to close reports
# If he doesn't, raise an AuthError
if "read:admin-board" not in token_payload["permissions"]:
raise AuthError(
{
"code": 403,
"description": "You do not have permission to close \
this post's report.",
},
403,
)
# Otherwise get the open report and close it
open_report = Report.query.filter(
Report.id == updated_post["closeReport"]
).one_or_none()
open_report.dismissed = False
open_report.closed = True
original_post.open_report = False
# Try to update the database
try:
# Objects to update
to_update = [original_post, current_user, post_author]
# If there's a report to close, add it to the list of objects
# to update.
if "closeReport" in updated_post:
to_update.append(open_report)
# Update users' and post's data
updated_res = db_update_multi(to_update)
# If there was an added hug, add the new notification
if "givenHugs" in updated_post:
if original_hugs != updated_post["givenHugs"]:
send_push_notification(
user_id=notification_for, data=push_notification
)
db_add(notification)
data = json.loads(updated_res.data)["updated"]
db_updated_post = data[0]
# If there's an error, abort
except Exception:
print(sys.exc_info())
abort(500)
return jsonify({"success": True, "updated": db_updated_post})
# Endpoint: DELETE /posts/<post_id>
# Description: Deletes a post from the database.
# Parameters: post_id - ID of the post to delete.
# Authorization: delete:my-post or delete:any-post.
@app.route("/posts/<post_id>", methods=["DELETE"])
@requires_auth(["delete:my-post", "delete:any-post"])
def delete_post(token_payload, post_id):
# If there's no ID provided
if post_id is None:
abort(404)
# Check if the post ID isn't an integer; if it isn't, abort
validator.check_type(post_id, "Post ID")
# Gets the post to delete
post_data = Post.query.filter(Post.id == post_id).one_or_none()
# If this post doesn't exist, abort
if post_data is None:
abort(404)
# If the user only has permission to delete their own posts
if "delete:my-post" in token_payload["permissions"]:
# Gets the user's ID and compares it to the user_id of the post
current_user = User.query.filter(
User.auth0_id == token_payload["sub"]
).one_or_none()
# If it's not the same user, they can't delete the post, so an
# auth error is raised
if post_data.user_id != current_user.id:
raise AuthError(
{
"code": 403,
"description": "You do not have permission to delete \
this post.",
},
403,
)
# Otherwise, it's either their post or they're allowed to delete any
# post.
# Try to delete the post
try:
db_delete(post_data)
# If there's an error, abort
except Exception:
abort(500)
return jsonify({"success": True, "deleted": post_id})
# Endpoint: GET /posts/<type>
# Description: Gets all new posts.
# Parameters: type - Type of posts (new or suggested) to fetch.
# Authorization: None.
@app.route("/posts/<type>")
def get_new_posts(type):
page = request.args.get("page", 1, type=int)
# Gets the recent posts and paginates them
full_posts = joined_query("full " + type)["return"]
paginated_data = paginate(full_posts, page)
paginated_posts = paginated_data[0]
total_pages = paginated_data[1]
return jsonify(
{"success": True, "posts": paginated_posts, "total_pages": total_pages}
)
# Endpoint: GET /users/<type>
# Description: Gets users by a given type.
# Parameters: type - A type by which to filter the users.
# Authorization: read:admin-board.
@app.route("/users/<type>")
@requires_auth(["read:admin-board"])
def get_users_by_type(token_payload, type):
page = request.args.get("page", 1, type=int)
# If the type of users to fetch is blocked users
if type.lower() == "blocked":
# Get all blocked users
users = (
# TODO: Replace the True + NOQA with db.true()
# Requires passing the db object back to the app
User.query.filter(User.blocked == True) # NOQA
.order_by(User.release_date)
.all()
)
# If there are no blocked users
if users is None:
paginated_users = []
total_pages = 1
# Otherwise, filter and paginate blocked users
else:
formatted_users = []
# Format users data
for user in users:
# If it's past the user's release date, unblock them
current_date = datetime.now()
if user.release_date < current_date:
user.blocked = False
user.release_date = None
# Try to update the database
try:
db_update(user)
# If there's an error, abort
except Exception:
abort(500)
# Otherwise, format the user's data
else:
formatted_users.append(user.format())
# Paginate users
paginated_data = paginate(formatted_users, page)
paginated_users = paginated_data[0]
total_pages = paginated_data[1]
return jsonify(
{"success": True, "users": paginated_users, "total_pages": total_pages}
)
# Endpoint: GET /users/all/<user_id>
# Description: Gets the user's data.
# Parameters: user_id - The user's Auth0 ID.
# Authorization: read:user.
@app.route("/users/all/<user_id>")
@requires_auth(["read:user"])
def get_user_data(token_payload, user_id):
# If there's no ID provided
if user_id is None:
abort(404)
user_data = User.query.filter(User.auth0_id == user_id).one_or_none()
# If there's no user with that Auth0 ID, try to find a user with that
# ID; the user might be trying to view user profile
if user_data is None:
# Try to convert it to a number; if it's a number, it's a
# regular ID, so try to find the user with that ID
try:
int(user_id)
user_data = User.query.filter(User.id == user_id).one_or_none()
# If there's no user with that ID either, abort
if user_data is None:
abort(404)
# Otherwise, it's an Auth0 ID and it's the user's first login,
# so just return a 'not found' message
except Exception:
abort(404)
# If the user is currently blocked, compare their release date to
# the current date and time.
if user_data.release_date:
current_date = datetime.now()
# If it's past the user's release date, unblock them
if user_data.release_date < current_date:
user_data.blocked = False
user_data.release_date = None
# Try to update the database
try:
db_update(user_data)
# If there's an error, abort
except Exception:
abort(500)
formatted_user_data = user_data.format()
formatted_user_data["posts"] = len(
Post.query.filter(Post.user_id == user_data.id).all()
)
return jsonify({"success": True, "user": formatted_user_data})
# Endpoint: POST /users
# Description: Adds a new user to the users table.
# Parameters: None.
# Authorization: post:user.
@app.route("/users", methods=["POST"])
@requires_auth(["post:user"])
def add_user(token_payload):
# Gets the user's data
user_data = json.loads(request.data)
# If the user is attempting to add a user that isn't themselves to
# the database, aborts
if user_data["id"] != token_payload["sub"]:
abort(422)
# Checks whether a user with that Auth0 ID already exists
# If it is, aborts
database_user = User.query.filter(
User.auth0_id == user_data["id"]
).one_or_none()
if database_user:
abort(409)
new_user = User(
auth0_id=user_data["id"],
display_name=user_data["displayName"],
role="user",
last_notifications_read=datetime.now(),
login_count=0,
blocked=False,
open_report=False,
auto_refresh=True,
refresh_rate=20,
push_enabled=False,
selected_character="kitty",
icon_colours='{"character":"#BA9F93",\
"lbg":"#e2a275","rbg":"#f8eee4",\
"item":"#f4b56a"}',
)
# Try to add the post to the database
try:
added_user = db_add(new_user)["added"]
# If there's an error, abort
except Exception:
abort(500)
# Get the Management API token and check that it's valid
MGMT_API_TOKEN = check_mgmt_api_token()
# If the token expired, get and check a
if MGMT_API_TOKEN.lower() == "token expired":
get_management_api_token()
MGMT_API_TOKEN = check_mgmt_api_token()
# Try to replace the user's role in Auth0's systems
try:
# General variables for establishing an HTTPS connection to Auth0
connection = http.client.HTTPSConnection(AUTH0_DOMAIN)
auth_header = "Bearer " + MGMT_API_TOKEN
headers = {
"content-type": "application/json",
"authorization": auth_header,
"cache-control": "no-cache",
}
# Remove the 'new user' role from the user's payload
delete_payload = '{ "roles": [ "rol_QeyIIcHg326Vv1Ay" ] }'
connection.request(
"DELETE",
"/api/v2/users/" + user_data["id"] + "/roles",
delete_payload,
headers,
)
delete_response = connection.getresponse()
delete_response_data = delete_response.read()
print(delete_response_data)
# Then add the 'user' role to the user's payload
create_payload = '{ "roles": [ "rol_BhidDxUqlXDx8qIr" ] }'
connection.request(
"POST",
"/api/v2/users/" + user_data["id"] + "/roles",
create_payload,
headers,
)
create_response = connection.getresponse()
create_response_data = create_response.read()
print(create_response_data)
# If there's an error, print it
except Exception as e:
print(e)
return jsonify({"success": True, "user": added_user})
# Endpoint: PATCH /users/all/<user_id>
# Description: Updates a user in the database.
# Parameters: user_id - ID of the user to update.
# Authorization: patch:user or patch:any-user.
@app.route("/users/all/<user_id>", methods=["PATCH"])
@requires_auth(["patch:user", "patch:any-user"])
def edit_user(token_payload, user_id):
# if there's no user ID provided, abort with 'Bad Request'
if user_id is None:
abort(404)
# Check if the user ID isn't an integer; if it isn't, abort
validator.check_type(user_id, "User ID")
updated_user = json.loads(request.data)
original_user = User.query.filter(User.id == user_id).one_or_none()
current_user = User.query.filter(
User.auth0_id == token_payload["sub"]
).one_or_none()
# If the user being updated was given a hug, also update the current
# user's "given hugs" value, as they just gave a hug
if "receivedH" in updated_user and "givenH" in updated_user:
original_hugs = original_user.received_hugs
if original_user.received_hugs != updated_user["receivedH"]:
current_user.given_hugs += 1
today = datetime.now()
notification = Notification(
for_id=original_user.id,
from_id=current_user.id,
type="hug",
text="You got a hug",
date=today,
)
push_notification = {
"type": "hug",
"text": current_user.display_name + " sent you a hug",
}
notification_for = original_user.id
# Update user data
original_user.received_hugs = updated_user["receivedH"]
original_user.given_hugs = updated_user["givenH"]
# If there's a login count (meaning, the user is editing their own
# data), update it
if "loginCount" in updated_user:
original_user.login_count = updated_user["loginCount"]
# If the user is attempting to change a user's display name, check
# their permissions
if "displayName" in updated_user:
if updated_user["displayName"] != original_user.display_name:
# if the user is only allowed to change their own name
# (user / mod)
if "patch:user" in token_payload["permissions"]:
# If it's not the current user, abort
if token_payload["sub"] != original_user.auth0_id:
raise AuthError(
{
"code": 403,
"description": "You do not have permission to \
edit this user's display name.",
},
403,
)
# If it is, let them update user data
else:
# Check the length and type of the user's display name
validator.check_length(
updated_user["displayName"], "display name"
)
validator.check_type(
updated_user["displayName"], "display name"
)
original_user.display_name = updated_user["displayName"]
# if the user can edit anyone or the user is trying to
# update their own name
else:
# Check the length adn type of the user's display name
validator.check_length(updated_user["displayName"], "display name")
validator.check_type(updated_user["displayName"], "display name")
original_user.display_name = updated_user["displayName"]
# If the request was in done in order to block or unlock a user
if "blocked" in updated_user:
# If the user doesn't have permission to block/unblock a user
if "block:user" not in token_payload["permissions"]:
raise AuthError(
{
"code": 403,
"description": "You do not have permission to block \
this user.",
},
403,
)
# Otherwise, the user is a manager, so they can block a user.
# In that case, block / unblock the user as requested.
else:
original_user.blocked = updated_user["blocked"]
original_user.release_date = updated_user["releaseDate"]
# If there's a 'closeReport' value, this update is the result of
# a report, which means the report with the given ID needs to be
# closed.
if "closeReport" in updated_user:
open_report = Report.query.filter(
Report.id == updated_user["closeReport"]
).one_or_none()
open_report.dismissed = False
open_report.closed = True
original_user.open_report = False
# If the user is attempting to change a user's settings, check
# whether it's the current user
if (
"autoRefresh" in updated_user
or "pushEnabled" in updated_user
or "refreshRate" in updated_user
):
# If it's not the current user, abort
if token_payload["sub"] != original_user.auth0_id:
raise AuthError(
{
"code": 403,
"description": "You do not have permission to \
edit another user's settings.",
},
403,
)
# If the user is changing their auto-refresh settings
if "autoRefresh" in updated_user:
original_user.auto_refresh = updated_user["autoRefresh"]
# If the user is changing their push notifications setting
if "pushEnabled" in updated_user:
original_user.push_enabled = updated_user["pushEnabled"]
# If the user is changing their auto-refresh settings
if "refreshRate" in updated_user:
original_user.refresh_rate = updated_user["refreshRate"]
# If the user is changing their selected character
if "selectedIcon" in updated_user:
original_user.selected_character = updated_user["selectedIcon"]
# If the user is changing their character colours
if "iconColours" in updated_user:
original_user.icon_colours = json.dumps(updated_user["iconColours"])
# Checks if the user's role is updated based on the
# permissions in the JWT
# Checks whether the user has 'patch:any-post' permission, which
# if given to moderators and admins
if "patch:any-post" in token_payload["permissions"]:
# Checks whether the user has 'delete:any-post' permission, which
# is given only to admins, and whether the user is already
# marked as an admin in the database; if the user isn't an admin
# in the database, changes their role to admin. If they are,
# there's no need to update their role.
if (
"delete:any-post" in token_payload["permissions"]
and original_user.role != "admin"
):
original_user.role = "admin"
# If the user doesn't have that permission but they have the
# permission to edit any post, they're moderators. Checks whether
# the user is marked as a mod in the database; if the user isn't,
# changes their role to moderator. If they are, there's no need to
# update their role.
elif (
"delete:any-post" not in token_payload["permissions"]
and original_user.role != "moderator"
):
original_user.role = "moderator"
# Otherwise, the user's role is a user, so make sure to mark it
# as such.
else:
original_user.role = "user"
# Try to update it in the database
try:
# Update users' data
db_update(original_user)
db_update(current_user)
if "closeReport" in updated_user:
db_update(open_report)
# If the user was given a hug, add a new notification
if "receivedH" in updated_user and "givenH" in updated_user:
if original_hugs != updated_user["receivedH"]:
send_push_notification(
user_id=notification_for, data=push_notification
)
db_add(notification)
updated_user = original_user.format()
# If there's an error, abort
except Exception:
abort(500)
return jsonify({"success": True, "updated": updated_user})
# Endpoint: GET /users/all/<user_id>/posts
# Description: Gets a specific user's posts.
# Parameters: user_id - whose posts to fetch.
# Authorization: read:user.
@app.route("/users/all/<user_id>/posts")
@requires_auth(["read:user"])
def get_user_posts(token_payload, user_id):
page = request.args.get("page", 1, type=int)
# if there's no user ID provided, abort with 'Bad Request'
if user_id is None:
abort(400)
validator.check_type(user_id, "User ID")
# Gets all posts written by the given user
user_posts = (
Post.query.filter(Post.user_id == user_id).order_by(Post.date).all()
)
user_posts_array = []
# If there are no posts, returns an empty array
if user_posts is None:
user_posts_array = []
# If the user has written posts, formats each post and adds it
# to the posts array
else:
for post in user_posts:
user_posts_array.append(post.format())
paginated_data = paginate(user_posts_array, page)
paginated_posts = paginated_data[0]
total_pages = paginated_data[1]
return jsonify(
{
"success": True,
"posts": paginated_posts,
"page": page,
"total_pages": total_pages,
}
)
# Endpoint: DELETE /users/all/<user_id>/posts
# Description: Deletes a specific user's posts.
# Parameters: user_id - whose posts to delete.
# Authorization: delete:my-post or delete:any-post
@app.route("/users/all/<user_id>/posts", methods=["DELETE"])
@requires_auth(["delete:my-post", "delete:any-post"])
def delete_user_posts(token_payload, user_id):
validator.check_type(user_id, "User ID")
current_user = User.query.filter(
User.auth0_id == token_payload["sub"]
).one_or_none()
# If the user making the request isn't the same as the user
# whose posts should be deleted
if current_user.id != int(user_id):
# If the user can only delete their own posts, they're not
# allowed to delete others' posts, so raise an AuthError
if "delete:my-post" in token_payload["permissions"]:
raise AuthError(
{