-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
236 lines (200 loc) · 7.72 KB
/
database.py
File metadata and controls
236 lines (200 loc) · 7.72 KB
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
import sqlite3
import hashlib
from os import urandom
from base64 import b64encode
from typing import Optional
conn = sqlite3.connect("server.db", check_same_thread=False)
# conn.execute("PRAGMA foreign_keys = ON;")
################################################################################
# HASHING FUNCTIONS #
################################################################################
def generate_salt() ->bytes:
# 128 bit salt value
salt = urandom(16)
return salt
def hash_password(password: str, salt: Optional[bytes] = None) -> tuple[str, bytes, str, int]:
if salt is None:
salt = generate_salt()
iterations = 100_000
function = "pbkdf2_hmac"
hash_value = b64encode(
hashlib.pbkdf2_hmac(
"sha512",
password.encode("utf-8"),
salt,
iterations
)
).decode("utf-8")
return_value = (hash_value, salt, function, iterations)
return return_value
################################################################################
# STANDARD, MULTI-USE FUNCTIONS #
################################################################################
def exists(table: str, value: str) -> bool:
"""
:param table: clients or chatrooms
:param value: value being tested
:return: true if item exists, false otherwise
"""
with sqlite3.connect(table) as conn:
cursor = conn.conn()
if table == "clients":
column = "username"
elif table == "chatrooms":
column = "chat_name"
else:
return False
query = f"SELECT 1 FROM {table} WHERE {column} = ? LIMIT 1;"
cursor.execute(query, (value,))
result = cursor.fetchone()
return True if result else False
################################################################################
# DB FUNCTIONS #
################################################################################
def init_db() -> bool :
"""
This function initializes the database
Prints a string describing success or errors
Returns: True/False
"""
try:
with sqlite3.connect("server.db") as conn:
cursor = conn.conn()
cursor.execute('''
CREATE TABLE IF NOT EXISTS clients (
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL,
salt BLOB NOT NULL,
hash_algo TEXT NOT NULL,
iterations INTEGER NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS chatrooms (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_name TEXT NOT NULL,
owner_id INTEGER NOT NULL,
FOREIGN KEY (owner_id) REFERENCES clients(user_id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS clients_chatroom (
user_id INTEGER NOT NULL,
chatroom_id INTEGER NOT NULL,
PRIMARY KEY (user_id, chatroom_id),
FOREIGN KEY (user_id) REFERENCES clients(user_id),
FOREIGN KEY (chatroom_id) REFERENCES chatrooms(id)
)
''')
conn.commit()
print("Database initialized")
return True
except sqlite3.OperationalError as e:
print(f"Database operational error: {e}")
return False
except Exception as e:
print(f"Database initialization error: {e}")
return False
def add_user(username: str, password_plaintext: str) -> bool | None:
"""
This function adds a user to the database
:param password_plaintext: plaintext password to add (stored as a hash)
:param username: username of the user
:return: True/False, None if an error occurred
"""
try:
password, salt, hash_algo, iterations = hash_password(password_plaintext)
except ValueError as e:
print(f"Password hashing error: {e}")
return None
try:
if not username or not password:
print("Username or password is empty")
return False
with sqlite3.connect("server.db") as conn:
cursor = conn.conn()
if exists("clients", username):
print("Database integrity error: Username already exists")
return False
else:
cursor.execute('''
INSERT INTO clients(username, password, salt, hash_algo, iterations)
VALUES(?, ?, ?, ?, ?)
''', (username, password, salt, hash_algo, iterations))
conn.commit()
print(f"User [{username}] successfully added")
return True
except sqlite3.OperationalError as e:
print(f"Database initialization error: {e}")
return None
except sqlite3.IntegrityError:
print("Database integrity error: Username already exists")
return False
except Exception as e:
print(f"An error occurred: {e}")
return None
def confirm_login(username: str, password_plaintext: str) -> bool | None:
"""
This function confirms the login of a user
:param username: username the user entered
:param password_plaintext: password the user entered
:return:True/False, None if an error occurred
"""
try:
with sqlite3.connect("server.db") as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT password, salt, hash_algo, iterations
FROM clients
WHERE username = ?
''', (username,))
row = cursor.fetchone()
if row is None:
print(f"User [{username}] does not exist")
return False
stored_password, salt, hash_algo, iterations = row
if hash_algo == "pbkdf2_hmac":
hashed_password = hash_password(password_plaintext, salt=salt)[0]
if hashed_password == stored_password:
print("Successful login")
return True
else:
print("Wrong password")
return False
else:
print(f"Error: [{hash_algo}] is not supported")
return None
except Exception as e:
print(f"Error: {e}")
return None
def create_chatroom(username: str, chat_name: str, settings: dict) -> bool | None:
"""
This functions adds a chatroom id to the database. This will be referenced for client-to-chatroom connections throughout the program.
:param settings: {login_required: bool,
:param username: Username of the owner of the chatroom
:param chat_name: Name of the chatroom
:return: True/False, None if an error occurred
"""
try:
with sqlite3.connect("server.db") as conn:
cursor = conn.cursor()
if not exists("chatrooms", chat_name):
cursor.execute('''
INSERT INTO chatrooms(chat_name, owner_id)
VALUES(?, ?)''', (chat_name, username))
return True
else:
print("Already exists")
return False
except Exception as e:
print(f"Error: {e}")
return None
def join_chatroom(chat_name: str, username: str, password: Optional[str] = None, join_code: Optional[str] = None) -> bool | None:
if exists("chatrooms", chat_name):
return True
if password:
...
if join_code:
...
q