-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql.py
516 lines (396 loc) · 15.6 KB
/
sql.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
import sqlite3
import uuid
import hashlib
import bcrypt
from datetime import datetime
import time
# This class is a simple handler for all of our SQL database actions
# Practicing a good separation of concerns, we should only ever call
# These functions from our models
# If you notice anything out of place here, consider it to your advantage and don't spoil the surprise
class SQLDatabase():
'''
Our SQL Database
'''
# Get the database running
def __init__(self):
self.conn = sqlite3.connect("database.db", uri=True)
self.cur = self.conn.cursor()
# SQLite 3 does not natively support multiple commands in a single statement
# Using this handler restores this functionality
# This only returns the output of the last command
def execute(self, sql_string):
out = None
for string in sql_string.split(";"):
try:
out = self.cur.execute(string)
except:
pass
return out
# Commit changes to the database
def commit(self):
self.conn.commit()
# -----------------------------------------------------------------------------
# Sets up the database
# Default admin password
def database_setup(self, admin_password='admin'):
# Clear the database if needed
self.execute("DROP TABLE IF EXISTS Users")
self.execute("DROP TABLE IF EXISTS Friends")
self.execute("DROP TABLE IF EXISTS Messages")
self.execute("DROP TABLE IF EXISTS Posts")
self.execute("DROP TABLE IF EXISTS Comments")
self.commit()
# Create the users table
self.execute("""CREATE TABLE Users(
username TEXT UNIQUE,
password TEXT,
salt TEXT,
admin TEXT DEFAULT 'NO',
attempts INTEGER DEFAULT 0,
block_time DATETIME DEFAULT NULL,
public_key TEXT DEFAULT NULL,
mute TEXT DEFAULT 'NO',
avatar TEXT,
block TEXT
)""")
# Create the Firends table
self.execute("""CREATE TABLE Friends(
Id INTEGER PRIMARY KEY,
username TEXT,
friend TEXT
)""")
# Create the Messages table to store encrypted messages
self.execute("""CREATE TABLE Messages(
Id INTEGER PRIMARY KEY,
sender_username TEXT,
receiver_username TEXT,
encrypted_messagge TEXT
)""")
# Create the post table
self.execute("""CREATE TABLE Posts(
Id INTEGER PRIMARY KEY,
title TEXT,
content TEXT,
section TEXT,
sender_username TEXT,
add_time datetime
)""")
# Create the comment table
self.execute("""CREATE TABLE Comments(
Id INTEGER PRIMARY KEY,
post_id INTEGER,
detail TEXT,
sender_username TEXT,
add_time datetime
)""")
self.commit()
# Add our admin user
self.add_user('admin', admin_password, admin='YES')
self.add_user('root', '321.qwer', admin='NO')
self.add_post("what's your name? ",
'Welcome to USPS.com. Find information on our most convenient and affordable shipping and mailing services. Use our quick tools to find locations, ...',
'root', 'general')
# -----------------------------------------------------------------------------
# User handling
# -----------------------------------------------------------------------------
# Add a user to the database
def add_user(self, username, password, admin):
sql_cmd = """
INSERT INTO Users(username, password, salt, admin,block,avatar)
VALUES('{username}', '{password}', '{salt}', '{admin}','NO','/img/avatar.png')
"""
# Generate a random number as salt.
salt = uuid.uuid4().hex
password_salt = salt + password
password_hash = hashlib.sha256(password_salt.encode()).hexdigest()
# Hash the password
password_double_encrypted = bcrypt.hashpw(password_hash.encode('ascii'), bcrypt.gensalt()).hex()
sql_cmd = sql_cmd.format(username=username, password=password_double_encrypted, salt=salt, admin=admin)
self.execute(sql_cmd)
self.commit()
return True
# Add a public key to a user
def add_pk(self, username, public_key):
# Update the public key
sql_query = """
UPDATE Users
SET public_key = '{public_key}'
WHERE username = '{username}'
"""
sql_cmd = sql_query.format(public_key=public_key, username=username)
self.execute(sql_cmd)
self.commit()
return True
# Get a public key for a user
def get_pk(self, username):
# Update the public key
sql_query = """
SELECT public_key
FROM Users
WHERE username = '{username}'
"""
sql_cmd = sql_query.format(username=username)
self.execute(sql_cmd)
return self.cur.fetchall()
# -----------------------------------------------------------------------------
def get_user(self, username):
sql_query = """
SELECT *
FROM Users
WHERE username = '{username}'
"""
sql_query = sql_query.format(username=username)
self.execute(sql_query)
self.commit()
return self.cur.fetchall()
def debug(self):
sql_query = """
SELECT *
FROM Users
"""
self.execute(sql_query)
self.commit()
return self.cur.fetchall()
def debug_friend(self):
sql_query = """
SELECT *
FROM Friends
"""
self.execute(sql_query)
self.commit()
return self.cur.fetchall()
def debug_message(self):
sql_query = """
SELECT *
FROM Messages
"""
self.execute(sql_query)
self.commit()
return self.cur.fetchall()
# Check login credentials
def check_credentials(self, username, password):
sql_query = """
SELECT *
FROM Users
WHERE username = '{username}'
"""
sql_query = sql_query.format(username=username)
self.execute(sql_query)
# Get the return result
result = self.cur.fetchone()
# Check if the hash is same
if bcrypt.checkpw(password.encode('ascii'), bytes.fromhex(result[1])):
# Update the attempts to zero
sql_query = """
UPDATE Users
SET attempts = 0, block_time = NULL
WHERE username = '{username}'
"""
sql_query = sql_query.format(username=username)
self.execute(sql_query)
self.commit()
return True
else:
attempts = int(result[4]) + 1
# Update Attempts
# Update the attempts to zero
sql_query = """
UPDATE Users
SET attempts = '{attempts}'
WHERE username = '{username}'
"""
sql_query = sql_query.format(username=username, attempts=attempts)
self.execute(sql_query)
self.commit()
# Do a attempts_check
self.attempts_check(username)
return False
# -----------------------------------------------------------------------------
# Check if the username is exist
def check_username(self, username):
sql_query = """
SELECT *
FROM Users
WHERE username = '{username}'
"""
sql_query = sql_query.format(username=username)
self.execute(sql_query)
# If our query returns
if self.cur.fetchone():
return True
else:
return False
# -----------------------------------------------------------------------------
# Check user attempts to defense Brute Force Attack
def attempts_check(self, username):
sql_query = """
SELECT *
FROM Users
WHERE username = '{username}'
"""
sql_query = sql_query.format(username=username)
self.execute(sql_query)
# Get the return result
result = self.cur.fetchone()
attempts = result[4]
block_time = result[5]
# Form the data that the account is block
format_data = "%Y-%m-%d %H:%M:%S"
# If the account is block, cooldown for 5 minutes
if block_time != None:
block_time = datetime.strptime(block_time, format_data)
# Check if pass the 5 minutes cooldown
different = datetime.utcnow() - block_time
different = different.total_seconds() / 60
if different >= 5:
return True
else:
return False
# IF the password gets wrong three times, block the account
if attempts == 3:
current_time = datetime.utcnow().strftime(format_data)
# Update the block time
sql_query = """
UPDATE Users
SET attempts = 0, block_time = '{block_time}'
WHERE username = '{username}'
"""
sql_query = sql_query.format(block_time=current_time, username=username)
self.execute(sql_query)
self.commit()
return False
return True
# -----------------------------------------------------------------------------
# Add a friend to a user
def add_friend(self, username, friend):
# Check if the friend usernmae is exist
if len(self.get_user(friend)) == 0:
return False
sql_cmd = """
INSERT INTO Friends(username, friend)
VALUES('{username}', '{friend}')
"""
sql_cmd = sql_cmd.format(username=username, friend=friend)
self.execute(sql_cmd)
self.commit()
return True
# -----------------------------------------------------------------------------
# Get a user friends list
def get_friendlist(self, username):
sql_query = """
SELECT *
FROM Friends
WHERE username='{username}' or friend='{username}'
"""
sql_cmd = sql_query.format(username=username)
self.execute(sql_cmd)
return self.cur.fetchall()
# -----------------------------------------------------------------------------
# Check if two user is friends
def check_friendlist(self, username, friend_username):
sql_query = """
SELECT *
FROM Friends
WHERE (username = '{username}' and friend = '{friend_username}') or (username = '{friend_username}' and friend = '{username}')
"""
sql_cmd = sql_query.format(username=username, friend_username=friend_username)
self.execute(sql_cmd)
return self.cur.fetchone()
# -----------------------------------------------------------------------------
# Add encrypted message to the database
def add_messages(self, sender_username, receiver_username, encrypted_messagge):
sql_query = """
INSERT INTO Messages(sender_username, receiver_username, encrypted_messagge)
VALUES('{sender_username}', '{receiver_username}', '{encrypted_messagge}')
"""
sql_cmd = sql_query.format(sender_username=sender_username, receiver_username=receiver_username,
encrypted_messagge=encrypted_messagge)
self.execute(sql_cmd)
self.commit()
return True
# -----------------------------------------------------------------------------
# Get encrypted message to the database between two user
def get_messages(self, username, friend_username):
sql_query = """
SELECT *
FROM Messages
WHERE (sender_username = '{username}' and receiver_username = '{friend_username}') or (sender_username = '{friend_username}' and receiver_username = '{username}')
"""
sql_cmd = sql_query.format(username=username, friend_username=friend_username)
self.execute(sql_cmd)
return self.cur.fetchall()
# -----------------------------------------------------------------------------
def add_post(self, title, content, sender_username, section):
add_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sql_query = f'insert into Posts(title,content,sender_username,section,add_time) values' \
f'("{title}","{content}","{sender_username}","{section}","{add_time}") '
self.execute(sql_query)
self.commit()
return self.cur.lastrowid
def delete_post(self, Id):
sql_cmd = f"delete from Posts where Id={Id}"
self.execute(sql_cmd)
self.commit()
return True
def get_post_list(self):
sql_cmd = "select * from Posts"
self.execute(sql_cmd)
return self.cur.fetchall()
def get_post_by_section(self, section):
sql_cmd = f"select * from Posts where section='{section}'"
self.execute(sql_cmd)
return self.cur.fetchall()
def add_comment(self, sender_username, post_id, detail):
add_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sql_query = f'insert into Comments(post_id,sender_username,detail,add_time) values' \
f'("{post_id}","{sender_username}","{detail}","{add_time}") '
self.execute(sql_query)
self.commit()
return self.cur.lastrowid
def delete_comment(self, comment_id):
sql_cmd = f"delete from Comments where Id={comment_id}"
self.execute(sql_cmd)
self.commit()
return True
def get_comments(self, post_id):
sql_cmd = f"select * from Comments where post_id={post_id}"
self.execute(sql_cmd)
return self.cur.fetchall()
def get_user_list(self):
sql_cmd = f"select username,avatar,block from Users"
self.execute(sql_cmd)
return self.cur.fetchall()
def block_user(self, username, block='YES'):
sql_cmd = f"update Users set block='{block}' where username='{username}'"
self.execute(sql_cmd)
self.commit()
return True
def update_password(self, username, password):
salt = uuid.uuid4().hex
password_salt = salt + password
password_hash = hashlib.sha256(password_salt.encode()).hexdigest()
password_double_encrypted = bcrypt.hashpw(password_hash.encode('ascii'), bcrypt.gensalt()).hex()
sql_cmd = f"update Users set password='{password_double_encrypted}',salt='{salt}' where username='{username}'"
self.execute(sql_cmd)
self.commit()
return True
def update_avatar(self, username, avatar):
sql_cmd = f"update Users set avatar='{avatar}' where username='{username}'"
self.cur.execute(sql_cmd)
self.commit()
return True
def is_block(self, username):
sql_cmd = f"select block from Users where username='{username}'"
self.execute(sql_cmd)
data = self.cur.fetchall()
if not data:
return True
else:
return data[0][-1] == "YES"
# sql = SQLDatabase()
# sql.database_setup()
# sql.add_post('1', '1', '1', '1')
# row_id = sql.add_post('1', '1', '1', '1')
# sql.delete_post(row_id)
# print(sql.get_post_list())