-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconfig_manager.py
More file actions
261 lines (224 loc) · 9.34 KB
/
Copy pathconfig_manager.py
File metadata and controls
261 lines (224 loc) · 9.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""
Configuration Manager for NoSQL2SQL
Handles settings persistence, theme preferences, MCP toggles, and secure API key storage
"""
import json
import os
from pathlib import Path
from cryptography.fernet import Fernet
import base64
import hashlib
class SettingsManager:
"""Manages application settings with encryption for sensitive data"""
def __init__(self):
self.config_dir = Path.home() / ".nosql2sql"
self.config_file = self.config_dir / "settings.json"
self.secure_file = self.config_dir / "secure.enc"
self.key_file = self.config_dir / ".key"
# Default settings
self.settings = {
"theme": "auto", # auto, light, dark
"mcp_enabled": False,
"mcp_auto_start": False,
"visualization_enabled": True,
"ai_recommendations_enabled": False,
"last_source_db": "Redis",
"last_target_db": "MySQL",
"window_geometry": "700x700",
"chat_history_enabled": True,
"auto_backup": True
}
self.secure_data = {
"gemini_api_key": "",
"neo4j_password": "",
"couchdb_password": ""
}
self._ensure_config_dir()
self._load_or_create_key()
self.load_settings()
def _ensure_config_dir(self):
"""Create config directory if it doesn't exist"""
try:
self.config_dir.mkdir(parents=True, exist_ok=True)
# Set directory permissions (Windows) - simplified approach
if os.name == 'nt':
try:
import subprocess
subprocess.run(['icacls', str(self.config_dir), '/grant', f'{os.getlogin()}:(OI)(CI)F'],
capture_output=True, check=False, timeout=5)
except:
pass
except Exception as e:
print(f"Warning: Config directory issue: {e}")
# Try to use local directory as fallback
try:
self.config_dir = Path(__file__).parent / ".nosql2sql_local"
self.config_dir.mkdir(parents=True, exist_ok=True)
self.config_file = self.config_dir / "settings.json"
self.secure_file = self.config_dir / "secure.enc"
self.key_file = self.config_dir / "encryption.key"
except:
pass
def _load_or_create_key(self):
"""Load or create encryption key"""
# Check if key file exists and is a directory (error case)
if self.key_file.exists() and self.key_file.is_dir():
import shutil
shutil.rmtree(self.key_file)
if self.key_file.exists() and self.key_file.is_file():
try:
with open(self.key_file, 'rb') as f:
self.cipher_key = f.read()
except Exception as e:
print(f"Warning: Could not read key file: {e}")
# Delete corrupted key file and regenerate
self.key_file.unlink()
self._load_or_create_key() # Recursive call to regenerate
return
else:
# Generate key from machine-specific data
machine_id = self._get_machine_id()
self.cipher_key = base64.urlsafe_b64encode(
hashlib.sha256(machine_id.encode()).digest()
)
try:
with open(self.key_file, 'wb') as f:
f.write(self.cipher_key)
# Hide the key file (Windows)
if os.name == 'nt':
try:
import ctypes
FILE_ATTRIBUTE_HIDDEN = 0x02
ctypes.windll.kernel32.SetFileAttributesW(str(self.key_file),
FILE_ATTRIBUTE_HIDDEN)
except:
pass # Not critical if hiding fails
except PermissionError:
print(f"Warning: Could not write key file to {self.key_file}")
# Use in-memory key only
pass
self.cipher = Fernet(self.cipher_key)
def _get_machine_id(self):
"""Get unique machine identifier"""
if os.name == 'nt':
# Windows - use MachineGuid
try:
import winreg
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\Cryptography")
guid = winreg.QueryValueEx(key, "MachineGuid")[0]
winreg.CloseKey(key)
return guid
except:
pass
# Fallback to hostname + username
import socket
return f"{socket.gethostname()}-{os.getlogin()}"
def load_settings(self):
"""Load settings from file"""
# Load general settings
if self.config_file.exists():
try:
with open(self.config_file, 'r') as f:
loaded = json.load(f)
self.settings.update(loaded)
except Exception as e:
print(f"Warning: Could not load settings: {e}")
# Load secure settings
if self.secure_file.exists():
try:
with open(self.secure_file, 'rb') as f:
encrypted = f.read()
decrypted = self.cipher.decrypt(encrypted)
loaded_secure = json.loads(decrypted)
self.secure_data.update(loaded_secure)
except Exception as e:
print(f"Warning: Could not load secure settings: {e}")
def save_settings(self):
"""Save settings to file"""
# Save general settings
try:
with open(self.config_file, 'w') as f:
json.dump(self.settings, f, indent=2)
except Exception as e:
print(f"Error saving settings: {e}")
# Save secure settings
try:
json_data = json.dumps(self.secure_data)
encrypted = self.cipher.encrypt(json_data.encode())
with open(self.secure_file, 'wb') as f:
f.write(encrypted)
except Exception as e:
print(f"Error saving secure settings: {e}")
def get(self, key, default=None):
"""Get a setting value"""
return self.settings.get(key, default)
def set(self, key, value):
"""Set a setting value"""
self.settings[key] = value
self.save_settings()
def get_secure(self, key, default=""):
"""Get a secure setting value"""
return self.secure_data.get(key, default)
def set_secure(self, key, value):
"""Set a secure setting value"""
self.secure_data[key] = value
self.save_settings()
def get_theme(self):
"""Get current theme preference"""
theme = self.settings.get("theme", "auto")
if theme == "auto":
# Detect Windows theme
if os.name == 'nt':
try:
import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize")
value = winreg.QueryValueEx(key, "AppsUseLightTheme")[0]
winreg.CloseKey(key)
return "light" if value == 1 else "dark"
except:
pass
return "light" # Default fallback
return theme
def is_mcp_enabled(self):
"""Check if MCP is enabled"""
return self.settings.get("mcp_enabled", False)
def is_visualization_enabled(self):
"""Check if visualization is enabled"""
return self.settings.get("visualization_enabled", True)
def is_ai_recommendations_enabled(self):
"""Check if AI recommendations are enabled"""
return self.settings.get("ai_recommendations_enabled", False)
def has_gemini_api_key(self):
"""Check if Gemini API key is configured"""
return bool(self.secure_data.get("gemini_api_key"))
def reset_to_defaults(self):
"""Reset all settings to defaults"""
self.settings = {
"theme": "auto",
"mcp_enabled": False,
"mcp_auto_start": False,
"visualization_enabled": True,
"ai_recommendations_enabled": False,
"last_source_db": "Redis",
"last_target_db": "MySQL",
"window_geometry": "700x700",
"chat_history_enabled": True,
"auto_backup": True
}
self.save_settings()
if __name__ == "__main__":
# Test the settings manager
print("Testing Settings Manager...")
manager = SettingsManager()
print(f"Config directory: {manager.config_dir}")
print(f"Current theme: {manager.get_theme()}")
print(f"MCP enabled: {manager.is_mcp_enabled()}")
# Test setting and getting
manager.set("test_setting", "test_value")
print(f"Test setting: {manager.get('test_setting')}")
# Test secure storage
manager.set_secure("gemini_api_key", "test_api_key_12345")
print(f"API key stored: {manager.has_gemini_api_key()}")
print("✅ Settings Manager test complete!")