forked from Feluk6174/doxa_server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_actions.py
313 lines (258 loc) · 12 KB
/
user_actions.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
from Crypto.PublicKey import RSA
from typing import Union
import auth
import database
import log
import managment
import time
from conn import NodeConnection, ClientConnection
def new_post(msg_info:dict, connection:Union[ClientConnection, NodeConnection], ip:str=None):
global db, logger
logger.log(f"posting: {msg_info} {ip}")
if not database.is_safe(msg_info["post_id"]):
connection.send("WRONG CHARS")
return
pub_key = db.querry(f"SELECT public_key FROM users WHERE user_name = '{msg_info['user_name']}'")
pub_key = RSA.import_key(auth.reconstruct_key(pub_key[0][0], key_type="pub"))
if not auth.verify(pub_key, msg_info["signature"], msg_info["content"], msg_info["post_id"], msg_info["user_name"], msg_info["background_color"], msg_info["time"]):
connection.send("WRONG SIGNATURE")
return
#CREATE TABLE posts(id INT NOT NULL PRIMARY KEY, user_id VARCHAR(16) NOT NULL, post VARCHAR(255) NOT NULL, time_posted INT NOT NULL, FOREIGN KEY (user_id) REFERENCES users (user_name));")
res = db.querry(f"SELECT * FROM posts WHERE id = '{msg_info['post_id']}';")
if len(res) == 0:
sql = f"INSERT INTO posts(id, user_id, post, background_color, time_posted, signature) VALUES('{msg_info['post_id']}', '{msg_info['user_name']}', '{msg_info['content']}', '{msg_info['background_color']}', {int(msg_info['time'])}, '{msg_info['signature']}');"
err = db.execute(sql)
if not err == "ERROR":
managment.broadcast(msg_info, ip)
if ip == None:
connection.send('OK')
else:
connection.send('DATABASE ERROR')
elif ip == None:
connection.send("ALREADY EXISTS")
def register_user(msg_info:dict, connection:Union[ClientConnection, NodeConnection], ip:str=None):
global db, logger
logger.log(f"registering user: {msg_info} {ip}")
if not database.is_safe(msg_info["user_name"], msg_info['public_key'], msg_info['public_key'], msg_info['profile_picture'], msg_info['info']):
connection.send("WRONG CHARS")
return
#"CREATE TABLE users(user_name VARCHAR(16) NOT NULL UNIQUE PRIMARY KEY, public_key INT NOT NULL UNIQUE, time_created INT NOT NULL, profile_picture VARCHAR(64) NOT NULL, info VARCHAR(255));")
res = db.querry(f"SELECT * FROM users WHERE user_name = '{msg_info['user_name']}'")
logger.log("res", res, len(res))
if len(res) == 0:
sql = f"INSERT INTO users(user_name, public_key, key_file, time_created, profile_picture, info) VALUES('{msg_info['user_name']}', '{msg_info['public_key']}', '{msg_info['private_key']}', {int(time.time())}, '{msg_info['profile_picture']}', '{msg_info['info']}');"
logger.log("r"+sql)
err = db.execute(sql)
if not err == "ERROR":
managment.broadcast(msg_info, ip)
if ip == None:
connection.send("OK")
else:
connection.send("DATABASE ERROR")
elif ip == None:
connection.send("ALREADY EXISTS")
def change_profile_picture(msg_info:dict, connection:Union[ClientConnection, NodeConnection], ip:str=None):
global db, logger
logger.log(f"changing pp: {msg_info} {ip}")
if not database.is_safe(msg_info["profile_picture"], msg_info["user_name"]):
connection.send("WRONG CHARS")
return
pub_key = db.querry(f"SELECT public_key FROM users WHERE user_name = '{msg_info['user_name']}'")
pub_key = RSA.import_key(auth.reconstruct_key(pub_key[0][0], key_type="pub"))
if not auth.verify(pub_key, msg_info["signature"], msg_info["user_name"], msg_info["profile_picture"], msg_info["time"]):
connection.send("WRONG SIGNATURE")
return
res = db.querry(f"SELECT * FROM users WHERE user_name = '{msg_info['user_name']}' AND profile_picture = '{msg_info['profile_picture']}';")
if len(res) == 0:
sql = f"UPDATE users SET profile_picture = '{msg_info['profile_picture']}' WHERE user_name = '{msg_info['user_name']}';"
err = db.execute(sql)
if not err == "ERROR":
managment.broadcast(msg_info, ip)
if ip == None:
connection.send('OK')
elif ip == None:
connection.send('DATABASE ERROR')
elif ip == None:
connection.send("OK")
def change_info(msg_info:dict, connection:Union[ClientConnection, NodeConnection], ip:str=None):
global db, logger
logger.log(f"changing info: {msg_info} {ip}")
if not database.is_safe(msg_info["info"], msg_info["user_name"]):
connection.send("WRONG CHARS")
return
pub_key = db.querry(f"SELECT public_key FROM users WHERE user_name = '{msg_info['user_name']}'")
pub_key = RSA.import_key(auth.reconstruct_key(pub_key[0][0], key_type="pub"))
if not auth.verify(pub_key, msg_info["signature"], msg_info["user_name"], msg_info["info"], msg_info["time"]):
connection.send("WRONG SIGNATURE")
return
res = db.querry(f"SELECT * FROM users WHERE user_name = '{msg_info['user_name']}' AND info = '{msg_info['info']}';")
if len(res) == 0:
sql = f"UPDATE users SET info = '{msg_info['info']}' WHERE user_name = '{msg_info['user_name']}';"
err = db.execute(sql)
if not err == "ERROR":
managment.broadcast(msg_info, ip)
if ip == None:
connection.send('OK')
elif ip == None:
connection.send('DATABASE ERROR')
elif ip == None:
connection.send("OK")
def get_user_posts(msg_info:dict, connection:ClientConnection):
global db, logger
logger.log(f"geting posts: {msg_info}")
if not database.is_safe(msg_info['user_name']):
connection.send("0")
res = connection.recv_from_queue()
if not res == "OK":
logger.log(res)
connection.send("WRONG CHARS")
return
posts = db.querry(f"SELECT * FROM posts WHERE user_id = '{msg_info['user_name']}'")
connection.send(str(len(posts)))
res = connection.recv_from_queue()
logger.log("res1", res)
if not res == "OK":
logger.log(res)
for i, post in enumerate(posts):
msg = "{"+f'"id": "{post[0]}", "user_id": "{post[1]}", "content": "{post[2]}", "background_color": "{post[3]}", "time_posted": {post[4]}, "signature": "{post[5]}"'+"}"
connection.send(msg)
res = connection.recv_from_queue()
if not res == "OK":
logger.log(res)
connection.send("OK")
def get_posts(msg_info:dict, connection:ClientConnection):
global db, logger
logger.log(f"geting posts: {msg_info}")
logger.log("debug 0")
#"user_name", "hashtag", "include_background_color", "exclude_background_color", "sort_by"
if not database.is_safe(msg_info['user_name'], msg_info["hashtag"], msg_info["include_background_color"], msg_info["exclude_background_color"], msg_info["sort_by"], msg_info["num"], msg_info["id"]):
connection.send("0")
res = connection.recv_from_queue()
if not res == "OK":
logger.log(res)
connection.send("WRONG CHARS")
return
logger.log("debug 1")
first = True
sql = "SELECT * FROM posts"
if not msg_info["user_name"] == "None":
if first:
first = False
sql += " WHERE ("
else:
sql += " AND ("
msg_info["user_name"] = msg_info["user_name"].split(",")
logger.log(msg_info["user_name"])
for i, user_name in enumerate(msg_info["user_name"]):
sql += f" user_id = '{user_name}'"
#logger.log(i, len(msg_info)-1, i == len(msg_info)-1)
if not i == len(msg_info["user_name"])-1:
sql += " OR"
else:
sql += ")"
if not msg_info["id"] == "None":
if first:
first = False
sql += " WHERE ("
else:
sql += " AND ("
msg_info["id"] = msg_info["id"].split(",")
logger.log(msg_info["id"])
for i, id in enumerate(msg_info["id"]):
sql += f" id = '{id}'"
#logger.log(i, len(msg_info)-1, i == len(msg_info)-1)
if not i == len(msg_info["id"])-1:
sql += " OR"
else:
sql += ")"
if not msg_info["hashtag"] == "None":
if first:
first = False
sql += " WHERE"
else:
sql += " AND"
sql += f" INSTR(post, '{msg_info['hashtag']}')"
if not msg_info["include_background_color"] == "None":
logger.log("kek", type(msg_info["include_background_color"]), msg_info["include_background_color"])
for i in range(len(msg_info["include_background_color"])):
if msg_info["include_background_color"][i] == "1":
if first:
first = False
sql += " WHERE"
else:
sql += " AND"
sql += f" background_color = '{msg_info['include_background_color']}'"
if not msg_info["exclude_background_color"] == "None":
for i in range(len(msg_info["exclude_background_color"])):
if msg_info["exclude_background_color"][i] == "1":
if first:
first = False
sql += " WHERE"
else:
sql += " AND"
sql += f" not background_color = '{msg_info['include_background_color']}'"
if not msg_info["sort_by"] == "None":
sql += f" ORDER BY {msg_info['sort_by']}"
if not msg_info["sort_order"] == "None":
if msg_info["sort_order"] == "asc" or msg_info["sort_order"] == 0:
sql += " ASC"
elif msg_info["sort_order"] == "desc" or msg_info["sort_order"] == 1:
sql += " DESC"
try:
sql += f" LIMIT {msg_info['offset']}, {msg_info['num']}"
except KeyError:
sql += f" LIMIT {msg_info['num']}"
sql += ";"
logger.log("sql", sql)
posts = db.querry(sql)
connection.send(str(len(posts)))
res = connection.recv_from_queue()
logger.log("res1", res)
if not res == "OK":
logger.log(res)
logger.log("www", posts)
for i, post in enumerate(posts):
msg = "{"+f'"id": "{post[0]}", "user_id": "{post[1]}", "content": "{post[2]}", "background_color": "{post[3]}", "time_posted": {post[4]}, "signature": "{post[5]}"'+"}"
connection.send(msg)
res = connection.recv_from_queue()
if not res == "OK":
logger.log(res)
connection.send("OK")
def get_user_info(msg_info:dict, connection:ClientConnection):
global db, logger
if not database.is_safe(msg_info["user_name"]):
connection.send("WRONG CHARS")
return
# (user_name, public_key, key_file, time_created, profile_picture, info)
user_info = db.querry(f"SELECT * FROM users WHERE user_name = '{msg_info['user_name']}';")
logger.log(user_info)
if not len(user_info) == 0 and not user_info == "ERROR":
user_info = user_info[0]
msg = "{"+f'"user_name": "{user_info[0]}", "public_key": "{user_info[1]}", "private_key": "{user_info[2]}", "time_created": {user_info[3]}, "profile_picture": "{user_info[4]}", "info": "{user_info[5]}"'+"}"
else:
msg = "{}"
connection.send(msg)
def get_post(msg_info:dict, connection:ClientConnection):
global db, logger
if not database.is_safe(msg_info["post_id"]):
connection.send("WRONG CHARS")
return
# (id, user_id, post, background_color, time_posted, signature)
post = db.querry(f"SELECT * FROM posts WHERE id = '{msg_info['post_id']}';")
logger.log(post)
if not len(post) == 0:
post = post[0]
msg = "{"+f'"id": "{post[0]}", "user_id": "{post[1]}", "content": "{post[2]}", "background_color": "{post[3]}", "time_posted": {post[4]}, "signature": "{post[5]}"'+"}"
else:
msg = "{}"
connection.send(msg)
def init(get_logger:log.Logger, get_db:database.Database):
# sets global variables
global logger, db
logger.stop()
logger = get_logger
db.stop()
db = get_db
logger = log.Logger(None)
db = database.Database()
from conn import NodeConnection, ClientConnection