-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_manager.py
More file actions
42 lines (37 loc) · 1.69 KB
/
Copy pathdatabase_manager.py
File metadata and controls
42 lines (37 loc) · 1.69 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
# database_manager.py
import sqlite3
from threading import Lock
from werkzeug.security import generate_password_hash, check_password_hash
class SecureDatabase:
"""Thread-safe SQLite database manager"""
def __init__(self, db_path: str = "ai_system.db"):
self.db_path = db_path
self.lock = Lock()
self._init_db()
def _init_db(self):
with self.lock, sqlite3.connect(self.db_path) as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT UNIQUE,
password_hash TEXT
)""")
conn.execute("""
CREATE TABLE IF NOT EXISTS interactions (
id INTEGER PRIMARY KEY,
user_id INTEGER,
query TEXT,
response TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(user_id) REFERENCES users(id)
)""")
def create_user(self, username: str, password: str):
with self.lock, sqlite3.connect(self.db_path) as conn:
conn.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)",
(username, generate_password_hash(password)))
def authenticate(self, username: str, password: str) -> bool:
with self.lock, sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT password_hash FROM users WHERE username = ?", (username,))
result = cursor.fetchone()
return result and check_password_hash(result[0], password)