-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
251 lines (200 loc) · 7.87 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
from uuid import uuid4
from json import loads as json_loads
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from uvicorn import run as uvicorn_run
from sqlite_handler import SQLiteHandler
from pydantic_models import Event
from jwt_coder import jwt_encode, get_user_id, check_token_admin, check_token_admin_deco
from hashing import to_hash
from db_init import db_init
# initialize the database (will not overwrite)
db_init()
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
@app.get("/events")
def get_events(search_filter):
search_filter = json_loads(search_filter)
command = "SELECT * FROM events WHERE verified=1"
for key, item in enumerate(search_filter):
if key == "tags":
continue
command += f" WHERE {key} = '{item}'"
with SQLiteHandler() as cur:
cur.execute(command)
events = list(map(dict, cur.fetchall()))
for event in events:
cur.execute(
"SELECT tag FROM event_tags WHERE event_id = ?",
(event["event_id"],)
)
event["tags"] = ",".join(list(map(lambda x: x["tag"], cur.fetchall())))
return events
@app.post("/events")
def create_event(event: Event):
event_id = uuid4().hex
with SQLiteHandler() as cur:
cur.execute(
"""
INSERT INTO events
(lat, lon, name, author, location, hrtime, deleteAfter, time,
website, description, event_id, verified)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
""",
(event.lat, event.lon, event.name, event.author, event.location, event.hrtime,
event.deleteAfter, event.time, event.website, event.description, event_id, 0))
for tag in event.tags.split(","):
cur.execute(
"INSERT INTO event_tags (event_id, tag) VALUES (?, ?);",
(event_id, tag)
)
return {"success": True}
@app.post("/event/like")
def like_event(request: Request, body: dict):
event_id, like, user_id = body["event_id"], body["like"], get_user_id(request)
with SQLiteHandler() as cur:
cur.execute("DELETE FROM likes WHERE event_id = ? AND user_id = ?", (event_id, user_id))
if like:
cur.execute("INSERT INTO likes (user_id, event_id) VALUES (?, ?)", (user_id, event_id))
@app.get("/admin")
def get_events_admin(request: Request, search_filter):
if not check_token_admin(request):
raise HTTPException(status_code=401)
search_filter = json_loads(search_filter)
command = "SELECT * FROM events WHERE verified=0"
for key, item in enumerate(search_filter):
if key == "tags":
continue
command += f" WHERE {key} = '{item}'"
with SQLiteHandler() as cur:
cur.execute(command)
events = list(map(dict, cur.fetchall()))
for event in events:
cur.execute(
"SELECT tag FROM event_tags WHERE event_id = ?",
(event["event_id"], )
)
event["tags"] = ",".join(list(map(lambda x: x["tag"], cur.fetchall())))
return events
@app.get("/admin/users")
@check_token_admin_deco
def get_users_admin(_: Request, __: dict):
with SQLiteHandler() as cur:
cur.execute("SELECT user_id, username, display_name, is_admin FROM users")
return cur.fetchall()
@app.delete("/admin/user")
@check_token_admin_deco
def delete_user(_: Request, body: dict):
user_id = body["user_id"]
with SQLiteHandler() as cur:
cur.execute("DELETE FROM users WHERE user_id = ?", (user_id, ))
cur.execute("DELETE FROM likes WHERE user_id = ?", (user_id, ))
return {"success": True, "message": f"User deleted: {user_id}"}
@app.post("/admin")
@check_token_admin_deco
def verify_event(_: Request, body: dict):
event_id = body["event_id"]
with SQLiteHandler() as cur:
cur.execute("UPDATE events SET verified=1 WHERE event_id=?", (event_id,))
return {"success": True}
@app.post("/admin/op")
@check_token_admin_deco
def make_admin(_: Request, body: dict):
user_id, is_admin = body["user_id"], 1 if body["is_admin"] else 0
with SQLiteHandler() as cur:
cur.execute("UPDATE users SET is_admin=? WHERE user_id=?", (is_admin, user_id))
return {"success": True}
@app.delete("/admin")
def delete_event(request: Request, event_id: str):
if not check_token_admin(request):
raise HTTPException(status_code=401)
with SQLiteHandler() as cur:
cur.execute("DELETE FROM events WHERE event_id=?", (event_id, ))
cur.execute("DELETE FROM likes WHERE event_id = ?", (event_id, ))
cur.execute("DELETE FROM event_tags WHERE event_id = ?", (event_id, ))
return {"success": True}
@app.post("/login")
def login(login_data: dict):
username, password = login_data["username"].lower(), login_data["password"]
hashed_password = to_hash(password, salt=username)
with SQLiteHandler() as cur:
cur.execute("SELECT hashed_password FROM users WHERE username=?", (username,))
if cur.fetchone()["hashed_password"] != hashed_password:
raise HTTPException(status_code=401, detail="Incorrect username or password")
cur.execute(
"SELECT is_admin, username, display_name, user_id FROM users WHERE username=?",
(username, )
)
user = cur.fetchone()
jwt_token = jwt_encode({
"is_admin": bool(user["is_admin"]),
"user_id": user["user_id"],
"username": user["username"]
})
return {
"success": True,
"token": jwt_token,
"is_admin": bool(user["is_admin"]),
"username": user["username"],
"display_name": user["display_name"]
}
@app.post("/user/register")
def create_user(user_data: dict):
username, password = user_data["username"].lower(), user_data["password"]
display_name = user_data["display_name"]
if display_name == "":
raise HTTPException(status_code=400, detail="display name cannot be empty")
with SQLiteHandler() as cur:
cur.execute("SELECT username FROM users WHERE username=?", (username,))
if len(cur.fetchall()) != 0:
raise HTTPException(status_code=409, detail="Chosen username is already in use")
hashed_password = to_hash(password, salt=username)
user_id = uuid4().hex
cur.execute(
"""
INSERT INTO users
(user_id, username, hashed_password, is_admin, display_name)
VALUES
(?, ?, ?, ?, ?)
""",
(user_id, username, hashed_password, 0, display_name)
)
jwt_token = jwt_encode({
"is_admin": False,
"user_id": user_id,
"username": username
})
return {
"success": True,
"token": jwt_token,
"is_admin": False,
"username": username,
"display_name": display_name
}
@app.get("/user/likes")
def get_likes(request: Request):
user_id = get_user_id(request)
with SQLiteHandler() as cur:
cur.execute("SELECT * FROM likes WHERE user_id=?", (user_id, ))
return list(map(lambda x: x["event_id"], cur.fetchall()))
if __name__ == "__main__":
from argparse import ArgumentParser
parser = ArgumentParser(
prog='EventSync backend',
add_help=True,
description=None,
epilog=None)
parser.add_argument("-p", "--port",
required=False,
action="store",
type=int,
default=8000,
help="specify port; default: 8000")
args = parser.parse_args()
uvicorn_run(app, host="0.0.0.0", port=args.port)