keepup-admin 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of keepup-admin might be problematic. Click here for more details.
- keepup/THIRD-PARTY.md +44 -0
- keepup/__init__.py +41 -0
- keepup/api_versions.py +100 -0
- keepup/audit.py +499 -0
- keepup/auth/__init__.py +7 -0
- keepup/auth/config.py +128 -0
- keepup/auth/dependencies.py +485 -0
- keepup/auth/dto/__init__.py +0 -0
- keepup/auth/dto/token.py +31 -0
- keepup/auth/factory.py +28 -0
- keepup/auth/login_throttle.py +151 -0
- keepup/auth/oidc.py +245 -0
- keepup/auth/oidc_policy.py +111 -0
- keepup/auth/oidc_routes.py +288 -0
- keepup/auth/panel_session.py +220 -0
- keepup/auth/permissions.py +59 -0
- keepup/auth/providers/__init__.py +0 -0
- keepup/auth/providers/base.py +168 -0
- keepup/auth/providers/local.py +180 -0
- keepup/auth/routes.py +660 -0
- keepup/auth/seed_accounts.py +322 -0
- keepup/auth/session_lifetime.py +104 -0
- keepup/auth/signing_key.py +138 -0
- keepup/auth/websocket.py +86 -0
- keepup/cluster.py +634 -0
- keepup/db.py +663 -0
- keepup/events.py +764 -0
- keepup/factory.py +484 -0
- keepup/instance.py +46 -0
- keepup/integrations.py +260 -0
- keepup/locks.py +412 -0
- keepup/logging_setup.py +690 -0
- keepup/metrics.py +818 -0
- keepup/metrics_retention.py +376 -0
- keepup/modules.py +572 -0
- keepup/notification_bus.py +355 -0
- keepup/plugins/__init__.py +9 -0
- keepup/plugins/admin.py +246 -0
- keepup/plugins/base.py +234 -0
- keepup/plugins/enablement.py +184 -0
- keepup/plugins/registry.py +171 -0
- keepup/plugins/route_mask.py +338 -0
- keepup/plugins/routes.py +376 -0
- keepup/roles.py +17 -0
- keepup/scheduler.py +93 -0
- keepup/schema.py +295 -0
- keepup/sections.json +104 -0
- keepup/settings.py +184 -0
- keepup/static/css/aos.css +1 -0
- keepup/static/css/main_nebula.css +232 -0
- keepup/static/css/main_new.css +852 -0
- keepup/static/css/tailwind.css +1 -0
- keepup/static/index_nebula.html +293 -0
- keepup/static/index_new.html +286 -0
- keepup/static/js/aos.js +1 -0
- keepup/static/js/feather-icons.js +13 -0
- keepup/static/js/main_new.js +1861 -0
- keepup/static/js/tailwind.js +83 -0
- keepup/static/modules/css/background_tasks.css +233 -0
- keepup/static/modules/css/cluster.css +16 -0
- keepup/static/modules/css/event_manager.css +386 -0
- keepup/static/modules/css/integration_logs.css +33 -0
- keepup/static/modules/css/metrics.css +115 -0
- keepup/static/modules/css/modules.css +189 -0
- keepup/static/modules/css/themes.css +563 -0
- keepup/static/modules/css/users.css +278 -0
- keepup/static/modules/js/background_tasks.js +657 -0
- keepup/static/modules/js/chart.js +14 -0
- keepup/static/modules/js/chartjs-adapter-date-fns.bundle.min.js +7 -0
- keepup/static/modules/js/cluster.js +363 -0
- keepup/static/modules/js/event_manager.js +979 -0
- keepup/static/modules/js/integration_logs.js +767 -0
- keepup/static/modules/js/metrics.js +908 -0
- keepup/static/modules/js/modules.js +1086 -0
- keepup/static/modules/js/themes.js +653 -0
- keepup/static/modules/js/users.js +784 -0
- keepup/tables.py +302 -0
- keepup/themes.py +496 -0
- keepup/web.py +182 -0
- keepup_admin-0.1.0.dist-info/METADATA +117 -0
- keepup_admin-0.1.0.dist-info/RECORD +86 -0
- keepup_admin-0.1.0.dist-info/WHEEL +5 -0
- keepup_admin-0.1.0.dist-info/licenses/LICENSE +202 -0
- keepup_admin-0.1.0.dist-info/licenses/NOTICE +22 -0
- keepup_admin-0.1.0.dist-info/licenses/THIRD-PARTY.md +44 -0
- keepup_admin-0.1.0.dist-info/top_level.txt +1 -0
keepup/modules.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
1
|
+
"""The catalogue of panel sections.
|
|
2
|
+
|
|
3
|
+
A section is a piece of the front end -- a script, a stylesheet, an init
|
|
4
|
+
function -- and a role is granted the sections it may see. The catalogue lives
|
|
5
|
+
in the database; the file the application ships is a seed and a fallback, and
|
|
6
|
+
new sections are added from it without touching what an administrator has
|
|
7
|
+
already switched off or taken away from a role.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
import time
|
|
15
|
+
from typing import Any, Dict, List, Optional
|
|
16
|
+
|
|
17
|
+
from fastapi import Depends, HTTPException, status
|
|
18
|
+
from pydantic import BaseModel
|
|
19
|
+
|
|
20
|
+
from keepup.auth.dependencies import get_current_admin, get_current_user
|
|
21
|
+
from keepup.db import DatabaseManager, DatabaseManagerV2, db_config
|
|
22
|
+
|
|
23
|
+
#: What an application may import from this module. Everything else is
|
|
24
|
+
#: internal and may change without notice -- see doc/keepup.md.
|
|
25
|
+
__all__ = [
|
|
26
|
+
"create_or_update_module",
|
|
27
|
+
"delete_module",
|
|
28
|
+
"get_all_modules_from_db",
|
|
29
|
+
"get_module_by_id",
|
|
30
|
+
"get_modules_for_role",
|
|
31
|
+
"import_modules_from_json",
|
|
32
|
+
"register_module_routes",
|
|
33
|
+
"sync_framework_sections",
|
|
34
|
+
"sync_new_modules_from_json",
|
|
35
|
+
"update_role_modules",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
MODULES_CONFIG_PATH = 'config/modules.json'
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ModuleCreate(BaseModel):
|
|
44
|
+
"""A panel section being declared."""
|
|
45
|
+
|
|
46
|
+
module_id: str
|
|
47
|
+
name: str
|
|
48
|
+
description: Optional[str] = None
|
|
49
|
+
js_path: Optional[str] = None
|
|
50
|
+
css_path: Optional[str] = None
|
|
51
|
+
init_function: Optional[str] = None
|
|
52
|
+
version: str = "1.0.0"
|
|
53
|
+
config: Optional[Dict[str, Any]] = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ModuleUpdate(BaseModel):
|
|
57
|
+
"""The parts of a declared section that may be changed."""
|
|
58
|
+
|
|
59
|
+
name: Optional[str] = None
|
|
60
|
+
description: Optional[str] = None
|
|
61
|
+
js_path: Optional[str] = None
|
|
62
|
+
css_path: Optional[str] = None
|
|
63
|
+
init_function: Optional[str] = None
|
|
64
|
+
version: Optional[str] = None
|
|
65
|
+
config: Optional[Dict[str, Any]] = None
|
|
66
|
+
is_active: Optional[bool] = None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class RoleModulesUpdate(BaseModel):
|
|
70
|
+
"""Which sections a role is granted."""
|
|
71
|
+
|
|
72
|
+
role_name: str
|
|
73
|
+
module_ids: List[str]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_all_modules_from_db():
|
|
77
|
+
"""Return every module from the database."""
|
|
78
|
+
return DatabaseManager.execute_sql('''
|
|
79
|
+
SELECT * FROM frontend_modules
|
|
80
|
+
WHERE is_active = TRUE
|
|
81
|
+
ORDER BY name
|
|
82
|
+
''')
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def get_module_by_id(module_id: str):
|
|
86
|
+
"""Return a module by id."""
|
|
87
|
+
return DatabaseManager.execute_sql_one('''
|
|
88
|
+
SELECT * FROM frontend_modules
|
|
89
|
+
WHERE module_id = ? AND is_active = TRUE
|
|
90
|
+
''', (module_id,))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def get_modules_for_role(role_name: str):
|
|
94
|
+
"""Return the modules granted to a role."""
|
|
95
|
+
return DatabaseManager.execute_sql('''
|
|
96
|
+
SELECT fm.*
|
|
97
|
+
FROM frontend_modules fm
|
|
98
|
+
JOIN role_modules rm ON fm.module_id = rm.module_id
|
|
99
|
+
WHERE rm.role_name = ?
|
|
100
|
+
AND rm.is_active = TRUE
|
|
101
|
+
AND fm.is_active = TRUE
|
|
102
|
+
ORDER BY fm.name
|
|
103
|
+
''', (role_name,))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def create_or_update_module(module_data: Dict[str, Any]):
|
|
107
|
+
"""Create or update a module."""
|
|
108
|
+
try:
|
|
109
|
+
module_id = module_data['id']
|
|
110
|
+
logger.info(f"=== Processing module: {module_id} ===")
|
|
111
|
+
|
|
112
|
+
name = module_data['name']
|
|
113
|
+
description = module_data.get('description')
|
|
114
|
+
js_path = module_data.get('js')
|
|
115
|
+
css_path = module_data.get('css')
|
|
116
|
+
init_function = module_data.get('initFunction')
|
|
117
|
+
version = module_data.get('version', '1.0.0')
|
|
118
|
+
config = json.dumps(module_data.get('config', {}))
|
|
119
|
+
|
|
120
|
+
logger.info(f"DB type: {db_config.db_type}")
|
|
121
|
+
logger.info(f"Name: {name}")
|
|
122
|
+
logger.info(f"JS path: {js_path}")
|
|
123
|
+
logger.info(f"CSS path: {css_path}")
|
|
124
|
+
logger.info(f"Init function: {init_function}")
|
|
125
|
+
|
|
126
|
+
existing = get_module_by_id(module_id)
|
|
127
|
+
logger.info(f"Module exists: {existing is not None}")
|
|
128
|
+
|
|
129
|
+
if existing:
|
|
130
|
+
logger.info(f"UPDATE path for module: {module_id}")
|
|
131
|
+
if db_config.is_postgres():
|
|
132
|
+
query = '''
|
|
133
|
+
UPDATE frontend_modules
|
|
134
|
+
SET name = %s, description = %s, js_path = %s, css_path = %s,
|
|
135
|
+
init_function = %s, version = %s, config = %s, updated_at = CURRENT_TIMESTAMP
|
|
136
|
+
WHERE module_id = %s
|
|
137
|
+
'''
|
|
138
|
+
else:
|
|
139
|
+
query = '''
|
|
140
|
+
UPDATE frontend_modules
|
|
141
|
+
SET name = ?, description = ?, js_path = ?, css_path = ?,
|
|
142
|
+
init_function = ?, version = ?, config = ?, updated_at = CURRENT_TIMESTAMP
|
|
143
|
+
WHERE module_id = ?
|
|
144
|
+
'''
|
|
145
|
+
params = (name, description, js_path, css_path, init_function, version, config, module_id)
|
|
146
|
+
else:
|
|
147
|
+
logger.info(f"INSERT path for module: {module_id}")
|
|
148
|
+
if db_config.is_postgres():
|
|
149
|
+
query = '''
|
|
150
|
+
INSERT INTO frontend_modules
|
|
151
|
+
(module_id, name, description, js_path, css_path, init_function, version, config)
|
|
152
|
+
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
|
153
|
+
'''
|
|
154
|
+
else:
|
|
155
|
+
query = '''
|
|
156
|
+
INSERT INTO frontend_modules
|
|
157
|
+
(module_id, name, description, js_path, css_path, init_function, version, config)
|
|
158
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
159
|
+
'''
|
|
160
|
+
params = (module_id, name, description, js_path, css_path, init_function, version, config)
|
|
161
|
+
|
|
162
|
+
logger.info(f"Final query: {query}")
|
|
163
|
+
logger.info(f"Params count: {len(params)}")
|
|
164
|
+
logger.info(f"Params: {params}")
|
|
165
|
+
|
|
166
|
+
logger.info("Testing database connection...")
|
|
167
|
+
test_conn = DatabaseManager.get_connection()
|
|
168
|
+
if test_conn:
|
|
169
|
+
logger.info("Database connection OK")
|
|
170
|
+
test_conn.close()
|
|
171
|
+
else:
|
|
172
|
+
logger.error("Database connection FAILED")
|
|
173
|
+
return False
|
|
174
|
+
|
|
175
|
+
logger.info("Executing SQL query...")
|
|
176
|
+
start_time = time.time()
|
|
177
|
+
|
|
178
|
+
result = DatabaseManager.execute_commit_only(query, params)
|
|
179
|
+
|
|
180
|
+
execution_time = time.time() - start_time
|
|
181
|
+
logger.info(f"Query executed in {execution_time:.2f} seconds")
|
|
182
|
+
|
|
183
|
+
if result:
|
|
184
|
+
logger.info(f"✓ Successfully {'updated' if existing else 'created'} module: {module_id}")
|
|
185
|
+
else:
|
|
186
|
+
logger.error(f"✗ Failed to {'update' if existing else 'create'} module: {module_id}")
|
|
187
|
+
|
|
188
|
+
except Exception as e:
|
|
189
|
+
logger.error(f"🚨 Error in create_or_update_module for {module_data.get('id', 'unknown')}: {str(e)}")
|
|
190
|
+
import traceback
|
|
191
|
+
logger.error(f"Stack trace: {traceback.format_exc()}")
|
|
192
|
+
raise
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def update_role_modules(role_name: str, module_ids: List[str]):
|
|
196
|
+
"""Update the modules granted to a role."""
|
|
197
|
+
DatabaseManager.execute_commit_only('''
|
|
198
|
+
UPDATE role_modules
|
|
199
|
+
SET is_active = FALSE
|
|
200
|
+
WHERE role_name = ?
|
|
201
|
+
''', (role_name,))
|
|
202
|
+
|
|
203
|
+
for module_id in module_ids:
|
|
204
|
+
if db_config.is_postgres():
|
|
205
|
+
DatabaseManager.execute_commit_only('''
|
|
206
|
+
INSERT INTO role_modules (role_name, module_id, is_active)
|
|
207
|
+
VALUES (%s, %s, TRUE)
|
|
208
|
+
ON CONFLICT (role_name, module_id)
|
|
209
|
+
DO UPDATE SET is_active = TRUE
|
|
210
|
+
''', (role_name, module_id))
|
|
211
|
+
else:
|
|
212
|
+
DatabaseManager.execute_commit_only('''
|
|
213
|
+
INSERT OR REPLACE INTO role_modules (role_name, module_id, is_active)
|
|
214
|
+
VALUES (?, ?, TRUE)
|
|
215
|
+
''', (role_name, module_id))
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def delete_module(module_id: str):
|
|
219
|
+
"""Delete a module (soft delete)."""
|
|
220
|
+
DatabaseManager.execute_commit_only('''
|
|
221
|
+
UPDATE frontend_modules
|
|
222
|
+
SET is_active = FALSE, updated_at = CURRENT_TIMESTAMP
|
|
223
|
+
WHERE module_id = ?
|
|
224
|
+
''', (module_id,))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def import_modules_from_json():
|
|
228
|
+
"""Import the modules from the JSON file into the database."""
|
|
229
|
+
try:
|
|
230
|
+
with open(MODULES_CONFIG_PATH, 'r', encoding='utf-8') as f:
|
|
231
|
+
config = json.load(f)
|
|
232
|
+
|
|
233
|
+
for module_config in config.get('modules', []):
|
|
234
|
+
create_or_update_module(module_config)
|
|
235
|
+
|
|
236
|
+
for role_config in config.get('roles', []):
|
|
237
|
+
role_name = role_config.get('name')
|
|
238
|
+
module_ids = role_config.get('modules', [])
|
|
239
|
+
update_role_modules(role_name, module_ids)
|
|
240
|
+
|
|
241
|
+
logger.info("Modules imported successfully from JSON")
|
|
242
|
+
return True
|
|
243
|
+
except Exception as e:
|
|
244
|
+
logger.error(f"Error importing modules from JSON: {str(e)}")
|
|
245
|
+
return False
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
#: The catalogue the framework ships. Resolved from this file's location, like
|
|
249
|
+
#: the panel shell: it is data of the package, and the process may have been
|
|
250
|
+
#: started anywhere.
|
|
251
|
+
FRAMEWORK_SECTIONS = str(Path(__file__).resolve().parent / "sections.json")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def sync_framework_sections(path: str = FRAMEWORK_SECTIONS) -> Dict[str, int]:
|
|
255
|
+
"""Bring the framework's own panel sections into the catalogue.
|
|
256
|
+
|
|
257
|
+
The application does not declare them: eight sections -- users, the section
|
|
258
|
+
catalogue itself, the cluster, metrics, themes, events, background tasks
|
|
259
|
+
and the integration log -- belong to the framework, and an application that
|
|
260
|
+
had to copy eight entries into its own file would get them wrong one at a
|
|
261
|
+
time (task keepup-4).
|
|
262
|
+
|
|
263
|
+
One rule here differs from sync_new_modules_from_json, and it is worth
|
|
264
|
+
saying plainly:
|
|
265
|
+
|
|
266
|
+
the framework owns *where the files of its sections are*;
|
|
267
|
+
the administrator owns *whether they are shown and to whom*.
|
|
268
|
+
|
|
269
|
+
So `js_path`, `css_path` and `init_function` are updated on rows that
|
|
270
|
+
already exist, while `is_active` and the grants are only ever inserted when
|
|
271
|
+
missing. Without the update, a deployment that has been running since
|
|
272
|
+
before the move keeps `/static/modules/js/users.js` in its database, the
|
|
273
|
+
file is not there any more, and the section breaks silently -- the panel
|
|
274
|
+
fetches a 404 and shows nothing.
|
|
275
|
+
|
|
276
|
+
`name` and `description` are left alone on an existing row: they are what a
|
|
277
|
+
person reads in the menu, and an administrator may have changed them on
|
|
278
|
+
purpose.
|
|
279
|
+
|
|
280
|
+
Args:
|
|
281
|
+
path: the catalogue to read; the package's own by default.
|
|
282
|
+
|
|
283
|
+
Returns:
|
|
284
|
+
How many rows were added and how many had their paths corrected.
|
|
285
|
+
"""
|
|
286
|
+
counted = {"modules": 0, "repointed": 0, "grants": 0}
|
|
287
|
+
try:
|
|
288
|
+
with open(path, "r", encoding="utf-8") as catalogue:
|
|
289
|
+
declared = json.load(catalogue)
|
|
290
|
+
except Exception as error:
|
|
291
|
+
logger.error("Framework panel sections not synchronised: cannot read %s: %s",
|
|
292
|
+
path, error)
|
|
293
|
+
return counted
|
|
294
|
+
|
|
295
|
+
for section in declared.get("modules", []):
|
|
296
|
+
try:
|
|
297
|
+
counted["modules"] += max(0, DatabaseManager.execute_commit_only(
|
|
298
|
+
"INSERT INTO frontend_modules (module_id, name, description, js_path, "
|
|
299
|
+
"css_path, init_function, version, config) "
|
|
300
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (module_id) DO NOTHING",
|
|
301
|
+
(section["id"], section["name"], section.get("description"),
|
|
302
|
+
section.get("js"), section.get("css"), section.get("initFunction"),
|
|
303
|
+
section.get("version", "1.0.0"), json.dumps(section.get("config", {})))))
|
|
304
|
+
|
|
305
|
+
counted["repointed"] += max(0, DatabaseManager.execute_commit_only(
|
|
306
|
+
"UPDATE frontend_modules SET js_path = ?, css_path = ?, init_function = ? "
|
|
307
|
+
"WHERE module_id = ? AND (js_path IS DISTINCT FROM ? "
|
|
308
|
+
"OR css_path IS DISTINCT FROM ?)"
|
|
309
|
+
if db_config.is_postgres() else
|
|
310
|
+
"UPDATE frontend_modules SET js_path = ?, css_path = ?, init_function = ? "
|
|
311
|
+
"WHERE module_id = ? AND (js_path IS NOT ? OR css_path IS NOT ?)",
|
|
312
|
+
(section.get("js"), section.get("css"), section.get("initFunction"),
|
|
313
|
+
section["id"], section.get("js"), section.get("css"))))
|
|
314
|
+
except Exception as error:
|
|
315
|
+
logger.warning("Framework section %s not synchronised: %s",
|
|
316
|
+
section.get("id"), error)
|
|
317
|
+
|
|
318
|
+
for role in declared.get("roles", []):
|
|
319
|
+
for module_id in role.get("modules", []):
|
|
320
|
+
try:
|
|
321
|
+
counted["grants"] += max(0, DatabaseManager.execute_commit_only(
|
|
322
|
+
"INSERT INTO role_modules (role_name, module_id, is_active) "
|
|
323
|
+
"VALUES (?, ?, TRUE) ON CONFLICT (role_name, module_id) DO NOTHING",
|
|
324
|
+
(role.get("name"), module_id)))
|
|
325
|
+
except Exception as error:
|
|
326
|
+
logger.warning("Framework grant %s/%s not added: %s",
|
|
327
|
+
role.get("name"), module_id, error)
|
|
328
|
+
|
|
329
|
+
if counted["modules"] or counted["repointed"]:
|
|
330
|
+
logger.info("Framework panel sections: %s added, %s repointed",
|
|
331
|
+
counted["modules"], counted["repointed"])
|
|
332
|
+
return counted
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def sync_new_modules_from_json(path: str = MODULES_CONFIG_PATH) -> Dict[str, int]:
|
|
336
|
+
"""Add what the file declares and the database has never seen; change nothing else.
|
|
337
|
+
|
|
338
|
+
The catalogue of panel sections lives in the database, and the file is only its
|
|
339
|
+
seed. Until this ran at start-up, a section added to the file stayed invisible
|
|
340
|
+
after deployment until somebody remembered to call the import by hand. The full
|
|
341
|
+
import cannot run on its own: it rewrites every role's grants from the file and
|
|
342
|
+
so undoes what an administrator changed in the panel.
|
|
343
|
+
|
|
344
|
+
So only rows that do not exist at all are written: a module whose id has no row,
|
|
345
|
+
a grant whose (role, module) pair has no row. A section an administrator switched
|
|
346
|
+
off or took away from a role keeps its row, and stays the way he left it.
|
|
347
|
+
"""
|
|
348
|
+
added = {"modules": 0, "grants": 0}
|
|
349
|
+
try:
|
|
350
|
+
with open(path, 'r', encoding='utf-8') as f:
|
|
351
|
+
config = json.load(f)
|
|
352
|
+
except Exception as e:
|
|
353
|
+
logger.warning(f"Panel sections not synchronised: cannot read {path}: {e}")
|
|
354
|
+
return added
|
|
355
|
+
|
|
356
|
+
for module in config.get('modules', []):
|
|
357
|
+
try:
|
|
358
|
+
added["modules"] += max(0, DatabaseManager.execute_commit_only(
|
|
359
|
+
"INSERT INTO frontend_modules (module_id, name, description, js_path, css_path, "
|
|
360
|
+
"init_function, version, config) VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
|
|
361
|
+
"ON CONFLICT (module_id) DO NOTHING",
|
|
362
|
+
(module['id'], module['name'], module.get('description'), module.get('js'),
|
|
363
|
+
module.get('css'), module.get('initFunction'), module.get('version', '1.0.0'),
|
|
364
|
+
json.dumps(module.get('config', {})))))
|
|
365
|
+
except Exception as e:
|
|
366
|
+
logger.warning(f"Panel section {module.get('id')} not added: {e}")
|
|
367
|
+
|
|
368
|
+
for role in config.get('roles', []):
|
|
369
|
+
for module_id in role.get('modules', []):
|
|
370
|
+
try:
|
|
371
|
+
added["grants"] += max(0, DatabaseManager.execute_commit_only(
|
|
372
|
+
"INSERT INTO role_modules (role_name, module_id, is_active) VALUES (?, ?, TRUE) "
|
|
373
|
+
"ON CONFLICT (role_name, module_id) DO NOTHING",
|
|
374
|
+
(role.get('name'), module_id)))
|
|
375
|
+
except Exception as e:
|
|
376
|
+
logger.warning(f"Panel section {module_id} not granted to {role.get('name')}: {e}")
|
|
377
|
+
|
|
378
|
+
if added["modules"] or added["grants"]:
|
|
379
|
+
logger.info(f"Panel sections from {path}: added {added['modules']} section(s) and "
|
|
380
|
+
f"{added['grants']} role grant(s) the database did not have")
|
|
381
|
+
return added
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
async def get_modules_from_json_fallback(current_user: dict):
|
|
385
|
+
"""Load the modules from the JSON file when the database read fails."""
|
|
386
|
+
try:
|
|
387
|
+
with open(MODULES_CONFIG_PATH, 'r', encoding='utf-8') as f:
|
|
388
|
+
config = json.load(f)
|
|
389
|
+
|
|
390
|
+
user_role = current_user['role']
|
|
391
|
+
role_config = next(
|
|
392
|
+
(role for role in config.get('roles', []) if role.get('name') == user_role),
|
|
393
|
+
None
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
if not role_config:
|
|
397
|
+
return {"modules": []}
|
|
398
|
+
|
|
399
|
+
allowed_module_names = set(role_config.get('modules', []))
|
|
400
|
+
available_modules = [
|
|
401
|
+
module for module in config.get('modules', [])
|
|
402
|
+
if module.get('id') in allowed_module_names
|
|
403
|
+
]
|
|
404
|
+
|
|
405
|
+
return {"modules": available_modules}
|
|
406
|
+
|
|
407
|
+
except Exception as e:
|
|
408
|
+
logger.error(f"Error getting modules from JSON fallback: {str(e)}")
|
|
409
|
+
return {"modules": []}
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def register_module_routes(app):
|
|
413
|
+
"""Register the panel-section endpoints on the application."""
|
|
414
|
+
|
|
415
|
+
@app.get("/api/admin/modules")
|
|
416
|
+
async def get_all_modules_admin(admin: dict = Depends(get_current_admin)):
|
|
417
|
+
"""Return every module (administrators only)."""
|
|
418
|
+
modules = get_all_modules_from_db()
|
|
419
|
+
return {"modules": modules}
|
|
420
|
+
@app.get("/api/admin/modules/{module_id}")
|
|
421
|
+
async def get_module_admin(module_id: str, admin: dict = Depends(get_current_admin)):
|
|
422
|
+
"""Return a module by id (administrators only)."""
|
|
423
|
+
module = get_module_by_id(module_id)
|
|
424
|
+
if not module:
|
|
425
|
+
raise HTTPException(status_code=404, detail="Module not found")
|
|
426
|
+
return module
|
|
427
|
+
@app.post("/api/admin/modules")
|
|
428
|
+
async def create_module(
|
|
429
|
+
module_data: ModuleCreate,
|
|
430
|
+
admin: dict = Depends(get_current_admin)
|
|
431
|
+
):
|
|
432
|
+
"""Create a module."""
|
|
433
|
+
try:
|
|
434
|
+
create_or_update_module(module_data.dict())
|
|
435
|
+
return {"success": True, "message": "Module created successfully"}
|
|
436
|
+
except Exception as e:
|
|
437
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
438
|
+
@app.put("/api/admin/modules/{module_id}")
|
|
439
|
+
async def update_module(
|
|
440
|
+
module_id: str,
|
|
441
|
+
module_data: ModuleUpdate,
|
|
442
|
+
admin: dict = Depends(get_current_admin)
|
|
443
|
+
):
|
|
444
|
+
"""Update a module."""
|
|
445
|
+
existing = get_module_by_id(module_id)
|
|
446
|
+
if not existing:
|
|
447
|
+
raise HTTPException(status_code=404, detail="Module not found")
|
|
448
|
+
|
|
449
|
+
try:
|
|
450
|
+
update_data = module_data.dict(exclude_unset=True)
|
|
451
|
+
update_data['module_id'] = module_id
|
|
452
|
+
create_or_update_module(update_data)
|
|
453
|
+
return {"success": True, "message": "Module updated successfully"}
|
|
454
|
+
except Exception as e:
|
|
455
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
456
|
+
@app.delete("/api/admin/modules/{module_id}")
|
|
457
|
+
async def delete_module_endpoint(
|
|
458
|
+
module_id: str,
|
|
459
|
+
admin: dict = Depends(get_current_admin)
|
|
460
|
+
):
|
|
461
|
+
"""Delete a module."""
|
|
462
|
+
existing = get_module_by_id(module_id)
|
|
463
|
+
if not existing:
|
|
464
|
+
raise HTTPException(status_code=404, detail="Module not found")
|
|
465
|
+
|
|
466
|
+
delete_module(module_id)
|
|
467
|
+
return {"success": True, "message": "Module deleted successfully"}
|
|
468
|
+
@app.get("/api/admin/role-modules")
|
|
469
|
+
async def get_role_modules(admin: dict = Depends(get_current_admin)):
|
|
470
|
+
"""Return the modules granted to each role."""
|
|
471
|
+
roles_modules = {}
|
|
472
|
+
roles = DatabaseManager.execute_sql('''
|
|
473
|
+
SELECT DISTINCT role_name FROM role_modules WHERE is_active = TRUE
|
|
474
|
+
''')
|
|
475
|
+
|
|
476
|
+
for role in roles:
|
|
477
|
+
modules = get_modules_for_role(role['role_name'])
|
|
478
|
+
roles_modules[role['role_name']] = modules
|
|
479
|
+
|
|
480
|
+
return roles_modules
|
|
481
|
+
@app.post("/api/admin/role-modules")
|
|
482
|
+
async def update_role_modules_endpoint(
|
|
483
|
+
role_data: RoleModulesUpdate,
|
|
484
|
+
admin: dict = Depends(get_current_admin)
|
|
485
|
+
):
|
|
486
|
+
"""Update the modules granted to a role."""
|
|
487
|
+
try:
|
|
488
|
+
update_role_modules(role_data.role_name, role_data.module_ids)
|
|
489
|
+
return {"success": True, "message": "Role modules updated successfully"}
|
|
490
|
+
except Exception as e:
|
|
491
|
+
raise HTTPException(status_code=400, detail=str(e))
|
|
492
|
+
@app.post("/api/admin/modules/import-from-json")
|
|
493
|
+
async def import_modules_from_json_endpoint(admin: dict = Depends(get_current_admin)):
|
|
494
|
+
"""Import the modules from the JSON file."""
|
|
495
|
+
success = import_modules_from_json()
|
|
496
|
+
if success:
|
|
497
|
+
return {"success": True, "message": "Modules imported successfully"}
|
|
498
|
+
else:
|
|
499
|
+
raise HTTPException(status_code=500, detail="Error importing modules")
|
|
500
|
+
@app.post("/api/admin/modules/export-to-json")
|
|
501
|
+
async def export_modules_to_json_endpoint(admin: dict = Depends(get_current_admin)):
|
|
502
|
+
"""Export the modules to the JSON file."""
|
|
503
|
+
try:
|
|
504
|
+
modules = get_all_modules_from_db()
|
|
505
|
+
roles_modules = {}
|
|
506
|
+
roles = DatabaseManager.execute_sql('SELECT DISTINCT role_name FROM role_modules WHERE is_active = TRUE')
|
|
507
|
+
|
|
508
|
+
for role in roles:
|
|
509
|
+
role_modules = get_modules_for_role(role['role_name'])
|
|
510
|
+
roles_modules[role['role_name']] = [module['module_id'] for module in role_modules]
|
|
511
|
+
|
|
512
|
+
export_data = {
|
|
513
|
+
"roles": [
|
|
514
|
+
{
|
|
515
|
+
"name": role_name,
|
|
516
|
+
"modules": module_ids
|
|
517
|
+
}
|
|
518
|
+
for role_name, module_ids in roles_modules.items()
|
|
519
|
+
],
|
|
520
|
+
"modules": [
|
|
521
|
+
{
|
|
522
|
+
"id": module['module_id'],
|
|
523
|
+
"name": module['name'],
|
|
524
|
+
"description": module['description'],
|
|
525
|
+
"js": module['js_path'],
|
|
526
|
+
"css": module['css_path'],
|
|
527
|
+
"initFunction": module['init_function'],
|
|
528
|
+
"version": module['version'],
|
|
529
|
+
"config": json.loads(module['config']) if module['config'] else {}
|
|
530
|
+
}
|
|
531
|
+
for module in modules
|
|
532
|
+
]
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
with open(MODULES_CONFIG_PATH, 'w', encoding='utf-8') as f:
|
|
536
|
+
json.dump(export_data, f, ensure_ascii=False, indent=2)
|
|
537
|
+
|
|
538
|
+
return {"success": True, "message": "Modules exported successfully"}
|
|
539
|
+
except Exception as e:
|
|
540
|
+
logger.error(f"Error exporting modules to JSON: {str(e)}")
|
|
541
|
+
raise HTTPException(status_code=500, detail="Error exporting modules")
|
|
542
|
+
@app.get("/api/modules")
|
|
543
|
+
async def get_modules(current_user: dict = Depends(get_current_user)):
|
|
544
|
+
"""Return the modules available to the current user, from the database."""
|
|
545
|
+
try:
|
|
546
|
+
user_role = current_user['role']
|
|
547
|
+
modules = get_modules_for_role(user_role)
|
|
548
|
+
|
|
549
|
+
if modules:
|
|
550
|
+
formatted_modules = []
|
|
551
|
+
for module in modules:
|
|
552
|
+
formatted_module = {
|
|
553
|
+
"id": module['module_id'],
|
|
554
|
+
"name": module['name'],
|
|
555
|
+
"description": module['description'],
|
|
556
|
+
"js": module['js_path'],
|
|
557
|
+
"css": module['css_path'],
|
|
558
|
+
"initFunction": module['init_function'],
|
|
559
|
+
"version": module['version']
|
|
560
|
+
}
|
|
561
|
+
if module['config']:
|
|
562
|
+
formatted_module["config"] = json.loads(module['config'])
|
|
563
|
+
formatted_modules.append(formatted_module)
|
|
564
|
+
|
|
565
|
+
return {"modules": formatted_modules}
|
|
566
|
+
else:
|
|
567
|
+
logger.warning("No modules found in DB, falling back to JSON file")
|
|
568
|
+
return await get_modules_from_json_fallback(current_user)
|
|
569
|
+
|
|
570
|
+
except Exception as e:
|
|
571
|
+
logger.error(f"Error getting modules from DB: {str(e)}")
|
|
572
|
+
return await get_modules_from_json_fallback(current_user)
|