Spaces:
Running
Running
File size: 1,535 Bytes
105e4a4 |
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 |
import sqlite3
import bcrypt
class SecureDatabase:
def __init__(self, db_path: str = "secure_ai_agix.db"):
self.db_path = db_path
self._init_db()
def _init_db(self):
with 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)"
)
def create_user(self, username: str, password: str):
hashed_password = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
with sqlite3.connect(self.db_path) as conn:
conn.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)", (username, hashed_password))
def authenticate(self, username: str, password: str) -> bool:
with 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 bcrypt.checkpw(password.encode(), result[0])
if __name__ == "__main__":
db = SecureDatabase()
db.create_user("admin", "securepassword")
|