Alibrown commited on
Commit
48d0015
·
verified ·
1 Parent(s): 79111f8

Delete fundaments

Browse files
fundaments/__init__.py DELETED
File without changes
fundaments/access_control.py DELETED
@@ -1,240 +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) -> bool:
47
- """
48
- Checks if the user has a specific permission.
49
- Uses the secure execute_secured_query function from the foundation.
50
- """
51
- if self.user_id is None:
52
- return False
53
-
54
- # SQL Query Explanation:
55
- # This query counts the number of rows where the user (user_id)
56
- # has a role (user_role_assignments) that is linked to a permission
57
- # (role_permissions) which has the specified name (user_permissions.name).
58
- # If the count is > 0, the user has the permission.
59
- sql = """
60
- SELECT COUNT(*) AS count
61
- FROM user_role_assignments ura
62
- JOIN role_permissions rp ON ura.role_id = rp.role_id
63
- JOIN user_permissions up ON rp.permission_id = up.id
64
- WHERE ura.user_id = $1 AND up.name = $2
65
- """
66
- try:
67
- result = await db.execute_secured_query(
68
- sql,
69
- self.user_id,
70
- permission_name,
71
- fetch_method='fetchrow'
72
- )
73
- return result['count'] > 0
74
- except Exception as e:
75
- # Error handling is managed by your postgresql module.
76
- # We just re-raise the exception here to propagate it.
77
- raise Exception(f'Failed to check permission: {e}')
78
-
79
- async def get_user_permissions(self) -> List[Dict[str, Any]]:
80
- """Returns all permissions for a user."""
81
- if self.user_id is None:
82
- return []
83
-
84
- # SQL Query Explanation:
85
- # This query retrieves all distinct permission names and descriptions
86
- # associated with the user's roles. `DISTINCT` ensures each permission
87
- # is listed only once.
88
- sql = """
89
- SELECT DISTINCT up.name, up.description
90
- FROM user_role_assignments ura
91
- JOIN role_permissions rp ON ura.role_id = rp.role_id
92
- JOIN user_permissions up ON rp.permission_id = up.id
93
- WHERE ura.user_id = $1
94
- ORDER BY up.name
95
- """
96
- try:
97
- return await db.execute_secured_query(sql, self.user_id)
98
- except Exception as e:
99
- raise Exception(f'Failed to get user permissions: {e}')
100
-
101
- async def get_user_roles(self) -> List[Dict[str, Any]]:
102
- """Returns all roles for a user."""
103
- if self.user_id is None:
104
- return []
105
-
106
- # SQL Query Explanation:
107
- # This query selects the details (id, name, description) of the roles
108
- # that are assigned to the specified user (user_id) in the
109
- # `user_role_assignments` table.
110
- sql = """
111
- SELECT r.id, r.name, r.description
112
- FROM user_role_assignments ura
113
- JOIN user_roles r ON ura.role_id = r.id
114
- WHERE ura.user_id = $1
115
- ORDER BY r.name
116
- """
117
- try:
118
- return await db.execute_secured_query(sql, self.user_id)
119
- except Exception as e:
120
- raise Exception(f'Failed to get user roles: {e}')
121
-
122
- async def assign_role(self, role_id: int) -> None:
123
- """Assigns a role to a user."""
124
- if self.user_id is None:
125
- raise Exception('No user specified')
126
-
127
- # SQL Query Explanation:
128
- # Inserts a new row into the `user_role_assignments` table to create
129
- # the relationship between a user and a role.
130
- sql = "INSERT INTO user_role_assignments (user_id, role_id) VALUES ($1, $2)"
131
- try:
132
- await db.execute_secured_query(
133
- sql,
134
- self.user_id,
135
- role_id,
136
- fetch_method='execute'
137
- )
138
- except Exception as e:
139
- raise Exception(f'Failed to assign role: {e}')
140
-
141
- async def remove_role(self, role_id: int) -> None:
142
- """Removes a role from a user."""
143
- if self.user_id is None:
144
- raise Exception('No user specified')
145
-
146
- # SQL Query Explanation:
147
- # Deletes the row from the `user_role_assignments` table that matches
148
- # the specified user ($1) and role ($2).
149
- sql = "DELETE FROM user_role_assignments WHERE user_id = $1 AND role_id = $2"
150
- try:
151
- await db.execute_secured_query(
152
- sql,
153
- self.user_id,
154
- role_id,
155
- fetch_method='execute'
156
- )
157
- except Exception as e:
158
- raise Exception(f'Failed to remove role: {e}')
159
-
160
- async def get_all_roles(self) -> List[Dict[str, Any]]:
161
- """Returns all available roles."""
162
- # SQL Query Explanation:
163
- # Selects all roles from the `user_roles` table.
164
- sql = "SELECT id, name, description FROM user_roles ORDER BY name"
165
- try:
166
- return await db.execute_secured_query(sql)
167
- except Exception as e:
168
- raise Exception(f'Failed to get roles: {e}')
169
-
170
- async def get_all_permissions(self) -> List[Dict[str, Any]]:
171
- """Returns all available permissions."""
172
- # SQL Query Explanation:
173
- # Selects all permissions from the `user_permissions` table.
174
- sql = "SELECT id, name, description FROM user_permissions ORDER BY name"
175
- try:
176
- return await db.execute_secured_query(sql)
177
- except Exception as e:
178
- raise Exception(f'Failed to get permissions: {e}')
179
-
180
- async def create_role(self, name: str, description: str) -> int:
181
- """Creates a new role."""
182
- # SQL Query Explanation:
183
- # Inserts a new role into the `user_roles` table and returns the
184
- # automatically generated ID of the new role (`RETURNING id`).
185
- sql = "INSERT INTO user_roles (name, description) VALUES ($1, $2) RETURNING id"
186
- try:
187
- result = await db.execute_secured_query(
188
- sql,
189
- name,
190
- description,
191
- fetch_method='fetchrow'
192
- )
193
- return result['id']
194
- except Exception as e:
195
- raise Exception(f'Failed to create role: {e}')
196
-
197
- async def update_role_permissions(self, role_id: int, permission_ids: List[int]) -> None:
198
- """Updates the permissions for a role."""
199
- # IMPORTANT: Since your module does not handle transactions across multiple
200
- # queries, we perform these actions sequentially. Query-level security
201
- # is guaranteed by your module.
202
- try:
203
- # SQL Query Explanation:
204
- # Deletes all existing permissions for the given role.
205
- sql_delete = "DELETE FROM role_permissions WHERE role_id = $1"
206
- await db.execute_secured_query(sql_delete, role_id, fetch_method='execute')
207
-
208
- # SQL Query Explanation:
209
- # Inserts a new row for each permission_id passed into the
210
- # `role_permissions` table.
211
- if permission_ids:
212
- sql_insert = "INSERT INTO role_permissions (role_id, permission_id) VALUES ($1, $2)"
213
- for permission_id in permission_ids:
214
- await db.execute_secured_query(
215
- sql_insert,
216
- role_id,
217
- permission_id,
218
- fetch_method='execute'
219
- )
220
- except Exception as e:
221
- # If an error occurs, the underlying foundation will log the issue.
222
- # We re-raise the error here.
223
- raise Exception(f'Failed to update role permissions: {e}')
224
-
225
- async def get_role_permissions(self, role_id: int) -> List[Dict[str, Any]]:
226
- """Returns all permissions for a role."""
227
- # SQL Query Explanation:
228
- # Selects the details (id, name, description) of all permissions
229
- # linked to the specified role.
230
- sql = """
231
- SELECT p.id, p.name, p.description
232
- FROM role_permissions rp
233
- JOIN user_permissions p ON rp.permission_id = p.id
234
- WHERE rp.role_id = $1
235
- ORDER BY p.name
236
- """
237
- try:
238
- return await db.execute_secured_query(sql, role_id)
239
- except Exception as e:
240
- 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,79 +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
- if await self.user_handler.login(username, password, request_data):
54
- return await self.user_handler.validate_session(request_data)
55
- return False
56
-
57
- # VORHER: Hier fehlt die Überprüfung, ob 'self.access_control' None ist.
58
- async def check_permission(self, user_id: int, permission_name: str) -> bool:
59
- logger.debug(f"Checking permission '{permission_name}' for user ID {user_id}")
60
- return await self.access_control.has_permission(user_id, permission_name)
61
-
62
- # VORHER: Hier wird geprüft, ob 'self.encryption' None ist, was korrekt ist.
63
- def encrypt_data(self, data: str) -> Dict[str, str]:
64
- if not self.encryption:
65
- raise RuntimeError("Encryption service not initialized.")
66
- logger.debug("Encrypting data.")
67
- return self.encryption.encrypt(data)
68
-
69
- # VORHER: Hier wird geprüft, ob 'self.encryption' None ist, was korrekt ist.
70
- def decrypt_data(self, encrypted_data: str, nonce: str, tag: str) -> Optional[str]:
71
- if not self.encryption:
72
- logger.error("Encryption service not initialized. Cannot decrypt data.")
73
- return None
74
- logger.debug("Decrypting data.")
75
- try:
76
- return self.encryption.decrypt(encrypted_data, nonce, tag)
77
- except Exception as e:
78
- logger.error(f"Decryption failed: {e}")
79
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fundaments/user_handler.py DELETED
@@ -1,342 +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
- # 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
- class Database:
15
- """
16
- A simple placeholder class to simulate a database connection.
17
- In a real application, you would use a proper ORM like SQLAlchemy
18
- or a specific database driver.
19
- """
20
- def __init__(self, db_name="cms_database.db"):
21
- self.conn = sqlite3.connect(db_name)
22
- self.cursor = self.conn.cursor()
23
-
24
- def execute(self, query, params=None):
25
- if params is None:
26
- params = []
27
- self.cursor.execute(query, params)
28
- self.conn.commit()
29
-
30
- def fetchone(self, query, params=None):
31
- if params is None:
32
- params = []
33
- self.cursor.execute(query, params)
34
- return self.cursor.fetchone()
35
-
36
- def fetchall(self, query, params=None):
37
- if params is None:
38
- params = []
39
- self.cursor.execute(query, params)
40
- return self.cursor.fetchall()
41
-
42
- def close(self):
43
- self.conn.close()
44
-
45
- def setup_tables(self):
46
- """
47
- Creates the necessary tables for users and sessions.
48
- """
49
- self.execute("""
50
- CREATE TABLE IF NOT EXISTS users (
51
- id INTEGER PRIMARY KEY AUTOINCREMENT,
52
- username TEXT UNIQUE NOT NULL,
53
- password TEXT NOT NULL,
54
- is_admin INTEGER NOT NULL DEFAULT 0,
55
- account_locked INTEGER NOT NULL DEFAULT 0,
56
- failed_login_attempts INTEGER NOT NULL DEFAULT 0
57
- )
58
- """)
59
- self.execute("""
60
- CREATE TABLE IF NOT EXISTS sessions (
61
- id TEXT PRIMARY KEY,
62
- user_id INTEGER NOT NULL,
63
- ip_address TEXT,
64
- user_agent TEXT,
65
- last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
66
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
67
- )
68
- """)
69
-
70
- class Security:
71
- """
72
- Handles secure password hashing and session regeneration.
73
- Using passlib for robust and secure password management.
74
- """
75
- @staticmethod
76
- def hash_password(password: str) -> str:
77
- """Hashes a password using PBKDF2 with SHA256."""
78
- return pbkdf2_sha256.hash(password)
79
-
80
- @staticmethod
81
- def verify_password(password: str, hashed_password: str) -> bool:
82
- """Verifies a password against a stored hash."""
83
- return pbkdf2_sha256.verify(password, hashed_password)
84
-
85
- @staticmethod
86
- def regenerate_session(session_id: str):
87
- """
88
- Simulates regenerating a session ID to prevent session fixation.
89
- In a real web framework, this would be a framework-specific function.
90
- """
91
- print(f"Session regenerated. Old ID: {session_id}")
92
- new_session_id = str(uuid.uuid4())
93
- print(f"New ID: {new_session_id}")
94
- return new_session_id
95
-
96
- class UserHandler:
97
- """
98
- Handles user login, logout, and session validation.
99
- This class mirrors the logic from the user's PHP User class.
100
- """
101
- def __init__(self, db: Database):
102
- self.db = db
103
- # A simple in-memory session store for this example
104
- self._session = {}
105
-
106
- def login(self, username: str, password: str, request_data: dict) -> bool:
107
- """
108
- Logs in the user by verifying credentials and storing a new session.
109
- :param username: The user's username.
110
- :param password: The user's plain-text password.
111
- :param request_data: A dictionary containing 'ip_address' and 'user_agent'.
112
- :return: True if login is successful, False otherwise.
113
- """
114
- try:
115
- # Step 1: Find the user in the database
116
- user_data = self.db.fetchone("SELECT id, username, password, is_admin, account_locked, failed_login_attempts FROM users WHERE username = ?", (username,))
117
- if user_data is None:
118
- print(f"Login failed: Username '{username}' not found.")
119
- return False
120
-
121
- user = {
122
- 'id': user_data[0],
123
- 'username': user_data[1],
124
- 'password': user_data[2],
125
- 'is_admin': user_data[3],
126
- 'account_locked': user_data[4],
127
- 'failed_login_attempts': user_data[5]
128
- }
129
-
130
- # Check if account is locked
131
- if user['account_locked'] == 1:
132
- print(f"Login failed: Account for '{username}' is locked.")
133
- return False
134
-
135
- # Step 2: Verify the password
136
- if Security.verify_password(password, user['password']):
137
- print(f"Login successful for user: '{username}'")
138
-
139
- # Reset failed login attempts on success
140
- self.reset_failed_attempts(username)
141
-
142
- # Step 3: Create a new session record in the database
143
- session_id = str(uuid.uuid4())
144
- ip_address = request_data.get('ip_address', 'unknown')
145
- user_agent = request_data.get('user_agent', 'unknown')
146
-
147
- self.db.execute(
148
- "INSERT INTO sessions (id, user_id, ip_address, user_agent) VALUES (?, ?, ?, ?)",
149
- (session_id, user['id'], ip_address, user_agent)
150
- )
151
-
152
- # Step 4: Store session data in the in-memory session (or a session store)
153
- self._session = {
154
- 'session_id': session_id,
155
- 'user_id': user['id'],
156
- 'username': user['username'],
157
- 'is_admin': user['is_admin']
158
- }
159
-
160
- # Security: Regenerate session ID
161
- self._session['session_id'] = Security.regenerate_session(session_id)
162
- return True
163
- else:
164
- print(f"Login failed: Incorrect password for user '{username}'.")
165
- # Increment failed login attempts
166
- self.increment_failed_attempts(username)
167
- return False
168
-
169
- except sqlite3.Error as e:
170
- print(f"Database error during login: {e}")
171
- return False
172
-
173
- def logout(self) -> bool:
174
- """
175
- Logs out the current user by deleting the session from the database.
176
- :return: True if logout is successful, False otherwise.
177
- """
178
- if 'user_id' not in self._session:
179
- print("No active session to log out.")
180
- return False
181
-
182
- try:
183
- # Step 1: Delete the session from the database
184
- self.db.execute("DELETE FROM sessions WHERE user_id = ?", (self._session['user_id'],))
185
-
186
- # Step 2: Clear the in-memory session data
187
- self._session.clear()
188
- print("User logged out successfully.")
189
- return True
190
- except sqlite3.Error as e:
191
- print(f"Database error during logout: {e}")
192
- return False
193
-
194
- def is_logged_in(self) -> bool:
195
- """
196
- Checks if the current user is logged in.
197
- :return: True if a valid session exists, False otherwise.
198
- """
199
- if 'user_id' not in self._session:
200
- return False
201
-
202
- try:
203
- # Check for the session in the database
204
- session_data = self.db.fetchone(
205
- "SELECT * FROM sessions WHERE id = ? AND user_id = ?",
206
- (self._session['session_id'], self._session['user_id'])
207
- )
208
- return session_data is not None
209
- except sqlite3.Error as e:
210
- print(f"Database error during is_logged_in check: {e}")
211
- return False
212
-
213
- def is_admin(self) -> bool:
214
- """
215
- Checks if the logged-in user is an admin.
216
- :return: True if the user is an admin, False otherwise.
217
- """
218
- return self._session.get('is_admin', 0) == 1
219
-
220
- def validate_session(self, request_data: dict) -> bool:
221
- """
222
- Validates the current session against IP address and user agent.
223
- :param request_data: A dictionary containing 'ip_address' and 'user_agent'.
224
- :return: True if the session is valid, False otherwise.
225
- """
226
- if not self.is_logged_in():
227
- return False
228
-
229
- try:
230
- ip_address = request_data.get('ip_address', 'unknown')
231
- user_agent = request_data.get('user_agent', 'unknown')
232
-
233
- session_data = self.db.fetchone(
234
- "SELECT * FROM sessions WHERE id = ? AND user_id = ? AND ip_address = ? AND user_agent = ?",
235
- (self._session['session_id'], self._session['user_id'], ip_address, user_agent)
236
- )
237
- return session_data is not None
238
- except sqlite3.Error as e:
239
- print(f"Database error during session validation: {e}")
240
- return False
241
-
242
- def lock_account(self, username: str):
243
- """
244
- Locks a user account.
245
- :param username: The username of the account to lock.
246
- """
247
- try:
248
- self.db.execute("UPDATE users SET account_locked = 1 WHERE username = ?", (username,))
249
- print(f"Account for '{username}' has been locked.")
250
- except sqlite3.Error as e:
251
- print(f"Database error while locking account: {e}")
252
-
253
- def reset_failed_attempts(self, username: str):
254
- """
255
- Resets failed login attempts for a user.
256
- :param username: The username of the account.
257
- """
258
- try:
259
- self.db.execute("UPDATE users SET failed_login_attempts = 0 WHERE username = ?", (username,))
260
- except sqlite3.Error as e:
261
- print(f"Database error while resetting failed attempts: {e}")
262
-
263
- def increment_failed_attempts(self, username: str):
264
- """
265
- Increments failed login attempts and locks the account if a threshold is met.
266
- :param username: The username of the account.
267
- """
268
- try:
269
- # Get the current failed attempts
270
- user_data = self.db.fetchone("SELECT failed_login_attempts FROM users WHERE username = ?", (username,))
271
- if user_data:
272
- attempts = user_data[0] + 1
273
- self.db.execute(
274
- "UPDATE users SET failed_login_attempts = ? WHERE username = ?",
275
- (attempts, username)
276
- )
277
- print(f"Failed login attempts for '{username}': {attempts}")
278
-
279
- # Check for threshold (e.g., 5 attempts)
280
- if attempts >= 5:
281
- self.lock_account(username)
282
-
283
- except sqlite3.Error as e:
284
- print(f"Database error while incrementing failed attempts: {e}")
285
-
286
- # --- Example Usage ---
287
- if __name__ == "__main__":
288
- db = Database()
289
- db.setup_tables()
290
- user_handler = UserHandler(db)
291
-
292
- # Clean up old test data if it exists
293
- db.execute("DELETE FROM users WHERE username IN (?, ?)", ("testuser", "adminuser"))
294
- db.execute("DELETE FROM sessions")
295
-
296
- # 1. Register a new user and an admin user
297
- hashed_password = Security.hash_password("secure_password_123")
298
- db.execute("INSERT INTO users (username, password) VALUES (?, ?)", ("testuser", hashed_password))
299
- db.execute("INSERT INTO users (username, password, is_admin) VALUES (?, ?, 1)", ("adminuser", hashed_password))
300
-
301
- print("--- Test 1: Successful Login ---")
302
- # Simulate a web request
303
- request_data = {
304
- 'ip_address': '192.168.1.100',
305
- 'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
306
- }
307
-
308
- login_success = user_handler.login("testuser", "secure_password_123", request_data)
309
- print(f"Login attempt status: {login_success}")
310
- print(f"Is user logged in? {user_handler.is_logged_in()}")
311
- print(f"Is user an admin? {user_handler.is_admin()}")
312
- print(f"Is session valid? {user_handler.validate_session(request_data)}")
313
- print("-" * 20)
314
-
315
- # 2. Simulate a logout
316
- print("--- Test 2: Logout ---")
317
- user_handler.logout()
318
- print(f"Is user logged in after logout? {user_handler.is_logged_in()}")
319
- print("-" * 20)
320
-
321
- # 3. Simulate a failed login and account lock
322
- print("--- Test 3: Failed Login and Account Lock ---")
323
- # Log in with the wrong password multiple times
324
- for i in range(6):
325
- user_handler.login("testuser", "wrong_password", request_data)
326
-
327
- # Now, try to log in with the correct password. It should fail because the account is locked.
328
- print("\nAttempting to log in with correct password after lock:")
329
- login_attempt_after_lock = user_handler.login("testuser", "secure_password_123", request_data)
330
- print(f"Login attempt status: {login_attempt_after_lock}")
331
- print("-" * 20)
332
-
333
- # 4. Reset failed attempts for a new login
334
- print("--- Test 4: Resetting failed attempts ---")
335
- user_handler.reset_failed_attempts("testuser")
336
- login_attempt_after_reset = user_handler.login("testuser", "secure_password_123", request_data)
337
- print(f"Login attempt status after reset: {login_attempt_after_reset}")
338
-
339
- db.close()
340
-
341
- # Optional: Clean up the database file after the run
342
- # os.remove("cms_database.db")