-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
495 lines (400 loc) · 13.4 KB
/
db.py
File metadata and controls
495 lines (400 loc) · 13.4 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
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
import os
import json
import logging
import uuid
import bcrypt
import requests
import mysql.connector
from mysql.connector import pooling, errors
from datetime import datetime, timedelta
from urllib.parse import urlparse, urlsplit
import jwt
from dotenv import load_dotenv
import re
from html import unescape
load_dotenv()
DB_CONFIG = {
"host": os.environ.get("DB_HOST"),
"user": os.environ.get("DB_USER"),
"password": os.environ.get("DB_PASS"),
"database": os.environ.get("DB_NAME"),
"pool_name": "opensum_pool",
"pool_size": int(os.environ.get("DB_POOL_SIZE", 5)),
}
SESSION_DURATION_HOURS = int(os.environ.get("SESSION_DURATION_HOURS", 24))
logger = logging.getLogger("db")
logging.basicConfig(level=logging.INFO)
cnxpool = None
def get_connection():
return cnxpool.get_connection()
def dict_from_row(cursor, row): # needs cur cause it contains sql informations like columns etc
if row is None:
return None
return {col[0]: row[idx] for idx, col in enumerate(cursor.description)}
def rows_to_dicts(cursor, rows): # needs cur cause it contains sql informations like columns etc
cols = [c[0] for c in cursor.description]
return [dict(zip(cols, row)) for row in rows]
def init_db():
global cnxpool
# temp conn
temp_conn = mysql.connector.connect(
host=DB_CONFIG["host"],
user=DB_CONFIG["user"],
password=DB_CONFIG["password"]
)
temp_cursor = temp_conn.cursor()
# create db
try:
temp_cursor.execute(f"CREATE DATABASE IF NOT EXISTS {DB_CONFIG['database']}")
logger.info(f"'{DB_CONFIG['database']}' db exists")
except errors.DatabaseError as e:
logger.error(f"err creating db: {e}")
temp_conn.close()
return False
# close temp conn
temp_cursor.close()
temp_conn.close()
# create conn pool
cnxpool = pooling.MySQLConnectionPool(
pool_name=DB_CONFIG["pool_name"],
pool_size=DB_CONFIG["pool_size"],
host=DB_CONFIG["host"],
user=DB_CONFIG["user"],
password=DB_CONFIG["password"],
database=DB_CONFIG["database"]
)
# create tables and admin
conn = cnxpool.get_connection()
cursor = conn.cursor()
try:
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id VARCHAR(36) PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
created_at DATETIME NOT NULL,
user_status TINYINT DEFAULT 1
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS sessions (
id VARCHAR(36) PRIMARY KEY,
user_id VARCHAR(36) NOT NULL,
token VARCHAR(255) NOT NULL,
expires_at DATETIME NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS summaries (
id VARCHAR(36) PRIMARY KEY,
title VARCHAR(255) NOT NULL,
summary TEXT NOT NULL,
user_id VARCHAR(36) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
""")
# check if there's any users in the database
cursor.execute("SELECT COUNT(*) FROM users")
user_count = cursor.fetchone()[0]
if user_count == 0:
user_id = str(uuid.uuid4())
created_at = datetime.utcnow()
password_hash = bcrypt.hashpw(b"password", bcrypt.gensalt()).decode('utf-8')
cursor.execute(
"""
INSERT INTO users (id, username, password_hash, email, created_at, user_status)
VALUES (%s, %s, %s, %s, %s, %s)
""",
(user_id, "admin", password_hash, "admin@buage.dev", created_at, 1)
)
conn.commit()
logger.info("admin user created!")
else:
logger.info("users already exist, skipping admin creation")
except errors.ProgrammingError as e:
logger.error(f"an error occured while creating admin user or db: {e}")
return False
finally:
cursor.close()
conn.close()
return True
def get_user_by_email(email):
conn = get_connection()
try:
cur = conn.cursor() # database connection, required to exec sql
cur.execute("SELECT * FROM users WHERE email = %s", (email,)) # sql to exec
row = cur.fetchone() # fetch only one result ( can use fetchall() too but useless here )
if not row:
return None
user = dict_from_row(cur, row)
user_obj = {
"id": user.get("id"), # user id
"username": user.get("username"),
"email": user.get("email"),
"password_hash": user.get("password_hash"),
"createdAt": user.get("created_at"),
"profile": json.loads(user.get("profile")) if user.get("profile") else {}, # user raw public profile data, will return something like {'bio': 'Test', 'id': '1' etc...}
"publicKey": user.get("public_key"),
"privateKey": user.get("private_key")
}
return user_obj
finally:
cur.close() # close the cursor, required to prevent memory leak or locks
conn.close() # close connection (conn) in a clean way to prevent crashes
def authenticate(token):
if not token:
return None
conn = get_connection()
try:
cur = conn.cursor(dictionary=True)
cur.execute(
'SELECT user_id FROM sessions WHERE token = %s AND expires_at > NOW()',
(token,)
)
row = cur.fetchone()
if not row:
return None
return get_user_by_id(row["user_id"])
finally:
cur.close()
conn.close()
def get_user_by_session(token): # old version function
return authenticate(token)
def login(email, password):
user = get_user_by_email(email)
if not user:
return None
password_hash = user.get("password_hash")
if not password_hash or not bcrypt.checkpw(password.encode('utf-8'), password_hash.encode('utf-8')):
return None
session_token = os.urandom(32).hex()
expires_at = datetime.utcnow() + timedelta(hours=int(SESSION_DURATION_HOURS))
rid = str(uuid.uuid4())
conn = get_connection()
try:
cur = conn.cursor()
cur.execute(
'INSERT INTO sessions (id, user_id, token, expires_at) VALUES (%s, %s, %s, %s)',
(rid, user['id'], session_token, expires_at)
)
conn.commit()
finally:
cur.close()
conn.close()
return {"token": session_token, "expiresAt": expires_at}
def get_user_by_id(user_id):
conn = get_connection()
try:
cur = conn.cursor()
cur.execute('SELECT * FROM users WHERE id=%s', (user_id,))
row = cur.fetchone()
if not row:
return None
user = dict_from_row(cur, row)
return {
"id": user.get("id"),
"username": user.get("username"),
"email": user.get("email"),
"password_hash": user.get("password_hash"),
"createdAt": user.get("created_at"),
"user_stats": user.get("user_status")
}
finally:
cur.close()
conn.close()
def update_username(user_id, new_username):
conn = get_connection()
try:
cur = conn.cursor()
cur.execute('UPDATE users SET username=%s WHERE id=%s', (new_username, user_id))
row = cur.fetchone()
conn.commit()
if not row:
return None
user = dict_from_row(cur, row)
return {
"id": user.get("id"),
"username": user.get("username"),
"email": user.get("email"),
"password_hash": user.get("password_hash"),
"createdAt": user.get("created_at"),
"user_stats": user.get("user_status")
}
finally:
cur.close()
conn.close()
def update_email(user_id, new_email):
conn = get_connection()
try:
cur = conn.cursor()
cur.execute('UPDATE users SET email=%s WHERE id=%s', (new_email, user_id))
row = cur.fetchone()
conn.commit()
if not row:
return None
user = dict_from_row(cur, row)
return {
"id": user.get("id"),
"username": user.get("username"),
"email": user.get("email"),
"password_hash": user.get("password_hash"),
"createdAt": user.get("created_at"),
"user_stats": user.get("user_status")
}
finally:
cur.close()
conn.close()
import bcrypt
def update_password(user_id, new_password):
if not new_password:
return None
conn = get_connection()
try:
cur = conn.cursor()
password_hash = bcrypt.hashpw(
new_password.encode('utf-8'),
bcrypt.gensalt()
).decode('utf-8')
cur.execute(
'UPDATE users SET password_hash=%s WHERE id=%s',
(password_hash, user_id)
)
conn.commit()
cur.execute('SELECT * FROM users WHERE id=%s', (user_id,))
row = cur.fetchone()
if not row:
return None
user = dict_from_row(cur, row)
return {
"id": user.get("id"),
"username": user.get("username"),
"email": user.get("email"),
"password_hash": user.get("password_hash"),
"createdAt": user.get("created_at"),
"user_stats": user.get("user_stats")
}
except Exception as e:
conn.rollback()
raise
finally:
cur.close()
conn.close()
def verify_password(user_id, pswrd):
if not pswrd:
return None
conn = get_connection()
try:
cur = conn.cursor(dictionary=True)
cur.execute(
'SELECT password_hash FROM users WHERE id = %s',
(user_id,)
)
row = cur.fetchone()
if not row:
return None
password_hash = row["password_hash"]
if not bcrypt.checkpw(pswrd.encode('utf-8'), password_hash.encode('utf-8')):
return None
return get_user_by_id(user_id)
finally:
cur.close()
conn.close()
# summaries
def saveSummary(title, summary, userId):
summary_id = str(uuid.uuid4())
created_at = datetime.utcnow()
conn = get_connection()
try:
cur = conn.cursor()
cur.execute(
"""
INSERT INTO summaries (id, title, summary, user_id, created_at)
VALUES (%s, %s, %s, %s, %s)
""",
(summary_id, title, summary, userId, created_at)
)
conn.commit()
logger.info(f"saved : {title}")
return {"id": summary_id, "title": title, "createdAt": created_at}
except errors.DatabaseError as e:
logger.error(f"error saving summary: {e}")
return None
finally:
cur.close()
conn.close()
def getSummary(summary_id):
conn = get_connection()
try:
cur = conn.cursor()
cur.execute(
"SELECT * FROM summaries WHERE id = %s",
(summary_id,)
)
row = cur.fetchone()
if not row:
return None
summary = dict_from_row(cur, row)
return {
"id": summary.get("id"),
"title": summary.get("title"),
"summary": summary.get("summary"),
"userId": summary.get("user_id"),
"createdAt": summary.get("created_at")
}
except errors.DatabaseError as e:
logger.error(f"Erreur lors de la récupération du résumé: {e}")
return None
finally:
cur.close()
conn.close()
def getSummariesByUser(user_id):
conn = get_connection()
try:
cur = conn.cursor()
cur.execute(
"SELECT * FROM summaries WHERE user_id = %s ORDER BY created_at DESC",
(user_id,)
)
rows = cur.fetchall()
if not rows:
return []
summaries = rows_to_dicts(cur, rows)
return [{
"id": s.get("id"),
"title": s.get("title"),
"summary": s.get("summary"),
"userId": s.get("user_id"),
"createdAt": s.get("created_at")
} for s in summaries]
except errors.DatabaseError as e:
logger.error(f"Erreur lors de la récupération des résumés: {e}")
return None
finally:
cur.close()
conn.close()
def deleteSummary(summary_id):
conn = get_connection()
try:
cur = conn.cursor()
cur.execute(
"DELETE FROM summaries WHERE id = %s",
(summary_id,)
)
if cur.rowcount > 0:
conn.commit()
return True
else:
return False
except Exception as e:
logger.error(f"error deleting summary: {e}")
conn.rollback()
return None
finally:
cur.close()
conn.close()
if not init_db():
logger.error("error")
raise RuntimeError("couldnt init the db")