Alibrown commited on
Commit
ce3aa84
·
verified ·
1 Parent(s): 1019332

Delete fundaments

Browse files
fundaments/__init__.py DELETED
@@ -1 +0,0 @@
1
-
 
 
fundaments/access_control.py DELETED
@@ -1,247 +0,0 @@
1
- # PyFundaments: A Secure Python Architecture
2
- # Copyright 2008-2025 - Volkan Kücükbudak
3
- # Apache License V. 2
4
- # Repo: https://github.com/VolkanSah/PyFundaments
5
- # access_control.py
6
- # This is the standalone module for access control.
7
- # It is intended to be imported by main.py or app.py.
8
-
9
- import sys
10
- from typing import Optional, List, Dict, Any
11
-
12
- # Your foundational PostgreSQL module is imported here.
13
- # IMPORTANT: Ensure 'postgresql.py' is in the same directory or accessible
14
- # via the Python path.
15
- from fundaments import postgresql as db
16
- # local db use: db.execute_secured_query(), db.init_db_pool(), etc. but this fundaments are optimized for clouds
17
-
18
-
19
- # If asyncpg is not installed, exit the script gracefully.
20
- try:
21
- import asyncpg
22
- except ImportError:
23
- print("Error: The 'asyncpg' library is required. Please install it with 'pip install asyncpg'.")
24
- sys.exit(1)
25
-
26
-
27
- class AccessControl:
28
- """
29
- Asynchronous class for managing access control.
30
- It builds directly on the functions of your secure database module.
31
- This is the layer that uses the foundation without modifying it.
32
-
33
- How to extend this class:
34
- To add new functionality, simply create a new asynchronous method
35
- within this class. This method can call the `db.execute_secured_query`
36
- function to interact with the database. For example:
37
-
38
- async def get_user_last_login(self):
39
- sql = "SELECT last_login FROM users WHERE id = $1"
40
- result = await db.execute_secured_query(sql, self.user_id, fetch_method='fetchrow')
41
- return result['last_login'] if result else None
42
- """
43
- def __init__(self, user_id: Optional[int] = None):
44
- self.user_id = user_id
45
-
46
- async def has_permission(self, permission_name: str, user_id: Optional[int] = None) -> bool:
47
- """
48
- Checks if the user has a specific permission.
49
- Uses the secure execute_secured_query function from the foundation.
50
-
51
- Args:
52
- permission_name: Name of the permission to check.
53
- user_id: Optional override — lets Security.check_permission()
54
- check ANY user without constructing a new instance.
55
- Falls back to the constructor user_id.
56
- """
57
- effective_user_id = user_id if user_id is not None else self.user_id
58
- if effective_user_id is None:
59
- return False
60
-
61
- # SQL Query Explanation:
62
- # This query counts the number of rows where the user (user_id)
63
- # has a role (user_role_assignments) that is linked to a permission
64
- # (role_permissions) which has the specified name (user_permissions.name).
65
- # If the count is > 0, the user has the permission.
66
- sql = """
67
- SELECT COUNT(*) AS count
68
- FROM user_role_assignments ura
69
- JOIN role_permissions rp ON ura.role_id = rp.role_id
70
- JOIN user_permissions up ON rp.permission_id = up.id
71
- WHERE ura.user_id = $1 AND up.name = $2
72
- """
73
- try:
74
- result = await db.execute_secured_query(
75
- sql,
76
- effective_user_id,
77
- permission_name,
78
- fetch_method='fetchrow'
79
- )
80
- return result['count'] > 0
81
- except Exception as e:
82
- # Error handling is managed by your postgresql module.
83
- # We just re-raise the exception here to propagate it.
84
- raise Exception(f'Failed to check permission: {e}')
85
-
86
- async def get_user_permissions(self) -> List[Dict[str, Any]]:
87
- """Returns all permissions for a user."""
88
- if self.user_id is None:
89
- return []
90
-
91
- # SQL Query Explanation:
92
- # This query retrieves all distinct permission names and descriptions
93
- # associated with the user's roles. `DISTINCT` ensures each permission
94
- # is listed only once.
95
- sql = """
96
- SELECT DISTINCT up.name, up.description
97
- FROM user_role_assignments ura
98
- JOIN role_permissions rp ON ura.role_id = rp.role_id
99
- JOIN user_permissions up ON rp.permission_id = up.id
100
- WHERE ura.user_id = $1
101
- ORDER BY up.name
102
- """
103
- try:
104
- return await db.execute_secured_query(sql, self.user_id)
105
- except Exception as e:
106
- raise Exception(f'Failed to get user permissions: {e}')
107
-
108
- async def get_user_roles(self) -> List[Dict[str, Any]]:
109
- """Returns all roles for a user."""
110
- if self.user_id is None:
111
- return []
112
-
113
- # SQL Query Explanation:
114
- # This query selects the details (id, name, description) of the roles
115
- # that are assigned to the specified user (user_id) in the
116
- # `user_role_assignments` table.
117
- sql = """
118
- SELECT r.id, r.name, r.description
119
- FROM user_role_assignments ura
120
- JOIN user_roles r ON ura.role_id = r.id
121
- WHERE ura.user_id = $1
122
- ORDER BY r.name
123
- """
124
- try:
125
- return await db.execute_secured_query(sql, self.user_id)
126
- except Exception as e:
127
- raise Exception(f'Failed to get user roles: {e}')
128
-
129
- async def assign_role(self, role_id: int) -> None:
130
- """Assigns a role to a user."""
131
- if self.user_id is None:
132
- raise Exception('No user specified')
133
-
134
- # SQL Query Explanation:
135
- # Inserts a new row into the `user_role_assignments` table to create
136
- # the relationship between a user and a role.
137
- sql = "INSERT INTO user_role_assignments (user_id, role_id) VALUES ($1, $2)"
138
- try:
139
- await db.execute_secured_query(
140
- sql,
141
- self.user_id,
142
- role_id,
143
- fetch_method='execute'
144
- )
145
- except Exception as e:
146
- raise Exception(f'Failed to assign role: {e}')
147
-
148
- async def remove_role(self, role_id: int) -> None:
149
- """Removes a role from a user."""
150
- if self.user_id is None:
151
- raise Exception('No user specified')
152
-
153
- # SQL Query Explanation:
154
- # Deletes the row from the `user_role_assignments` table that matches
155
- # the specified user ($1) and role ($2).
156
- sql = "DELETE FROM user_role_assignments WHERE user_id = $1 AND role_id = $2"
157
- try:
158
- await db.execute_secured_query(
159
- sql,
160
- self.user_id,
161
- role_id,
162
- fetch_method='execute'
163
- )
164
- except Exception as e:
165
- raise Exception(f'Failed to remove role: {e}')
166
-
167
- async def get_all_roles(self) -> List[Dict[str, Any]]:
168
- """Returns all available roles."""
169
- # SQL Query Explanation:
170
- # Selects all roles from the `user_roles` table.
171
- sql = "SELECT id, name, description FROM user_roles ORDER BY name"
172
- try:
173
- return await db.execute_secured_query(sql)
174
- except Exception as e:
175
- raise Exception(f'Failed to get roles: {e}')
176
-
177
- async def get_all_permissions(self) -> List[Dict[str, Any]]:
178
- """Returns all available permissions."""
179
- # SQL Query Explanation:
180
- # Selects all permissions from the `user_permissions` table.
181
- sql = "SELECT id, name, description FROM user_permissions ORDER BY name"
182
- try:
183
- return await db.execute_secured_query(sql)
184
- except Exception as e:
185
- raise Exception(f'Failed to get permissions: {e}')
186
-
187
- async def create_role(self, name: str, description: str) -> int:
188
- """Creates a new role."""
189
- # SQL Query Explanation:
190
- # Inserts a new role into the `user_roles` table and returns the
191
- # automatically generated ID of the new role (`RETURNING id`).
192
- sql = "INSERT INTO user_roles (name, description) VALUES ($1, $2) RETURNING id"
193
- try:
194
- result = await db.execute_secured_query(
195
- sql,
196
- name,
197
- description,
198
- fetch_method='fetchrow'
199
- )
200
- return result['id']
201
- except Exception as e:
202
- raise Exception(f'Failed to create role: {e}')
203
-
204
- async def update_role_permissions(self, role_id: int, permission_ids: List[int]) -> None:
205
- """Updates the permissions for a role."""
206
- # IMPORTANT: Since your module does not handle transactions across multiple
207
- # queries, we perform these actions sequentially. Query-level security
208
- # is guaranteed by your module.
209
- try:
210
- # SQL Query Explanation:
211
- # Deletes all existing permissions for the given role.
212
- sql_delete = "DELETE FROM role_permissions WHERE role_id = $1"
213
- await db.execute_secured_query(sql_delete, role_id, fetch_method='execute')
214
-
215
- # SQL Query Explanation:
216
- # Inserts a new row for each permission_id passed into the
217
- # `role_permissions` table.
218
- if permission_ids:
219
- sql_insert = "INSERT INTO role_permissions (role_id, permission_id) VALUES ($1, $2)"
220
- for permission_id in permission_ids:
221
- await db.execute_secured_query(
222
- sql_insert,
223
- role_id,
224
- permission_id,
225
- fetch_method='execute'
226
- )
227
- except Exception as e:
228
- # If an error occurs, the underlying foundation will log the issue.
229
- # We re-raise the error here.
230
- raise Exception(f'Failed to update role permissions: {e}')
231
-
232
- async def get_role_permissions(self, role_id: int) -> List[Dict[str, Any]]:
233
- """Returns all permissions for a role."""
234
- # SQL Query Explanation:
235
- # Selects the details (id, name, description) of all permissions
236
- # linked to the specified role.
237
- sql = """
238
- SELECT p.id, p.name, p.description
239
- FROM role_permissions rp
240
- JOIN user_permissions p ON rp.permission_id = p.id
241
- WHERE rp.role_id = $1
242
- ORDER BY p.name
243
- """
244
- try:
245
- return await db.execute_secured_query(sql, role_id)
246
- except Exception as e:
247
- raise Exception(f'Failed to get role permissions: {e}')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fundaments/config_handler.py DELETED
@@ -1,115 +0,0 @@
1
- # PyFundaments: A Secure Python Architecture
2
- # Copyright 2008-2025 - Volkan Kücükbudak
3
- # Apache License V. 2
4
- # Repo: https://github.com/VolkanSah/PyFundaments
5
- # fundaments/config_handler.py
6
- # This module loads environment variables without validation.
7
- # Validation is handled by main.py based on required services.
8
- import os
9
- import sys
10
- from dotenv import load_dotenv
11
- from typing import Optional, Dict, Any
12
-
13
- class ConfigHandler:
14
- """
15
- A universal configuration loader that reads all environment variables
16
- without imposing requirements. This ensures the config handler never
17
- needs updates regardless of what services are used.
18
-
19
- Validation is delegated to main.py which knows what services are needed.
20
- """
21
-
22
- def __init__(self):
23
- """
24
- Loads all environment variables from .env file and system environment.
25
- No validation is performed - that's main.py's responsibility.
26
- """
27
- load_dotenv()
28
- self.config = {}
29
- self.load_all_config()
30
-
31
- def load_all_config(self):
32
- """
33
- Loads all available environment variables into the config dictionary.
34
- No validation - main.py decides what's required based on enabled services.
35
- """
36
- # Load all environment variables
37
- for key, value in os.environ.items():
38
- if value: # Only store non-empty values
39
- self.config[key] = value
40
-
41
- def get(self, key: str) -> Optional[str]:
42
- """
43
- Retrieves a configuration value by key.
44
- Returns None if the key doesn't exist.
45
-
46
- Args:
47
- key: The environment variable name
48
-
49
- Returns:
50
- The value as string or None if not found
51
- """
52
- return self.config.get(key)
53
-
54
- def get_bool(self, key: str, default: bool = False) -> bool:
55
- """
56
- Retrieves a boolean configuration value.
57
- Recognizes: true, false, 1, 0, yes, no (case insensitive)
58
-
59
- Args:
60
- key: The environment variable name
61
- default: Default value if key not found
62
-
63
- Returns:
64
- Boolean value
65
- """
66
- value = self.get(key)
67
- if value is None:
68
- return default
69
-
70
- return value.lower() in ('true', '1', 'yes', 'on')
71
-
72
- def get_int(self, key: str, default: int = 0) -> int:
73
- """
74
- Retrieves an integer configuration value.
75
-
76
- Args:
77
- key: The environment variable name
78
- default: Default value if key not found or invalid
79
-
80
- Returns:
81
- Integer value
82
- """
83
- value = self.get(key)
84
- if value is None:
85
- return default
86
-
87
- try:
88
- return int(value)
89
- except ValueError:
90
- return default
91
-
92
- def has(self, key: str) -> bool:
93
- """
94
- Checks if a configuration key exists and has a non-empty value.
95
-
96
- Args:
97
- key: The environment variable name
98
-
99
- Returns:
100
- True if key exists and has value, False otherwise
101
- """
102
- return key in self.config and bool(self.config[key])
103
-
104
- def get_all(self) -> Dict[str, str]:
105
- """
106
- Returns all loaded configuration as a dictionary.
107
- Useful for debugging or passing to other services.
108
-
109
- Returns:
110
- Dictionary of all loaded environment variables
111
- """
112
- return self.config.copy()
113
-
114
- # Global singleton instance
115
- config_service = ConfigHandler()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fundaments/debug.py DELETED
@@ -1,91 +0,0 @@
1
- import os
2
- import sys
3
- import importlib.util
4
- import datetime
5
- import logging
6
- from logging.handlers import RotatingFileHandler
7
-
8
- class PyFundamentsDebug:
9
- """
10
- Debug-Klasse für PyFundaments.
11
- Liest ENV-Variablen und konfiguriert Logging.
12
- Gibt Startup-Infos aus, wenn PYFUNDAMENTS_DEBUG=true.
13
- """
14
-
15
- def __init__(self):
16
- # Debug aktivieren mit ENV VAR (default: False)
17
- self.enabled = os.getenv("PYFUNDAMENTS_DEBUG", "false").lower() == "true"
18
-
19
- # Log-Level aus ENV lesen, default INFO
20
- log_level_str = os.getenv("LOG_LEVEL", "INFO").upper()
21
- self.log_level = getattr(logging, log_level_str, logging.INFO)
22
-
23
- # Logs in /tmp oder stdout? (default False)
24
- self.log_to_tmp = os.getenv("LOG_TO_TMP", "false").lower() == "true"
25
-
26
- # Öffentliches Logging an/aus (default True)
27
- self.enable_public_logs = os.getenv("ENABLE_PUBLIC_LOGS", "true").lower() == "true"
28
-
29
- # Logger Setup
30
- self.logger = logging.getLogger('pyfundaments_debug')
31
- self._setup_logger()
32
-
33
- def _setup_logger(self):
34
- if not self.enable_public_logs:
35
- # Nur kritische Fehler im Log, wenn deaktiviert
36
- logging.basicConfig(level=logging.CRITICAL)
37
- return
38
-
39
- handlers = []
40
- if self.log_to_tmp:
41
- log_file = '/tmp/pyfundaments_debug.log'
42
- file_handler = RotatingFileHandler(log_file, maxBytes=1024*1024, backupCount=3)
43
- handlers.append(file_handler)
44
- handlers.append(logging.StreamHandler(sys.stdout))
45
-
46
- logging.basicConfig(
47
- level=self.log_level,
48
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
49
- handlers=handlers
50
- )
51
-
52
- def run(self):
53
- if not self.enabled:
54
- return
55
-
56
- self.logger.info(f"==== PYFUNDAMENTS DEBUG STARTUP ({datetime.datetime.now()}) ====")
57
- self.logger.info(f"Python version: {sys.version}")
58
- self.logger.info(f"CWD: {os.getcwd()}")
59
- self.logger.info(f"sys.path: {sys.path}")
60
-
61
- fund_dir = "fundaments"
62
- self.logger.info(f"fundaments exists: {os.path.isdir(fund_dir)}")
63
-
64
- required_files = [
65
- "__init__.py",
66
- "access_control.py",
67
- "postgresql.py",
68
- "config_handler.py",
69
- "security.py",
70
- "user_handler.py",
71
- "encryption.py"
72
- ]
73
-
74
- for file in required_files:
75
- path = os.path.join(fund_dir, file)
76
- exists = os.path.isfile(path)
77
- readable = os.access(path, os.R_OK)
78
- self.logger.info(f"{file} exists: {exists} | readable: {readable}")
79
-
80
- if os.path.isdir(fund_dir):
81
- self.logger.info(f"Listing fundaments contents: {os.listdir(fund_dir)}")
82
- else:
83
- self.logger.warning("fundaments folder not found.")
84
-
85
- spec = importlib.util.find_spec("fundaments")
86
- self.logger.info(f"fundaments importable: {spec is not None}")
87
-
88
- conflicts = [mod for mod in sys.modules if mod == "fundaments"]
89
- self.logger.info(f"Name conflict in sys.modules: {conflicts}")
90
-
91
- self.logger.info("==== PYFUNDAMENTS DEBUG END ====")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fundaments/encryption.py DELETED
@@ -1,233 +0,0 @@
1
- # PyFundaments: A Secure Python Architecture
2
- # Copyright 2008-2025 - Volkan Kücükbudak
3
- # Apache License V. 2
4
- # Repo: https://github.com/VolkanSah/PyFundaments
5
- # encryption.py
6
- # A secure and robust encryption module using the cryptography library.
7
- # This module is designed as a core component for a CMS architecture.
8
-
9
- import os
10
- import sys
11
- import base64
12
- import binascii
13
- from typing import Dict, Union, Optional
14
-
15
- # IMPORTANT: The cryptography library is required for this module.
16
- # Please install it with 'pip install cryptography'.
17
- try:
18
- from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
19
- from cryptography.hazmat.primitives import hashes
20
- from cryptography.hazmat.backends import default_backend
21
- from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
22
- from cryptography.exceptions import InvalidTag
23
- except ImportError:
24
- print("Error: The 'cryptography' library is required. Please install it with 'pip install cryptography'.")
25
- sys.exit(1)
26
-
27
- class Encryption:
28
- """
29
- A class for symmetric encryption and decryption using AES-256-GCM.
30
- It securely handles both string data and file streaming.
31
-
32
- This version is designed as a reusable core component for a larger application.
33
- """
34
- CIPHER_NAME = 'AES-256-GCM'
35
- KEY_LENGTH = 32 # 256 bits
36
- NONCE_LENGTH = 12 # 96 bits, standard for GCM
37
- TAG_LENGTH = 16 # 128 bits
38
- SALT_LENGTH = 16
39
-
40
- @staticmethod
41
- def generate_salt() -> str:
42
- """
43
- Generates a new, cryptographically secure random salt for key derivation.
44
- This should be done once during application setup and stored securely.
45
-
46
- Returns:
47
- A hex-encoded string of the salt.
48
- """
49
- return binascii.hexlify(os.urandom(Encryption.SALT_LENGTH)).decode('utf-8')
50
-
51
- def __init__(self, master_key: str, salt: str):
52
- """
53
- Initializes the encryption class by deriving a secure key from a master key.
54
- The provided master_key and a persistent salt are used for key derivation.
55
-
56
- Args:
57
- master_key: The string to be used as the master key.
58
- salt: The hex-encoded string of the persistent salt.
59
-
60
- Raises:
61
- ValueError: If the provided salt is not a valid hex string or has an incorrect length.
62
- """
63
- try:
64
- salt_bytes = binascii.unhexlify(salt)
65
- except binascii.Error:
66
- raise ValueError("Invalid salt format. Must be a hex-encoded string.")
67
-
68
- if len(salt_bytes) != self.SALT_LENGTH:
69
- raise ValueError(f"Invalid salt length. Expected {self.SALT_LENGTH} bytes, got {len(salt_bytes)}.")
70
-
71
- kdf = PBKDF2HMAC(
72
- algorithm=hashes.SHA256(),
73
- length=self.KEY_LENGTH,
74
- salt=salt_bytes,
75
- iterations=480000, # Recommended value for 2023+
76
- backend=default_backend()
77
- )
78
- self.key = kdf.derive(master_key.encode('utf-8'))
79
-
80
- def encrypt(self, data: str) -> Dict[str, str]:
81
- """
82
- Encrypts a string using AES-256-GCM.
83
-
84
- Args:
85
- data: The string to be encrypted.
86
-
87
- Returns:
88
- A dictionary containing the base64-encoded ciphertext, hex-encoded IV/nonce,
89
- and hex-encoded authentication tag.
90
- """
91
- nonce = os.urandom(self.NONCE_LENGTH)
92
-
93
- aesgcm = Cipher(
94
- algorithms.AES(self.key),
95
- modes.GCM(nonce),
96
- backend=default_backend()
97
- ).encryptor()
98
-
99
- encrypted_data = aesgcm.update(data.encode('utf-8')) + aesgcm.finalize()
100
- tag = aesgcm.tag
101
-
102
- return {
103
- 'data': base64.b64encode(encrypted_data).decode('utf-8'),
104
- 'nonce': binascii.hexlify(nonce).decode('utf-8'),
105
- 'tag': binascii.hexlify(tag).decode('utf-8')
106
- }
107
-
108
- def decrypt(self, encrypted_data: str, nonce: str, tag: str) -> str:
109
- """
110
- Decrypts an AES-256-GCM encrypted string.
111
-
112
- Args:
113
- encrypted_data: The base64-encoded ciphertext.
114
- nonce: The hex-encoded nonce/IV.
115
- tag: The hex-encoded authentication tag.
116
-
117
- Returns:
118
- The decrypted plaintext string.
119
-
120
- Raises:
121
- ValueError: If nonce, tag, or data format is invalid.
122
- InvalidTag: If the authentication tag fails validation.
123
- """
124
- try:
125
- nonce_bytes = binascii.unhexlify(nonce)
126
- tag_bytes = binascii.unhexlify(tag)
127
- cipher_bytes = base64.b64decode(encrypted_data)
128
- except (binascii.Error, ValueError) as e:
129
- raise ValueError(f'Invalid data format: {e}')
130
-
131
- aesgcm = Cipher(
132
- algorithms.AES(self.key),
133
- modes.GCM(nonce_bytes, tag_bytes),
134
- backend=default_backend()
135
- ).decryptor()
136
-
137
- try:
138
- decrypted_data = aesgcm.update(cipher_bytes) + aesgcm.finalize()
139
- return decrypted_data.decode('utf-8')
140
- except InvalidTag:
141
- raise InvalidTag("Authentication tag validation failed. Data may be corrupted or key is incorrect.")
142
-
143
- def encrypt_file(self, source_path: str, destination_path: str) -> Dict[str, str]:
144
- """
145
- Encrypts a file using AES-256-GCM with a streaming approach.
146
-
147
- Args:
148
- source_path: Path to the file to be encrypted.
149
- destination_path: Path where the encrypted file will be saved.
150
-
151
- Returns:
152
- A dictionary containing the hex-encoded IV/nonce and authentication tag.
153
- """
154
- nonce = os.urandom(self.NONCE_LENGTH)
155
-
156
- encryptor = Cipher(
157
- algorithms.AES(self.key),
158
- modes.GCM(nonce),
159
- backend=default_backend()
160
- ).encryptor()
161
-
162
- try:
163
- with open(source_path, 'rb') as fp_source, open(destination_path, 'wb') as fp_dest:
164
- fp_dest.write(nonce)
165
-
166
- chunk_size = 8192
167
- while True:
168
- chunk = fp_source.read(chunk_size)
169
- if not chunk:
170
- break
171
- encrypted_chunk = encryptor.update(chunk)
172
- fp_dest.write(encrypted_chunk)
173
-
174
- encryptor.finalize()
175
- tag = encryptor.tag
176
- fp_dest.write(tag)
177
-
178
- return {
179
- 'nonce': binascii.hexlify(nonce).decode('utf-8'),
180
- 'tag': binascii.hexlify(tag).decode('utf-8')
181
- }
182
- except FileNotFoundError as e:
183
- raise ValueError(f"File not found: {e.filename}") from e
184
- except Exception as e:
185
- raise IOError(f"File encryption failed: {e}") from e
186
-
187
- def decrypt_file(self, source_path: str, destination_path: str) -> None:
188
- """
189
- Decrypts an AES-256-GCM encrypted file.
190
-
191
- Args:
192
- source_path: Path to the encrypted file.
193
- destination_path: Path where the decrypted file will be saved.
194
- """
195
- try:
196
- with open(source_path, 'rb') as fp_source, open(destination_path, 'wb') as fp_dest:
197
- nonce = fp_source.read(self.NONCE_LENGTH)
198
- if len(nonce) != self.NONCE_LENGTH:
199
- raise ValueError("Incomplete or invalid file format: Nonce is missing.")
200
-
201
- fp_source.seek(-self.TAG_LENGTH, os.SEEK_END)
202
- tag = fp_source.read(self.TAG_LENGTH)
203
- if len(tag) != self.TAG_LENGTH:
204
- raise ValueError("Incomplete or invalid file format: Tag is missing.")
205
-
206
- fp_source.seek(self.NONCE_LENGTH, os.SEEK_SET) # Rewind to the start of the ciphertext
207
-
208
- decryptor = Cipher(
209
- algorithms.AES(self.key),
210
- modes.GCM(nonce, tag),
211
- backend=default_backend()
212
- ).decryptor()
213
-
214
- chunk_size = 8192
215
- encrypted_file_size = os.path.getsize(source_path) - self.NONCE_LENGTH - self.TAG_LENGTH
216
-
217
- bytes_read = 0
218
- while bytes_read < encrypted_file_size:
219
- chunk_to_read = min(chunk_size, encrypted_file_size - bytes_read)
220
- chunk = fp_source.read(chunk_to_read)
221
-
222
- decrypted_chunk = decryptor.update(chunk)
223
- fp_dest.write(decrypted_chunk)
224
- bytes_read += len(chunk)
225
-
226
- decryptor.finalize()
227
-
228
- except InvalidTag as e:
229
- raise IOError(f"File decryption failed. The authentication tag is invalid, suggesting the file was corrupted or tampered with. Error: {e}") from e
230
- except FileNotFoundError as e:
231
- raise ValueError(f"File not found: {e.filename}") from e
232
- except Exception as e:
233
- raise IOError(f"File decryption failed due to an unexpected error: {e}") from e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fundaments/postgresql.py DELETED
@@ -1,179 +0,0 @@
1
- # PyFundaments: A Secure Python Architecture
2
- # Copyright 2008-2025 - Volkan Kücükbudak
3
- # Apache License V. 2
4
- # Repo: https://github.com/VolkanSah/PyFundaments
5
- # fundaments/postgresql.py
6
- import os
7
- import logging
8
- import asyncpg
9
- import ssl
10
- from urllib.parse import urlparse, urlencode, parse_qs, urlunparse
11
- from typing import Optional
12
-
13
- logging.basicConfig(
14
- level=logging.INFO,
15
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
16
- )
17
- logger = logging.getLogger(__name__)
18
-
19
- _db_pool: Optional[asyncpg.Pool] = None
20
-
21
- def enforce_cloud_security(dsn_url: str) -> str:
22
- """
23
- Enforces security settings for cloud environments.
24
- - Ensures SSL mode is at least 'require'
25
- - Removes unsupported options for cloud providers (e.g. statement_timeout for Neon)
26
- - Sets connect_timeout and keepalives_idle defaults
27
- """
28
- parsed = urlparse(dsn_url)
29
- query_params = parse_qs(parsed.query)
30
-
31
- # Enforce SSL (at least 'require')
32
- sslmode = query_params.get('sslmode', ['prefer'])[0].lower()
33
- if sslmode not in ['require', 'verify-ca', 'verify-full']:
34
- query_params['sslmode'] = ['require']
35
-
36
- # Set timeouts and keep-alives if not present
37
- if 'connect_timeout' not in query_params:
38
- query_params['connect_timeout'] = ['5']
39
- if 'keepalives_idle' not in query_params:
40
- query_params['keepalives_idle'] = ['60']
41
-
42
- # Remove statement_timeout option for Neon
43
- if 'neon.tech' in parsed.netloc:
44
- if 'options' in query_params:
45
- options_clean = []
46
- for opt in query_params['options']:
47
- if 'statement_timeout' not in opt:
48
- options_clean.append(opt)
49
- if options_clean:
50
- query_params['options'] = options_clean
51
- else:
52
- query_params.pop('options')
53
- logger.info("Removed unsupported 'statement_timeout' option for Neon.tech.")
54
- # Optionally, set a supported option for Neon (usually none)
55
-
56
- # TODO: Extend here for further providers...
57
-
58
- # Rebuild DSN
59
- new_query = urlencode(query_params, doseq=True)
60
- new_url = parsed._replace(query=new_query)
61
- return urlunparse(new_url)
62
-
63
- def mask_dsn(dsn_url: str) -> str:
64
- """
65
- Masks username/password from DSN so they are not exposed in logs.
66
- """
67
- parsed = urlparse(dsn_url)
68
- safe_netloc = f"{parsed.hostname}:{parsed.port}" if parsed.port else parsed.hostname
69
- return parsed._replace(netloc=safe_netloc).geturl()
70
-
71
- async def ssl_runtime_check(conn: asyncpg.Connection):
72
- """
73
- Performs a cloud-aware SSL runtime check on an active connection.
74
- For Neon/Supabase (or unknown cloud) only log a warning if pg_stat_ssl is unavailable.
75
- """
76
- dsn = os.getenv("DATABASE_URL", "")
77
- try:
78
- ssl_status = await conn.fetchval("""
79
- SELECT CASE WHEN ssl THEN 'active' ELSE 'INACTIVE' END
80
- FROM pg_stat_ssl WHERE pid = pg_backend_pid()
81
- """)
82
- if ssl_status != 'active':
83
- logger.critical("CRITICAL ERROR: SSL connection is not active!")
84
- raise RuntimeError("SSL connection failed")
85
- logger.info("SSL connection is active.")
86
- except Exception as e:
87
- # Cloud: If pg_stat_ssl is not available, don't fail hard.
88
- if "neon.tech" in dsn or "supabase" in dsn:
89
- logger.warning("SSL check via pg_stat_ssl not possible (cloud restriction). Assuming SSL is active due to sslmode=require.")
90
- else:
91
- logger.critical(f"SSL runtime check failed: {e}")
92
- raise
93
-
94
- async def init_db_pool(dsn_url: Optional[str] = None) -> Optional[asyncpg.Pool]:
95
- """Initializes the asynchronous database connection pool."""
96
- global _db_pool
97
- if _db_pool:
98
- return _db_pool
99
-
100
- if not dsn_url:
101
- dsn_url = os.getenv("DATABASE_URL") or os.getenv("PG_DSN")
102
- if not dsn_url:
103
- logger.warning("No DATABASE_URL or PG_DSN found. Skipping DB pool initialization.")
104
- return None
105
-
106
- # Enforce cloud security and remove unsupported options
107
- secured_dsn = enforce_cloud_security(dsn_url)
108
-
109
- # ⚠ WARNING: This logs full credentials — keep only for secure DEV debugging
110
- logger.debug(f"[DEV ONLY] Full DSN used for DB connection: {secured_dsn}")
111
-
112
- # Always log a masked DSN for production safety
113
- logger.info(f"DSN used for DB connection (masked): {mask_dsn(secured_dsn)}")
114
-
115
- ssl_context = None
116
- if 'sslmode=verify-full' in secured_dsn:
117
- ssl_context = ssl.create_default_context()
118
-
119
- try:
120
- logger.info("Initializing secure database pool...")
121
- _db_pool = await asyncpg.create_pool(
122
- dsn=secured_dsn,
123
- min_size=1,
124
- max_size=10,
125
- timeout=5,
126
- command_timeout=30,
127
- ssl=ssl_context
128
- )
129
- # Post-init checks
130
- async with _db_pool.acquire() as conn:
131
- await ssl_runtime_check(conn)
132
- logger.info("Secure database pool initialized.")
133
- return _db_pool
134
- except Exception as e:
135
- logger.critical(f"Pool initialization failed: {str(e)}")
136
- _db_pool = None
137
- return None # Fallback: allow app to run without DB
138
-
139
- async def close_db_pool():
140
- """Gracefully closes the database connection pool."""
141
- global _db_pool
142
- if _db_pool:
143
- await _db_pool.close()
144
- _db_pool = None
145
- logger.info("Database pool closed successfully.")
146
-
147
- async def execute_secured_query(query: str, *params, fetch_method='fetch'):
148
- """
149
- Executes a parameterized query with integrated security checks.
150
- """
151
- global _db_pool
152
- if not _db_pool:
153
- raise RuntimeError("Database pool not initialized")
154
-
155
- try:
156
- async with _db_pool.acquire() as conn:
157
- if fetch_method == 'fetch':
158
- return await conn.fetch(query, *params)
159
- elif fetch_method == 'fetchrow':
160
- return await conn.fetchrow(query, *params)
161
- elif fetch_method == 'execute':
162
- return await conn.execute(query, *params)
163
- else:
164
- raise ValueError("Invalid fetch_method")
165
- except asyncpg.PostgresError as e:
166
- error_type = "Security violation" if getattr(e, 'sqlstate', None) == '42501' else "Database error"
167
-
168
- if os.getenv('APP_ENV') == 'production':
169
- logger.error(f"{error_type} [Code: {getattr(e, 'sqlstate', '?')}]")
170
- else:
171
- logger.error(f"{error_type}: {e}")
172
-
173
- # Neon: Reconnect if connection terminated (optional)
174
- if getattr(e, 'sqlstate', None) == '08006' and 'neon.tech' in (os.getenv("DATABASE_URL") or ''):
175
- logger.warning("Neon.tech connection terminated. Restarting pool...")
176
- await close_db_pool()
177
- await init_db_pool(os.getenv("DATABASE_URL"))
178
-
179
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fundaments/security.py DELETED
@@ -1,82 +0,0 @@
1
- # PyFundaments: A Secure Python Architecture
2
- # Copyright 2008-2025 - Volkan Kücükbudak
3
- # Apache License V. 2
4
- # Repo: https://github.com/VolkanSah/PyFundaments
5
- # fundaments/security.py
6
- # A central security manager that orchestrates core security functions.
7
- # This class acts as a single, trusted interface for the application to
8
- # interact with all underlying security fundamentals.
9
-
10
- import logging
11
- from typing import Dict, Any, Optional
12
-
13
- # VORHER: Diese direkten Imports sind überflüssig,
14
- # da die Instanzen der Klassen über den 'services'-Dictionary
15
- # im __init__-Konstruktor übergeben werden.
16
- # Sie sind auch nicht für die Typisierung notwendig,
17
- # da wir 'Optional[ClassName]' verwenden, was ausreicht.
18
- # from fundaments.encryption import Encryption
19
- # from fundaments.access_control import AccessControl
20
- # from fundaments.postgresql import execute_secured_query
21
- # from fundaments.user_handler import UserHandler
22
-
23
- logger = logging.getLogger('security')
24
-
25
- class Security:
26
- def __init__(self, services: Dict[str, Any]):
27
- # VORHER: Hier werden die Instanzen aus dem übergebenen Dictionary entnommen.
28
- self.user_handler: Optional[UserHandler] = services.get("user_handler")
29
- self.access_control: Optional[AccessControl] = services.get("access_control")
30
- self.encryption: Optional[Encryption] = services.get("encryption")
31
-
32
- # VORHER: Bei fehlenden kritischen Diensten wird die Anwendung sofort gestoppt.
33
- # Dies ist eine strikte, aber unflexible Regel.
34
- if not self.user_handler:
35
- logger.critical("Security manager init failed: UserHandler service missing.")
36
- raise RuntimeError("UserHandler service missing")
37
-
38
- if not self.access_control:
39
- logger.critical("Security manager init failed: AccessControl service missing.")
40
- raise RuntimeError("AccessControl service missing")
41
-
42
- # VORHER: Bei einem nicht-kritischen Dienst wird nur eine Warnung ausgegeben.
43
- # Die Anwendung läuft weiter.
44
- if not self.encryption:
45
- logger.warning("Encryption service not available. Encryption/decryption features will be disabled.")
46
-
47
- logger.info("Security manager initialized and ready.")
48
-
49
- # VORHER: Hier fehlt die Überprüfung, ob 'self.user_handler' None ist.
50
- # Wenn der Dienst nicht initialisiert wurde (wie oben), würde dies einen AttributeError auslösen.
51
- async def user_login(self, username: str, password: str, request_data: dict) -> bool:
52
- logger.info(f"Attempting login for user: {username}")
53
- # UserHandler.login() is synchronous (SQLite) — no await.
54
- # The old 'await' raised TypeError: bool can't be awaited.
55
- if self.user_handler.login(username, password, request_data):
56
- return self.user_handler.validate_session(request_data)
57
- return False
58
-
59
- # VORHER: Hier fehlt die Überprüfung, ob 'self.access_control' None ist.
60
- async def check_permission(self, user_id: int, permission_name: str) -> bool:
61
- """Checks permission for ANY user_id (not just the constructor one)."""
62
- logger.debug(f"Checking permission '{permission_name}' for user ID {user_id}")
63
- return await self.access_control.has_permission(permission_name, user_id=user_id)
64
-
65
- # VORHER: Hier wird geprüft, ob 'self.encryption' None ist, was korrekt ist.
66
- def encrypt_data(self, data: str) -> Dict[str, str]:
67
- if not self.encryption:
68
- raise RuntimeError("Encryption service not initialized.")
69
- logger.debug("Encrypting data.")
70
- return self.encryption.encrypt(data)
71
-
72
- # VORHER: Hier wird geprüft, ob 'self.encryption' None ist, was korrekt ist.
73
- def decrypt_data(self, encrypted_data: str, nonce: str, tag: str) -> Optional[str]:
74
- if not self.encryption:
75
- logger.error("Encryption service not initialized. Cannot decrypt data.")
76
- return None
77
- logger.debug("Decrypting data.")
78
- try:
79
- return self.encryption.decrypt(encrypted_data, nonce, tag)
80
- except Exception as e:
81
- logger.error(f"Decryption failed: {e}")
82
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fundaments/user_handler.py DELETED
@@ -1,370 +0,0 @@
1
- # PyFundaments: A Secure Python Architecture
2
- # Copyright 2008-2025 - Volkan Kücükbudak
3
- # Apache License V. 2
4
- # Repo: https://github.com/VolkanSah/PyFundaments
5
- # root/fundaments/user_handler.py
6
- # A Python module for handling user authentication and session management.
7
-
8
- import sqlite3
9
- import uuid
10
- from datetime import datetime, timedelta
11
- from passlib.hash import pbkdf2_sha256
12
- import os
13
-
14
-
15
- class Database:
16
- """
17
- Handles the SQLite database connection and initialization.
18
- Supports dynamic path selection via environment variables with a
19
- fallback to the local application directory.
20
- """
21
- def __init__(self, db_name="cms_database.db"):
22
- # 1. Attempt to load the database path from an environment variable
23
- # This allows for flexible configuration in production/Docker environments
24
- env_path = os.getenv("SQLITE_PATH")
25
-
26
- if env_path:
27
- # Use the absolute path provided by the environment variable
28
- full_db_path = os.path.abspath(env_path)
29
- else:
30
- # Fallback logic: Locate the 'app' directory relative to this script
31
- # Expected structure: root/fun/user_handler.py -> root/app/
32
- base_path = os.path.dirname(os.path.abspath(__file__))
33
- app_dir = os.path.join(base_path, "..", "app")
34
- full_db_path = os.path.join(app_dir, db_name)
35
-
36
- # 2. Ensure the target directory exists before attempting to connect
37
- # SQLite can create the file, but not the parent folders.
38
- db_dir = os.path.dirname(full_db_path)
39
- if db_dir and not os.path.exists(db_dir):
40
- os.makedirs(db_dir)
41
-
42
- # Initialize the connection and cursor
43
- self.conn = sqlite3.connect(full_db_path)
44
- self.cursor = self.conn.cursor()
45
-
46
- # Log the active database path for debugging purposes
47
- print(f"Database connected to: {full_db_path}")
48
-
49
- def execute(self, query, params=None):
50
- if params is None:
51
- params = []
52
- self.cursor.execute(query, params)
53
- self.conn.commit()
54
-
55
- def fetchone(self, query, params=None):
56
- if params is None:
57
- params = []
58
- self.cursor.execute(query, params)
59
- return self.cursor.fetchone()
60
-
61
- def fetchall(self, query, params=None):
62
- if params is None:
63
- params = []
64
- self.cursor.execute(query, params)
65
- return self.cursor.fetchall()
66
-
67
- def close(self):
68
- self.conn.close()
69
-
70
- def setup_tables(self):
71
- """
72
- Creates the necessary tables for users and sessions.
73
- """
74
- self.execute("""
75
- CREATE TABLE IF NOT EXISTS users (
76
- id INTEGER PRIMARY KEY AUTOINCREMENT,
77
- username TEXT UNIQUE NOT NULL,
78
- password TEXT NOT NULL,
79
- is_admin INTEGER NOT NULL DEFAULT 0,
80
- account_locked INTEGER NOT NULL DEFAULT 0,
81
- failed_login_attempts INTEGER NOT NULL DEFAULT 0
82
- )
83
- """)
84
- self.execute("""
85
- CREATE TABLE IF NOT EXISTS sessions (
86
- id TEXT PRIMARY KEY,
87
- user_id INTEGER NOT NULL,
88
- ip_address TEXT,
89
- user_agent TEXT,
90
- last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
91
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
92
- )
93
- """)
94
-
95
- class Security:
96
- """
97
- Handles secure password hashing and session regeneration.
98
- Using passlib for robust and secure password management.
99
- """
100
- @staticmethod
101
- def hash_password(password: str) -> str:
102
- """Hashes a password using PBKDF2 with SHA256."""
103
- return pbkdf2_sha256.hash(password)
104
-
105
- @staticmethod
106
- def verify_password(password: str, hashed_password: str) -> bool:
107
- """Verifies a password against a stored hash."""
108
- return pbkdf2_sha256.verify(password, hashed_password)
109
-
110
- @staticmethod
111
- def regenerate_session(session_id: str):
112
- """
113
- Simulates regenerating a session ID to prevent session fixation.
114
- In a real web framework, this would be a framework-specific function.
115
- """
116
- print(f"Session regenerated. Old ID: {session_id}")
117
- new_session_id = str(uuid.uuid4())
118
- print(f"New ID: {new_session_id}")
119
- return new_session_id
120
-
121
- class UserHandler:
122
- """
123
- Handles user login, logout, and session validation.
124
- This class mirrors the logic from the user's PHP User class.
125
- """
126
- def __init__(self, db: Database):
127
- self.db = db
128
- # A simple in-memory session store for this example
129
- self._session = {}
130
-
131
- def login(self, username: str, password: str, request_data: dict) -> bool:
132
- """
133
- Logs in the user by verifying credentials and storing a new session.
134
- :param username: The user's username.
135
- :param password: The user's plain-text password.
136
- :param request_data: A dictionary containing 'ip_address' and 'user_agent'.
137
- :return: True if login is successful, False otherwise.
138
- """
139
- try:
140
- # Step 1: Find the user in the database
141
- user_data = self.db.fetchone("SELECT id, username, password, is_admin, account_locked, failed_login_attempts FROM users WHERE username = ?", (username,))
142
- if user_data is None:
143
- print(f"Login failed: Username '{username}' not found.")
144
- return False
145
-
146
- user = {
147
- 'id': user_data[0],
148
- 'username': user_data[1],
149
- 'password': user_data[2],
150
- 'is_admin': user_data[3],
151
- 'account_locked': user_data[4],
152
- 'failed_login_attempts': user_data[5]
153
- }
154
-
155
- # Check if account is locked
156
- if user['account_locked'] == 1:
157
- print(f"Login failed: Account for '{username}' is locked.")
158
- return False
159
-
160
- # Step 2: Verify the password
161
- if Security.verify_password(password, user['password']):
162
- print(f"Login successful for user: '{username}'")
163
-
164
- # Reset failed login attempts on success
165
- self.reset_failed_attempts(username)
166
-
167
- # Step 3: Create a new session record in the database
168
- session_id = str(uuid.uuid4())
169
- ip_address = request_data.get('ip_address', 'unknown')
170
- user_agent = request_data.get('user_agent', 'unknown')
171
-
172
- self.db.execute(
173
- "INSERT INTO sessions (id, user_id, ip_address, user_agent) VALUES (?, ?, ?, ?)",
174
- (session_id, user['id'], ip_address, user_agent)
175
- )
176
-
177
- # Step 4: Store session data in the in-memory session (or a session store)
178
- self._session = {
179
- 'session_id': session_id,
180
- 'user_id': user['id'],
181
- 'username': user['username'],
182
- 'is_admin': user['is_admin']
183
- }
184
-
185
- # Security: Regenerate session ID
186
- self._session['session_id'] = Security.regenerate_session(session_id)
187
- return True
188
- else:
189
- print(f"Login failed: Incorrect password for user '{username}'.")
190
- # Increment failed login attempts
191
- self.increment_failed_attempts(username)
192
- return False
193
-
194
- except sqlite3.Error as e:
195
- print(f"Database error during login: {e}")
196
- return False
197
-
198
- def logout(self) -> bool:
199
- """
200
- Logs out the current user by deleting the session from the database.
201
- :return: True if logout is successful, False otherwise.
202
- """
203
- if 'user_id' not in self._session:
204
- print("No active session to log out.")
205
- return False
206
-
207
- try:
208
- # Step 1: Delete the session from the database
209
- self.db.execute("DELETE FROM sessions WHERE user_id = ?", (self._session['user_id'],))
210
-
211
- # Step 2: Clear the in-memory session data
212
- self._session.clear()
213
- print("User logged out successfully.")
214
- return True
215
- except sqlite3.Error as e:
216
- print(f"Database error during logout: {e}")
217
- return False
218
-
219
- def is_logged_in(self) -> bool:
220
- """
221
- Checks if the current user is logged in.
222
- :return: True if a valid session exists, False otherwise.
223
- """
224
- if 'user_id' not in self._session:
225
- return False
226
-
227
- try:
228
- # Check for the session in the database
229
- session_data = self.db.fetchone(
230
- "SELECT * FROM sessions WHERE id = ? AND user_id = ?",
231
- (self._session['session_id'], self._session['user_id'])
232
- )
233
- return session_data is not None
234
- except sqlite3.Error as e:
235
- print(f"Database error during is_logged_in check: {e}")
236
- return False
237
-
238
- def is_admin(self) -> bool:
239
- """
240
- Checks if the logged-in user is an admin.
241
- :return: True if the user is an admin, False otherwise.
242
- """
243
- return self._session.get('is_admin', 0) == 1
244
-
245
- def validate_session(self, request_data: dict) -> bool:
246
- """
247
- Validates the current session against IP address and user agent.
248
- :param request_data: A dictionary containing 'ip_address' and 'user_agent'.
249
- :return: True if the session is valid, False otherwise.
250
- """
251
- if not self.is_logged_in():
252
- return False
253
-
254
- try:
255
- ip_address = request_data.get('ip_address', 'unknown')
256
- user_agent = request_data.get('user_agent', 'unknown')
257
-
258
- session_data = self.db.fetchone(
259
- "SELECT * FROM sessions WHERE id = ? AND user_id = ? AND ip_address = ? AND user_agent = ?",
260
- (self._session['session_id'], self._session['user_id'], ip_address, user_agent)
261
- )
262
- return session_data is not None
263
- except sqlite3.Error as e:
264
- print(f"Database error during session validation: {e}")
265
- return False
266
-
267
- def lock_account(self, username: str):
268
- """
269
- Locks a user account.
270
- :param username: The username of the account to lock.
271
- """
272
- try:
273
- self.db.execute("UPDATE users SET account_locked = 1 WHERE username = ?", (username,))
274
- print(f"Account for '{username}' has been locked.")
275
- except sqlite3.Error as e:
276
- print(f"Database error while locking account: {e}")
277
-
278
- def reset_failed_attempts(self, username: str):
279
- """
280
- Resets failed login attempts for a user.
281
- :param username: The username of the account.
282
- """
283
- try:
284
- self.db.execute("UPDATE users SET failed_login_attempts = 0 WHERE username = ?", (username,))
285
- except sqlite3.Error as e:
286
- print(f"Database error while resetting failed attempts: {e}")
287
-
288
- def increment_failed_attempts(self, username: str):
289
- """
290
- Increments failed login attempts and locks the account if a threshold is met.
291
- :param username: The username of the account.
292
- """
293
- try:
294
- # Get the current failed attempts
295
- user_data = self.db.fetchone("SELECT failed_login_attempts FROM users WHERE username = ?", (username,))
296
- if user_data:
297
- attempts = user_data[0] + 1
298
- self.db.execute(
299
- "UPDATE users SET failed_login_attempts = ? WHERE username = ?",
300
- (attempts, username)
301
- )
302
- print(f"Failed login attempts for '{username}': {attempts}")
303
-
304
- # Check for threshold (e.g., 5 attempts)
305
- if attempts >= 5:
306
- self.lock_account(username)
307
-
308
- except sqlite3.Error as e:
309
- print(f"Database error while incrementing failed attempts: {e}")
310
-
311
- # --- Example Usage ---
312
- if __name__ == "__main__":
313
- db = Database()
314
- db.setup_tables()
315
- user_handler = UserHandler(db)
316
-
317
- # Clean up old test data if it exists
318
- db.execute("DELETE FROM users WHERE username IN (?, ?)", ("testuser", "adminuser"))
319
- db.execute("DELETE FROM sessions")
320
-
321
- # 1. Register a new user and an admin user
322
- hashed_password = Security.hash_password("secure_password_123")
323
- db.execute("INSERT INTO users (username, password) VALUES (?, ?)", ("testuser", hashed_password))
324
- db.execute("INSERT INTO users (username, password, is_admin) VALUES (?, ?, 1)", ("adminuser", hashed_password))
325
-
326
- print("--- Test 1: Successful Login ---")
327
- # Simulate a web request
328
- request_data = {
329
- 'ip_address': '192.168.1.100',
330
- 'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
331
- }
332
-
333
- login_success = user_handler.login("testuser", "secure_password_123", request_data)
334
- print(f"Login attempt status: {login_success}")
335
- print(f"Is user logged in? {user_handler.is_logged_in()}")
336
- print(f"Is user an admin? {user_handler.is_admin()}")
337
- print(f"Is session valid? {user_handler.validate_session(request_data)}")
338
- print("-" * 20)
339
-
340
- # 2. Simulate a logout
341
- print("--- Test 2: Logout ---")
342
- user_handler.logout()
343
- print(f"Is user logged in after logout? {user_handler.is_logged_in()}")
344
- print("-" * 20)
345
-
346
- # 3. Simulate a failed login and account lock
347
- print("--- Test 3: Failed Login and Account Lock ---")
348
- # Log in with the wrong password multiple times
349
- for i in range(6):
350
- user_handler.login("testuser", "wrong_password", request_data)
351
-
352
- # Now, try to log in with the correct password. It should fail because the account is locked.
353
- print("\nAttempting to log in with correct password after lock:")
354
- login_attempt_after_lock = user_handler.login("testuser", "secure_password_123", request_data)
355
- print(f"Login attempt status: {login_attempt_after_lock}")
356
- print("-" * 20)
357
-
358
- # 4. Reset failed attempts for a new login
359
- print("--- Test 4: Resetting failed attempts ---")
360
- user_handler.reset_failed_attempts("testuser")
361
- login_attempt_after_reset = user_handler.login("testuser", "secure_password_123", request_data)
362
- print(f"Login attempt status after reset: {login_attempt_after_reset}")
363
-
364
- db.close()
365
-
366
- # Optional: Clean up the database file after the run
367
- # OLD
368
- # os.remove("cms_database.db")
369
- # NEW : Clean up the database file after the run:
370
- # os.remove(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "app", "cms_database.db"))