Spaces:
Running
Running
File size: 14,696 Bytes
3060aa0 5724eea 3060aa0 5724eea 3060aa0 5724eea 3060aa0 5724eea 3060aa0 5724eea 3060aa0 5724eea 3060aa0 5724eea | 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 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 73 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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | # PyFundaments: A Secure Python Architecture
# Copyright 2008-2025 - Volkan Kücükbudak
# Apache License V. 2
# Repo: https://github.com/VolkanSah/PyFundaments
# root/fundaments/user_handler.py
# A Python module for handling user authentication and session management.
import sqlite3
import uuid
from datetime import datetime, timedelta
from passlib.hash import pbkdf2_sha256
import os
class Database:
"""
Handles the SQLite database connection and initialization.
Supports dynamic path selection via environment variables with a
fallback to the local application directory.
"""
def __init__(self, db_name="cms_database.db"):
# 1. Attempt to load the database path from an environment variable
# This allows for flexible configuration in production/Docker environments
env_path = os.getenv("SQLITE_PATH")
if env_path:
# Use the absolute path provided by the environment variable
full_db_path = os.path.abspath(env_path)
else:
# Fallback logic: Locate the 'app' directory relative to this script
# Expected structure: root/fun/user_handler.py -> root/app/
base_path = os.path.dirname(os.path.abspath(__file__))
app_dir = os.path.join(base_path, "..", "app")
full_db_path = os.path.join(app_dir, db_name)
# 2. Ensure the target directory exists before attempting to connect
# SQLite can create the file, but not the parent folders.
db_dir = os.path.dirname(full_db_path)
if db_dir and not os.path.exists(db_dir):
os.makedirs(db_dir)
# Initialize the connection and cursor
self.conn = sqlite3.connect(full_db_path)
self.cursor = self.conn.cursor()
# Log the active database path for debugging purposes
print(f"Database connected to: {full_db_path}")
def execute(self, query, params=None):
if params is None:
params = []
self.cursor.execute(query, params)
self.conn.commit()
def fetchone(self, query, params=None):
if params is None:
params = []
self.cursor.execute(query, params)
return self.cursor.fetchone()
def fetchall(self, query, params=None):
if params is None:
params = []
self.cursor.execute(query, params)
return self.cursor.fetchall()
def close(self):
self.conn.close()
def setup_tables(self):
"""
Creates the necessary tables for users and sessions.
"""
self.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
is_admin INTEGER NOT NULL DEFAULT 0,
account_locked INTEGER NOT NULL DEFAULT 0,
failed_login_attempts INTEGER NOT NULL DEFAULT 0
)
""")
self.execute("""
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
ip_address TEXT,
user_agent TEXT,
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
""")
class Security:
"""
Handles secure password hashing and session regeneration.
Using passlib for robust and secure password management.
"""
@staticmethod
def hash_password(password: str) -> str:
"""Hashes a password using PBKDF2 with SHA256."""
return pbkdf2_sha256.hash(password)
@staticmethod
def verify_password(password: str, hashed_password: str) -> bool:
"""Verifies a password against a stored hash."""
return pbkdf2_sha256.verify(password, hashed_password)
@staticmethod
def regenerate_session(session_id: str):
"""
Simulates regenerating a session ID to prevent session fixation.
In a real web framework, this would be a framework-specific function.
"""
print(f"Session regenerated. Old ID: {session_id}")
new_session_id = str(uuid.uuid4())
print(f"New ID: {new_session_id}")
return new_session_id
class UserHandler:
"""
Handles user login, logout, and session validation.
This class mirrors the logic from the user's PHP User class.
"""
def __init__(self, db: Database):
self.db = db
# A simple in-memory session store for this example
self._session = {}
def login(self, username: str, password: str, request_data: dict) -> bool:
"""
Logs in the user by verifying credentials and storing a new session.
:param username: The user's username.
:param password: The user's plain-text password.
:param request_data: A dictionary containing 'ip_address' and 'user_agent'.
:return: True if login is successful, False otherwise.
"""
try:
# Step 1: Find the user in the database
user_data = self.db.fetchone("SELECT id, username, password, is_admin, account_locked, failed_login_attempts FROM users WHERE username = ?", (username,))
if user_data is None:
print(f"Login failed: Username '{username}' not found.")
return False
user = {
'id': user_data[0],
'username': user_data[1],
'password': user_data[2],
'is_admin': user_data[3],
'account_locked': user_data[4],
'failed_login_attempts': user_data[5]
}
# Check if account is locked
if user['account_locked'] == 1:
print(f"Login failed: Account for '{username}' is locked.")
return False
# Step 2: Verify the password
if Security.verify_password(password, user['password']):
print(f"Login successful for user: '{username}'")
# Reset failed login attempts on success
self.reset_failed_attempts(username)
# Step 3: Create a new session record in the database
session_id = str(uuid.uuid4())
ip_address = request_data.get('ip_address', 'unknown')
user_agent = request_data.get('user_agent', 'unknown')
self.db.execute(
"INSERT INTO sessions (id, user_id, ip_address, user_agent) VALUES (?, ?, ?, ?)",
(session_id, user['id'], ip_address, user_agent)
)
# Step 4: Store session data in the in-memory session (or a session store)
self._session = {
'session_id': session_id,
'user_id': user['id'],
'username': user['username'],
'is_admin': user['is_admin']
}
# Security: Regenerate session ID
self._session['session_id'] = Security.regenerate_session(session_id)
return True
else:
print(f"Login failed: Incorrect password for user '{username}'.")
# Increment failed login attempts
self.increment_failed_attempts(username)
return False
except sqlite3.Error as e:
print(f"Database error during login: {e}")
return False
def logout(self) -> bool:
"""
Logs out the current user by deleting the session from the database.
:return: True if logout is successful, False otherwise.
"""
if 'user_id' not in self._session:
print("No active session to log out.")
return False
try:
# Step 1: Delete the session from the database
self.db.execute("DELETE FROM sessions WHERE user_id = ?", (self._session['user_id'],))
# Step 2: Clear the in-memory session data
self._session.clear()
print("User logged out successfully.")
return True
except sqlite3.Error as e:
print(f"Database error during logout: {e}")
return False
def is_logged_in(self) -> bool:
"""
Checks if the current user is logged in.
:return: True if a valid session exists, False otherwise.
"""
if 'user_id' not in self._session:
return False
try:
# Check for the session in the database
session_data = self.db.fetchone(
"SELECT * FROM sessions WHERE id = ? AND user_id = ?",
(self._session['session_id'], self._session['user_id'])
)
return session_data is not None
except sqlite3.Error as e:
print(f"Database error during is_logged_in check: {e}")
return False
def is_admin(self) -> bool:
"""
Checks if the logged-in user is an admin.
:return: True if the user is an admin, False otherwise.
"""
return self._session.get('is_admin', 0) == 1
def validate_session(self, request_data: dict) -> bool:
"""
Validates the current session against IP address and user agent.
:param request_data: A dictionary containing 'ip_address' and 'user_agent'.
:return: True if the session is valid, False otherwise.
"""
if not self.is_logged_in():
return False
try:
ip_address = request_data.get('ip_address', 'unknown')
user_agent = request_data.get('user_agent', 'unknown')
session_data = self.db.fetchone(
"SELECT * FROM sessions WHERE id = ? AND user_id = ? AND ip_address = ? AND user_agent = ?",
(self._session['session_id'], self._session['user_id'], ip_address, user_agent)
)
return session_data is not None
except sqlite3.Error as e:
print(f"Database error during session validation: {e}")
return False
def lock_account(self, username: str):
"""
Locks a user account.
:param username: The username of the account to lock.
"""
try:
self.db.execute("UPDATE users SET account_locked = 1 WHERE username = ?", (username,))
print(f"Account for '{username}' has been locked.")
except sqlite3.Error as e:
print(f"Database error while locking account: {e}")
def reset_failed_attempts(self, username: str):
"""
Resets failed login attempts for a user.
:param username: The username of the account.
"""
try:
self.db.execute("UPDATE users SET failed_login_attempts = 0 WHERE username = ?", (username,))
except sqlite3.Error as e:
print(f"Database error while resetting failed attempts: {e}")
def increment_failed_attempts(self, username: str):
"""
Increments failed login attempts and locks the account if a threshold is met.
:param username: The username of the account.
"""
try:
# Get the current failed attempts
user_data = self.db.fetchone("SELECT failed_login_attempts FROM users WHERE username = ?", (username,))
if user_data:
attempts = user_data[0] + 1
self.db.execute(
"UPDATE users SET failed_login_attempts = ? WHERE username = ?",
(attempts, username)
)
print(f"Failed login attempts for '{username}': {attempts}")
# Check for threshold (e.g., 5 attempts)
if attempts >= 5:
self.lock_account(username)
except sqlite3.Error as e:
print(f"Database error while incrementing failed attempts: {e}")
# --- Example Usage ---
if __name__ == "__main__":
db = Database()
db.setup_tables()
user_handler = UserHandler(db)
# Clean up old test data if it exists
db.execute("DELETE FROM users WHERE username IN (?, ?)", ("testuser", "adminuser"))
db.execute("DELETE FROM sessions")
# 1. Register a new user and an admin user
hashed_password = Security.hash_password("secure_password_123")
db.execute("INSERT INTO users (username, password) VALUES (?, ?)", ("testuser", hashed_password))
db.execute("INSERT INTO users (username, password, is_admin) VALUES (?, ?, 1)", ("adminuser", hashed_password))
print("--- Test 1: Successful Login ---")
# Simulate a web request
request_data = {
'ip_address': '192.168.1.100',
'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
login_success = user_handler.login("testuser", "secure_password_123", request_data)
print(f"Login attempt status: {login_success}")
print(f"Is user logged in? {user_handler.is_logged_in()}")
print(f"Is user an admin? {user_handler.is_admin()}")
print(f"Is session valid? {user_handler.validate_session(request_data)}")
print("-" * 20)
# 2. Simulate a logout
print("--- Test 2: Logout ---")
user_handler.logout()
print(f"Is user logged in after logout? {user_handler.is_logged_in()}")
print("-" * 20)
# 3. Simulate a failed login and account lock
print("--- Test 3: Failed Login and Account Lock ---")
# Log in with the wrong password multiple times
for i in range(6):
user_handler.login("testuser", "wrong_password", request_data)
# Now, try to log in with the correct password. It should fail because the account is locked.
print("\nAttempting to log in with correct password after lock:")
login_attempt_after_lock = user_handler.login("testuser", "secure_password_123", request_data)
print(f"Login attempt status: {login_attempt_after_lock}")
print("-" * 20)
# 4. Reset failed attempts for a new login
print("--- Test 4: Resetting failed attempts ---")
user_handler.reset_failed_attempts("testuser")
login_attempt_after_reset = user_handler.login("testuser", "secure_password_123", request_data)
print(f"Login attempt status after reset: {login_attempt_after_reset}")
db.close()
# Optional: Clean up the database file after the run
# OLD
# os.remove("cms_database.db")
# NEW : Clean up the database file after the run:
# os.remove(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "app", "cms_database.db")) |