|
import sqlite3 |
|
import bcrypt |
|
import os |
|
from datetime import datetime |
|
|
|
DB_FILE = "user_auth.db" |
|
|
|
|
|
def initialize_database(): |
|
if not os.path.exists(DB_FILE): |
|
conn = sqlite3.connect(DB_FILE) |
|
c = conn.cursor() |
|
|
|
c.execute(""" |
|
CREATE TABLE users ( |
|
username TEXT PRIMARY KEY, |
|
password_hash TEXT |
|
) |
|
""") |
|
|
|
c.execute(""" |
|
CREATE TABLE user_settings ( |
|
username TEXT PRIMARY KEY, |
|
topic TEXT, |
|
instructions TEXT, |
|
timestamp TEXT, |
|
FOREIGN KEY (username) REFERENCES users (username) |
|
) |
|
""") |
|
conn.commit() |
|
conn.close() |
|
|
|
|
|
def add_user(username, password): |
|
conn = sqlite3.connect(DB_FILE) |
|
c = conn.cursor() |
|
password_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode() |
|
try: |
|
c.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)", (username, password_hash)) |
|
conn.commit() |
|
except sqlite3.IntegrityError: |
|
conn.close() |
|
return False |
|
conn.close() |
|
return True |
|
|
|
|
|
def authenticate_user(username, password): |
|
conn = sqlite3.connect(DB_FILE) |
|
c = conn.cursor() |
|
c.execute("SELECT password_hash FROM users WHERE username = ?", (username,)) |
|
row = c.fetchone() |
|
conn.close() |
|
if row and bcrypt.checkpw(password.encode(), row[0].encode()): |
|
return True |
|
return False |
|
|
|
|
|
def load_settings(username): |
|
conn = sqlite3.connect(DB_FILE) |
|
c = conn.cursor() |
|
c.execute("SELECT topic, instructions FROM user_settings WHERE username = ?", (username,)) |
|
row = c.fetchone() |
|
conn.close() |
|
if row: |
|
return {"topic": row[0], "instructions": row[1]} |
|
return {"topic": "", "instructions": ""} |
|
|
|
|
|
def save_settings(username, settings): |
|
conn = sqlite3.connect(DB_FILE) |
|
c = conn.cursor() |
|
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
|
c.execute(""" |
|
INSERT INTO user_settings (username, topic, instructions, timestamp) |
|
VALUES (?, ?, ?, ?) |
|
ON CONFLICT(username) |
|
DO UPDATE SET topic = excluded.topic, instructions = excluded.instructions, timestamp = excluded.timestamp |
|
""", (username, settings["topic"], settings["instructions"], timestamp)) |
|
conn.commit() |
|
conn.close() |
|
|
|
|
|
def generate_prompt(topic, instructions): |
|
return f"Generated prompt based on topic '{topic}' and instructions: '{instructions}'." |
|
|