Spaces:
Sleeping
Sleeping
Create init__db.py
Browse files- init__db.py +40 -0
init__db.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sqlite3
|
2 |
+
import bcrypt
|
3 |
+
|
4 |
+
class SecureDatabase:
|
5 |
+
def __init__(self, db_path: str = "secure_ai_agix.db"):
|
6 |
+
self.db_path = db_path
|
7 |
+
self._init_db()
|
8 |
+
|
9 |
+
def _init_db(self):
|
10 |
+
with sqlite3.connect(self.db_path) as conn:
|
11 |
+
conn.execute(
|
12 |
+
"CREATE TABLE IF NOT EXISTS users ("
|
13 |
+
"id INTEGER PRIMARY KEY, "
|
14 |
+
"username TEXT UNIQUE, "
|
15 |
+
"password_hash TEXT)"
|
16 |
+
)
|
17 |
+
conn.execute(
|
18 |
+
"CREATE TABLE IF NOT EXISTS interactions ("
|
19 |
+
"id INTEGER PRIMARY KEY, "
|
20 |
+
"user_id INTEGER, "
|
21 |
+
"query TEXT, "
|
22 |
+
"response TEXT, "
|
23 |
+
"timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)"
|
24 |
+
)
|
25 |
+
|
26 |
+
def create_user(self, username: str, password: str):
|
27 |
+
hashed_password = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
|
28 |
+
with sqlite3.connect(self.db_path) as conn:
|
29 |
+
conn.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)", (username, hashed_password))
|
30 |
+
|
31 |
+
def authenticate(self, username: str, password: str) -> bool:
|
32 |
+
with sqlite3.connect(self.db_path) as conn:
|
33 |
+
cursor = conn.cursor()
|
34 |
+
cursor.execute("SELECT password_hash FROM users WHERE username = ?", (username,))
|
35 |
+
result = cursor.fetchone()
|
36 |
+
return result and bcrypt.checkpw(password.encode(), result[0])
|
37 |
+
|
38 |
+
if __name__ == "__main__":
|
39 |
+
db = SecureDatabase()
|
40 |
+
db.create_user("admin", "securepassword")
|