Update database.py
Browse files- database.py +163 -161
database.py
CHANGED
|
@@ -1,161 +1,163 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
from
|
| 6 |
-
import
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def
|
| 18 |
-
"""Initialize database
|
| 19 |
-
try:
|
| 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 |
-
logger.
|
| 73 |
-
return
|
| 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 |
-
if
|
| 159 |
-
logger.
|
| 160 |
-
|
| 161 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# database.py
|
| 2 |
+
import sqlite3
|
| 3 |
+
import hashlib
|
| 4 |
+
import logging
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Optional, Dict, Any
|
| 7 |
+
|
| 8 |
+
# Set up logging
|
| 9 |
+
logging.basicConfig(level=logging.INFO)
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
class Database:
|
| 13 |
+
def __init__(self, db_path: str = "users.db"):
|
| 14 |
+
self.db_path = db_path
|
| 15 |
+
self.init_database()
|
| 16 |
+
|
| 17 |
+
def init_database(self):
|
| 18 |
+
"""Initialize the database and create tables"""
|
| 19 |
+
try:
|
| 20 |
+
# Ensure directory exists
|
| 21 |
+
Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
|
| 22 |
+
|
| 23 |
+
conn = sqlite3.connect(self.db_path)
|
| 24 |
+
cursor = conn.cursor()
|
| 25 |
+
|
| 26 |
+
# Create users table with proper constraints
|
| 27 |
+
cursor.execute('''
|
| 28 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 29 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 30 |
+
username TEXT UNIQUE NOT NULL,
|
| 31 |
+
password_hash TEXT NOT NULL,
|
| 32 |
+
role TEXT NOT NULL,
|
| 33 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 34 |
+
)
|
| 35 |
+
''')
|
| 36 |
+
|
| 37 |
+
conn.commit()
|
| 38 |
+
conn.close()
|
| 39 |
+
logger.info("Database initialized successfully")
|
| 40 |
+
|
| 41 |
+
except Exception as e:
|
| 42 |
+
logger.error(f"Error initializing database: {e}")
|
| 43 |
+
raise
|
| 44 |
+
|
| 45 |
+
def hash_password(self, password: str) -> str:
|
| 46 |
+
"""Hash a password using SHA-256"""
|
| 47 |
+
return hashlib.sha256(password.encode()).hexdigest()
|
| 48 |
+
|
| 49 |
+
def create_user(self, username: str, password: str, role: str) -> bool:
|
| 50 |
+
"""Create a new user"""
|
| 51 |
+
try:
|
| 52 |
+
conn = sqlite3.connect(self.db_path)
|
| 53 |
+
cursor = conn.cursor()
|
| 54 |
+
|
| 55 |
+
password_hash = self.hash_password(password)
|
| 56 |
+
|
| 57 |
+
cursor.execute('''
|
| 58 |
+
INSERT INTO users (username, password_hash, role)
|
| 59 |
+
VALUES (?, ?, ?)
|
| 60 |
+
''', (username, password_hash, role))
|
| 61 |
+
|
| 62 |
+
conn.commit()
|
| 63 |
+
conn.close()
|
| 64 |
+
logger.info(f"User '{username}' created successfully with role '{role}'")
|
| 65 |
+
return True
|
| 66 |
+
|
| 67 |
+
except sqlite3.IntegrityError as e:
|
| 68 |
+
if "UNIQUE constraint failed" in str(e):
|
| 69 |
+
logger.info(f"User '{username}' already exists, skipping...")
|
| 70 |
+
return False # User already exists, not really an error
|
| 71 |
+
else:
|
| 72 |
+
logger.error(f"Integrity error creating user '{username}': {e}")
|
| 73 |
+
return False
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logger.error(f"Error creating user '{username}': {e}")
|
| 76 |
+
return False
|
| 77 |
+
|
| 78 |
+
def verify_user(self, username: str, password: str) -> Optional[Dict[str, Any]]:
|
| 79 |
+
"""Verify user credentials and return user info"""
|
| 80 |
+
try:
|
| 81 |
+
conn = sqlite3.connect(self.db_path)
|
| 82 |
+
cursor = conn.cursor()
|
| 83 |
+
|
| 84 |
+
password_hash = self.hash_password(password)
|
| 85 |
+
|
| 86 |
+
cursor.execute('''
|
| 87 |
+
SELECT username, role FROM users
|
| 88 |
+
WHERE username = ? AND password_hash = ?
|
| 89 |
+
''', (username, password_hash))
|
| 90 |
+
|
| 91 |
+
result = cursor.fetchone()
|
| 92 |
+
conn.close()
|
| 93 |
+
|
| 94 |
+
if result:
|
| 95 |
+
return {
|
| 96 |
+
"username": result[0],
|
| 97 |
+
"role": result[1]
|
| 98 |
+
}
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
logger.error(f"Error verifying user '{username}': {e}")
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
def list_users(self) -> list:
|
| 106 |
+
"""List all users (for debugging)"""
|
| 107 |
+
try:
|
| 108 |
+
conn = sqlite3.connect(self.db_path)
|
| 109 |
+
cursor = conn.cursor()
|
| 110 |
+
|
| 111 |
+
cursor.execute('SELECT username, role FROM users')
|
| 112 |
+
users = cursor.fetchall()
|
| 113 |
+
conn.close()
|
| 114 |
+
|
| 115 |
+
return [{"username": user[0], "role": user[1]} for user in users]
|
| 116 |
+
|
| 117 |
+
except Exception as e:
|
| 118 |
+
logger.error(f"Error listing users: {e}")
|
| 119 |
+
return []
|
| 120 |
+
|
| 121 |
+
# Create global database instance
|
| 122 |
+
db = Database()
|
| 123 |
+
|
| 124 |
+
def initialize_users():
|
| 125 |
+
"""Initialize default users"""
|
| 126 |
+
default_users = [
|
| 127 |
+
("Tony", "password123", "engineering"),
|
| 128 |
+
("Bruce", "securepass", "marketing"),
|
| 129 |
+
("Sam", "financepass", "finance"),
|
| 130 |
+
("Natasha", "hrpass123", "hr"),
|
| 131 |
+
]
|
| 132 |
+
|
| 133 |
+
success_count = 0
|
| 134 |
+
error_count = 0
|
| 135 |
+
|
| 136 |
+
logger.info("Initializing default users...")
|
| 137 |
+
|
| 138 |
+
for username, password, role in default_users:
|
| 139 |
+
try:
|
| 140 |
+
if db.create_user(username, password, role):
|
| 141 |
+
success_count += 1
|
| 142 |
+
else:
|
| 143 |
+
# User already exists, count as success but log as info
|
| 144 |
+
success_count += 1
|
| 145 |
+
# The error_count was being incremented for existing users
|
| 146 |
+
# which is why you were seeing "6 errors" - let's not count this as an error
|
| 147 |
+
except Exception as e:
|
| 148 |
+
error_count += 1
|
| 149 |
+
logger.error(f"Failed to create user {username}: {e}")
|
| 150 |
+
|
| 151 |
+
if error_count == 0:
|
| 152 |
+
logger.info(f"User initialization successful: {success_count} users ready")
|
| 153 |
+
else:
|
| 154 |
+
logger.info(f"User initialization completed: {success_count} successful, {error_count} errors")
|
| 155 |
+
|
| 156 |
+
# List all users for verification
|
| 157 |
+
users = db.list_users()
|
| 158 |
+
if users:
|
| 159 |
+
logger.info(f"Available users: {', '.join([f\"{u['username']}({u['role']})\" for u in users])}")
|
| 160 |
+
else:
|
| 161 |
+
logger.warning("No users found in database!")
|
| 162 |
+
|
| 163 |
+
return success_count, error_count
|