-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutations.py
111 lines (82 loc) · 2.72 KB
/
mutations.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
import os
import strawberry
from fastapi.encoders import jsonable_encoder
from db import db
from models import User
# import all models and types
from otypes import Info, RoleInput, UserDataInput
inter_communication_secret = os.getenv("INTER_COMMUNICATION_SECRET")
# update role of user with uid
@strawberry.mutation
def updateRole(roleInput: RoleInput, info: Info) -> bool:
user = info.context.user
if not user:
raise Exception("Not logged in!")
roleInputData = jsonable_encoder(roleInput)
# check if user is admin
if user.get("role", None) not in ["cc"]:
raise Exception("Authentication Error! Only admins can assign roles!")
# check if the secret is correct
if (
roleInputData.get("inter_communication_secret", None)
!= inter_communication_secret
):
raise Exception("Authentication Error! Invalid secret!")
db_user = db.users.find_one({"uid": roleInputData["uid"]})
# insert if not exists
if not db_user:
new_user = User(uid=roleInputData["uid"])
db.users.insert_one(jsonable_encoder(new_user))
# update role in database
db.users.update_one(
{"uid": roleInputData["uid"]},
{"$set": {"role": roleInputData["role"]}},
)
return True
@strawberry.mutation
def updateUserPhone(userDataInput: UserDataInput, info: Info) -> bool:
user = info.context.user
if not user:
raise Exception("Not logged in!")
userData = jsonable_encoder(userDataInput)
# Validate the data by putting in the model
try:
User(**userData)
except Exception:
raise Exception("Invalid phone number!")
# check if user has access
if not (
user.get("role", None) in ["cc", "club"]
or user.get("uid", None) == userData["uid"]
):
raise Exception("You are not allowed to perform this action!")
db.users.update_one(
{"uid": userData["uid"]},
{"$set": {"phone": userData["phone"]}},
)
return True
@strawberry.mutation
def updateUserData(userDataInput: UserDataInput, info: Info) -> bool:
user = info.context.user
if not user:
raise Exception("Not logged in!")
userData = jsonable_encoder(userDataInput)
# check if user has access
if (
user.get("role", None) not in ["cc"]
and user.get("uid", None) != userData["uid"]
):
raise Exception("You are not allowed to perform this action!")
# Validate the data by putting in the model
User(**userData)
db.users.update_one(
{"uid": userData["uid"]},
{"$set": {"img": userData["img"], "phone": userData["phone"]}},
)
return True
# register all mutations
mutations = [
updateRole,
updateUserPhone,
updateUserData,
]