248 lines
9.3 KiB
Python
248 lines
9.3 KiB
Python
# Copyright (c) 2025 Patrick Motsch
|
|
# All rights reserved.
|
|
"""
|
|
CodeEditor Feature Container - Main Module.
|
|
Handles feature initialization and RBAC catalog registration.
|
|
Cursor-style AI file editing via chat interface.
|
|
"""
|
|
|
|
import logging
|
|
from typing import Dict, List, Any
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
FEATURE_CODE = "codeeditor"
|
|
FEATURE_LABEL = {"en": "Code Editor", "de": "Code Editor", "fr": "Code Editor"}
|
|
FEATURE_ICON = "mdi-file-document-edit"
|
|
|
|
UI_OBJECTS = [
|
|
{
|
|
"objectKey": "ui.feature.codeeditor.editor",
|
|
"label": {"en": "Editor", "de": "Editor", "fr": "Editeur"},
|
|
"meta": {"area": "editor"}
|
|
},
|
|
{
|
|
"objectKey": "ui.feature.codeeditor.workflows",
|
|
"label": {"en": "Workflows", "de": "Workflows", "fr": "Workflows"},
|
|
"meta": {"area": "workflows"}
|
|
},
|
|
]
|
|
|
|
RESOURCE_OBJECTS = [
|
|
{
|
|
"objectKey": "resource.feature.codeeditor.start",
|
|
"label": {"en": "Start Workflow", "de": "Workflow starten", "fr": "Demarrer workflow"},
|
|
"meta": {"endpoint": "/api/codeeditor/{instanceId}/start/stream", "method": "POST"}
|
|
},
|
|
{
|
|
"objectKey": "resource.feature.codeeditor.stop",
|
|
"label": {"en": "Stop Workflow", "de": "Workflow stoppen", "fr": "Arreter workflow"},
|
|
"meta": {"endpoint": "/api/codeeditor/{instanceId}/{workflowId}/stop", "method": "POST"}
|
|
},
|
|
{
|
|
"objectKey": "resource.feature.codeeditor.chatData",
|
|
"label": {"en": "Get Chat Data", "de": "Chat-Daten abrufen", "fr": "Recuperer donnees chat"},
|
|
"meta": {"endpoint": "/api/codeeditor/{instanceId}/{workflowId}/chatData", "method": "GET"}
|
|
},
|
|
{
|
|
"objectKey": "resource.feature.codeeditor.files",
|
|
"label": {"en": "Manage Files", "de": "Dateien verwalten", "fr": "Gerer fichiers"},
|
|
"meta": {"endpoint": "/api/codeeditor/{instanceId}/files", "method": "GET"}
|
|
},
|
|
{
|
|
"objectKey": "resource.feature.codeeditor.apply",
|
|
"label": {"en": "Apply Edit", "de": "Aenderung anwenden", "fr": "Appliquer modification"},
|
|
"meta": {"endpoint": "/api/codeeditor/{instanceId}/{workflowId}/apply", "method": "POST"}
|
|
},
|
|
]
|
|
|
|
TEMPLATE_ROLES = [
|
|
{
|
|
"roleLabel": "codeeditor-viewer",
|
|
"description": {
|
|
"en": "Code Editor Viewer - View editor (read-only)",
|
|
"de": "Code Editor Betrachter - Editor ansehen (nur lesen)",
|
|
"fr": "Visualiseur Code Editor - Consulter l'editeur (lecture seule)"
|
|
},
|
|
"accessRules": [
|
|
{"context": "UI", "item": "ui.feature.codeeditor.editor", "view": True},
|
|
{"context": "DATA", "item": None, "view": True, "read": "m", "create": "n", "update": "n", "delete": "n"},
|
|
]
|
|
},
|
|
{
|
|
"roleLabel": "codeeditor-user",
|
|
"description": {
|
|
"en": "Code Editor User - Use editor and workflows",
|
|
"de": "Code Editor Benutzer - Editor und Workflows nutzen",
|
|
"fr": "Utilisateur Code Editor - Utiliser l'editeur et les workflows"
|
|
},
|
|
"accessRules": [
|
|
{"context": "UI", "item": "ui.feature.codeeditor.editor", "view": True},
|
|
{"context": "UI", "item": "ui.feature.codeeditor.workflows", "view": True},
|
|
{"context": "RESOURCE", "item": "resource.feature.codeeditor.start", "view": True},
|
|
{"context": "RESOURCE", "item": "resource.feature.codeeditor.stop", "view": True},
|
|
{"context": "RESOURCE", "item": "resource.feature.codeeditor.chatData", "view": True},
|
|
{"context": "RESOURCE", "item": "resource.feature.codeeditor.files", "view": True},
|
|
{"context": "RESOURCE", "item": "resource.feature.codeeditor.apply", "view": True},
|
|
{"context": "DATA", "item": None, "view": True, "read": "m", "create": "m", "update": "m", "delete": "m"},
|
|
]
|
|
},
|
|
{
|
|
"roleLabel": "codeeditor-admin",
|
|
"description": {
|
|
"en": "Code Editor Admin - Full access to code editor",
|
|
"de": "Code Editor Admin - Vollzugriff auf Code Editor",
|
|
"fr": "Administrateur Code Editor - Acces complet au code editor"
|
|
},
|
|
"accessRules": [
|
|
{"context": "UI", "item": None, "view": True},
|
|
{"context": "RESOURCE", "item": None, "view": True},
|
|
{"context": "DATA", "item": None, "view": True, "read": "a", "create": "a", "update": "a", "delete": "a"},
|
|
]
|
|
},
|
|
]
|
|
|
|
|
|
def getFeatureDefinition() -> Dict[str, Any]:
|
|
"""Return the feature definition for registration."""
|
|
return {
|
|
"code": FEATURE_CODE,
|
|
"label": FEATURE_LABEL,
|
|
"icon": FEATURE_ICON,
|
|
"autoCreateInstance": True,
|
|
}
|
|
|
|
|
|
def getUiObjects() -> List[Dict[str, Any]]:
|
|
"""Return UI objects for RBAC catalog registration."""
|
|
return UI_OBJECTS
|
|
|
|
|
|
def getResourceObjects() -> List[Dict[str, Any]]:
|
|
"""Return resource objects for RBAC catalog registration."""
|
|
return RESOURCE_OBJECTS
|
|
|
|
|
|
def getTemplateRoles() -> List[Dict[str, Any]]:
|
|
"""Return template roles for this feature."""
|
|
return TEMPLATE_ROLES
|
|
|
|
|
|
def registerFeature(catalogService) -> bool:
|
|
"""Register this feature's RBAC objects in the catalog."""
|
|
try:
|
|
for uiObj in UI_OBJECTS:
|
|
catalogService.registerUiObject(
|
|
featureCode=FEATURE_CODE,
|
|
objectKey=uiObj["objectKey"],
|
|
label=uiObj["label"],
|
|
meta=uiObj.get("meta")
|
|
)
|
|
|
|
for resObj in RESOURCE_OBJECTS:
|
|
catalogService.registerResourceObject(
|
|
featureCode=FEATURE_CODE,
|
|
objectKey=resObj["objectKey"],
|
|
label=resObj["label"],
|
|
meta=resObj.get("meta")
|
|
)
|
|
|
|
_syncTemplateRolesToDb()
|
|
|
|
logger.info(f"Feature '{FEATURE_CODE}' registered {len(UI_OBJECTS)} UI objects and {len(RESOURCE_OBJECTS)} resource objects")
|
|
return True
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to register feature '{FEATURE_CODE}': {e}")
|
|
return False
|
|
|
|
|
|
def _syncTemplateRolesToDb() -> int:
|
|
"""Sync template roles and their AccessRules to the database."""
|
|
try:
|
|
from modules.interfaces.interfaceDbApp import getRootInterface
|
|
from modules.datamodels.datamodelRbac import Role, AccessRule, AccessRuleContext
|
|
|
|
rootInterface = getRootInterface()
|
|
|
|
existingRoles = rootInterface.getRolesByFeatureCode(FEATURE_CODE)
|
|
templateRoles = [r for r in existingRoles if r.mandateId is None]
|
|
existingRoleLabels = {r.roleLabel: str(r.id) for r in templateRoles}
|
|
|
|
createdCount = 0
|
|
for roleTemplate in TEMPLATE_ROLES:
|
|
roleLabel = roleTemplate["roleLabel"]
|
|
|
|
if roleLabel in existingRoleLabels:
|
|
roleId = existingRoleLabels[roleLabel]
|
|
_ensureAccessRulesForRole(rootInterface, roleId, roleTemplate.get("accessRules", []))
|
|
else:
|
|
newRole = Role(
|
|
roleLabel=roleLabel,
|
|
description=roleTemplate.get("description", {}),
|
|
featureCode=FEATURE_CODE,
|
|
mandateId=None,
|
|
featureInstanceId=None,
|
|
isSystemRole=False
|
|
)
|
|
createdRole = rootInterface.db.recordCreate(Role, newRole.model_dump())
|
|
roleId = createdRole.get("id")
|
|
_ensureAccessRulesForRole(rootInterface, roleId, roleTemplate.get("accessRules", []))
|
|
logger.info(f"Created template role '{roleLabel}' with ID {roleId}")
|
|
createdCount += 1
|
|
|
|
if createdCount > 0:
|
|
logger.info(f"Feature '{FEATURE_CODE}': Created {createdCount} template roles")
|
|
|
|
return createdCount
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error syncing template roles for feature '{FEATURE_CODE}': {e}")
|
|
return 0
|
|
|
|
|
|
def _ensureAccessRulesForRole(rootInterface, roleId: str, ruleTemplates: List[Dict[str, Any]]) -> int:
|
|
"""Ensure AccessRules exist for a role based on templates."""
|
|
from modules.datamodels.datamodelRbac import AccessRule, AccessRuleContext
|
|
|
|
existingRules = rootInterface.getAccessRulesByRole(roleId)
|
|
existingSignatures = set()
|
|
for rule in existingRules:
|
|
sig = (rule.context.value if rule.context else None, rule.item)
|
|
existingSignatures.add(sig)
|
|
|
|
createdCount = 0
|
|
for template in ruleTemplates:
|
|
context = template.get("context", "UI")
|
|
item = template.get("item")
|
|
sig = (context, item)
|
|
|
|
if sig in existingSignatures:
|
|
continue
|
|
|
|
if context == "UI":
|
|
contextEnum = AccessRuleContext.UI
|
|
elif context == "DATA":
|
|
contextEnum = AccessRuleContext.DATA
|
|
elif context == "RESOURCE":
|
|
contextEnum = AccessRuleContext.RESOURCE
|
|
else:
|
|
contextEnum = context
|
|
|
|
newRule = AccessRule(
|
|
roleId=roleId,
|
|
context=contextEnum,
|
|
item=item,
|
|
view=template.get("view", False),
|
|
read=template.get("read"),
|
|
create=template.get("create"),
|
|
update=template.get("update"),
|
|
delete=template.get("delete"),
|
|
)
|
|
rootInterface.db.recordCreate(AccessRule, newRule.model_dump())
|
|
createdCount += 1
|
|
|
|
if createdCount > 0:
|
|
logger.debug(f"Created {createdCount} AccessRules for role {roleId}")
|
|
|
|
return createdCount
|