Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/permissions available2 #236

Merged
merged 6 commits into from
Jul 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 12 additions & 29 deletions backend/gn_module_monitoring/command/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

from .utils import (
process_export_csv,
insert_permission_object,
process_available_permissions,
remove_monitoring_module,
add_nomenclature,
available_modules,
Expand Down Expand Up @@ -134,10 +134,8 @@ def cmd_install_monitoring_module(module_code):
DB.session.add(module)
DB.session.commit()

# Insert permission object
if config["module"].get("permission_objects"):
id_module = module.id_module
insert_permission_object(id_module, config["module"].get("permission_objects"))
# Ajouter les permissions disponibles
process_available_permissions(module_code)

#  run specific sql
if (module_config_dir_path / "synthese.sql").exists:
Expand Down Expand Up @@ -181,10 +179,10 @@ def cmd_install_monitoring_module(module_code):
return


@click.command("update_permission_objects")
@click.argument("module_code")
@click.command("update_module_available_permissions")
@click.argument("module_code", required=False, default="")
@with_appcontext
def cmd_update_perm_module_cmd(module_code):
def cmd_process_available_permission_module(module_code):
"""
Mise à jour (uniquement insertion) des objets permissions associés au module
Défini par le paramètre permission_objects du fichier module.json
Expand All @@ -193,28 +191,13 @@ def cmd_update_perm_module_cmd(module_code):
module_code ([string]): code du sous module

"""
try:
module = get_module("module_code", module_code)
except Exception:
print("le module n'existe pas")
return
path_module = monitoring_module_config_path(module_code) / "module.json"

if not path_module.is_file():
print(f"Il n'y a pas de fichier {path_module} pour ce module")
return
config_module = json_from_file(path_module, None)
if not config_module:
print("Il y a un problème avec le fichier {}".format(path_module))
return
if module_code:
return process_available_permissions(module_code)

for module in installed_modules():
process_available_permissions(module['module_code'])

print(f"Insertion des objets de permissions pour le module {module_code}")
# Insert permission object
if "permission_objects" in config_module:
id_module = module.id_module
insert_permission_object(id_module, config_module["permission_objects"])
else:
print("no permission")


@click.command("remove")
Expand Down Expand Up @@ -264,7 +247,7 @@ def synchronize_synthese(module_code, offset):
commands = [
cmd_process_export_csv,
cmd_install_monitoring_module,
cmd_update_perm_module_cmd,
cmd_process_available_permission_module,
cmd_remove_monitoring_module_cmd,
cmd_add_module_nomenclature_cli,
cmd_process_all,
Expand Down
132 changes: 86 additions & 46 deletions backend/gn_module_monitoring/command/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
from sqlalchemy.orm.exc import NoResultFound

from geonature.utils.env import DB, BACKEND_DIR
from geonature.core.gn_permissions.models import TObjects
from geonature.core.gn_permissions.models import PermObject
from geonature.core.gn_commons.models import TModules

from pypnnomenclature.models import TNomenclatures, BibNomenclaturesTypes

Expand All @@ -15,8 +16,9 @@
SUB_MODULE_CONFIG_DIR
)

from ..modules.repositories import get_module, get_source_by_code, get_modules
from ..config.repositories import get_config

from ..modules.repositories import get_module, get_source_by_code, get_modules

'''
utils.py
Expand All @@ -34,7 +36,8 @@ def process_for_all_module(process_func):
process_func(module.module_code)
return


def getMonitoringPermissionObjectLabel_dict():
return __import__('gn_module_monitoring').monitoring.definitions.MonitoringPermissionObjectLabel_dict

def process_export_csv(module_code=None):
'''
Expand Down Expand Up @@ -71,41 +74,80 @@ def process_export_csv(module_code=None):
print('{} - export csv erreur dans le script {} : {}'.format(module_code, f ,e))


def insert_permission_object(id_module, permissions):
""" Insertion de l'association permission object
def process_available_permissions(module_code):
try:
module = get_module("module_code", module_code)
except Exception:
print("le module n'existe pas")
return

Args:
id_module ([type]): id du module
permissions ([type]): liste des permissions à associer au module
config = get_config(module_code, force=True)
if not config:
print(f"Il y a un problème de configuration pour le module {module_code}")
return

Raises:
e: [description]
"""
for perm in permissions:
print(f"Insert perm {perm}")
# load object
try:
object = DB.session.query(TObjects).filter(TObjects.code_object == perm).one()
# save
txt = ("""
INSERT INTO gn_permissions.cor_object_module (id_module, id_object)
VALUES ({id_module}, {id_object})
""".format(
id_module=id_module,
id_object=object.id_object
)
)
try:
DB.engine.execution_options(autocommit=True).execute(txt)
print(f" Ok")
except IntegrityError:
DB.session.rollback()
print(f" Impossible d'insérer la permission {perm} pour des raisons d'intégrités")
except NoResultFound as e:
print(f" Permission {perm} does'nt exists")
except Exception as e:
print(f" Impossible d'insérer la permission {perm} :{e}")
insert_module_available_permissions(module_code, "ALL")

# Insert permission object
for permission_object_code in config.get("permission_objects", []):
insert_module_available_permissions(module_code, permission_object_code)


def insert_module_available_permissions(module_code, perm_object_code):
print(f'process permissions for (module_code, perm_object)= ({module_code},{perm_object_code})')

object_label = getMonitoringPermissionObjectLabel_dict().get(perm_object_code)

if not object_label:
print(f"L'object {perm_object_code} n'est pas traité")

try:
module = TModules.query.filter_by(module_code=module_code).one()
except NoResultFound:
print("Le module {module_code} n'est pas présent")
return

try:
perm_object = PermObject.query.filter_by(code_object=perm_object_code).one()
except NoResultFound:
print("L'object de permission {module_code} n'est pas présent")
return

txt_cor_object_module = f"""
INSERT INTO gn_permissions.cor_object_module(
id_module,
id_object
)
VALUES({module.id_module}, {perm_object.id_object})
ON CONFLICT DO NOTHING
"""
DB.engine.execution_options(autocommit=True).execute(txt_cor_object_module)

txt_perm_available = (f"""
INSERT INTO gn_permissions.t_permissions_available (
id_module,
id_object,
id_action,
label,
scope_filter)
SELECT
{module.id_module},
{perm_object.id_object},
a.id_action,
v.label,
true
FROM
( VALUES
('C', 'Créer des {object_label}'),
('R', 'Voir les {object_label}'),
('U', 'Modifier les {object_label}'),
('D', 'Supprimer des {object_label}'),
('E', 'Exporter les {object_label}')
) AS v (action_code, label)
JOIN gn_permissions.bib_actions a ON v.action_code = a.code_action
ON CONFLICT DO NOTHING
""")
DB.engine.execution_options(autocommit=True).execute(txt_perm_available)

def remove_monitoring_module(module_code):
try:
Expand All @@ -116,20 +158,18 @@ def remove_monitoring_module(module_code):

# remove module in db
try:
# HACK pour le moment suprresion avec un sql direct
# Car il y a un soucis de delete cascade dans les modèles sqlalchemy
txt = ("""
DELETE FROM gn_commons.t_modules WHERE id_module ={}
""".format(
module.id_module
)
)
# suppression des permissions disponibles pour ce module
txt = f"DELETE FROM gn_permissions.t_permissions_available WHERE id_module = {module.id_module}"
DB.engine.execution_options(autocommit=True).execute(txt)

# HACK pour le moment suppresion avec un sql direct
# Car il y a un soucis de delete cascade dans les modèles sqlalchemy
txt = f"""DELETE FROM gn_commons.t_modules WHERE id_module ={module.id_module}"""
DB.engine.execution_options(autocommit=True).execute(txt)
except IntegrityError:
print("Impossible de supprimer le module car il y a des données associées")
return
except Exception:
except Exception as e:
print("Impossible de supprimer le module")
raise(e)

Expand All @@ -141,7 +181,7 @@ def remove_monitoring_module(module_code):
DB.session.commit()
except Exception as e:
print("Impossible de supprimer la source {}".format(str(e)))
return
# return
# run specific sql TODO
# remove nomenclature TODO
return
Expand Down Expand Up @@ -262,4 +302,4 @@ def available_modules():
module = json_from_file(module_file)
available_modules_.append({**module, 'module_code': d})
break
return available_modules_
return available_modules_
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def upgrade():
FROM
(
VALUES
('MONITORINGS', 'ALL', 'R', False, 'Accéder à monitoring')
('MONITORINGS', 'ALL', 'R', False, 'Accéder au module')
) AS v (module_code, object_code, action_code, scope_filter, label)
JOIN
gn_commons.t_modules m ON m.module_code = v.module_code
Expand Down Expand Up @@ -76,6 +76,15 @@ def upgrade():
"""
)

op.execute("""
INSERT INTO gn_permissions.t_objects (code_object, description_object)
VALUES
('GNM_MODULES', 'Permissions sur les modules')
ON CONFLICT DO NOTHING
;
"""
)


def downgrade():
op.execute(
Expand Down
13 changes: 12 additions & 1 deletion backend/gn_module_monitoring/monitoring/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,18 @@
'site': "GNM_SITES",
'sites_group': "GNM_GRP_SITES",
'visite': "GNM_VISITES",
'observation': "GNM_OBSERVATIONS"
'observation': "GNM_OBSERVATIONS",
'module': "GNM_MODULES"
}

MonitoringPermissionObjectLabel_dict = {
'ALL': 'objects (sites, visites, observations, etc...)',
'GNM_SITES': 'sites',
'GNM_OBSERVATIONS': 'observations',
'GNM_VISITES': 'visites',
'GNM_GRP_SITES': 'groupes de sites',
'GNM_MODULES': 'modules'
}


monitoring_definitions.set(MonitoringObjects_dict, MonitoringModels_dict)
2 changes: 1 addition & 1 deletion backend/gn_module_monitoring/monitoring/repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def get(self, value=None, field_name=None, depth=0):
return self

except Exception as e:
raise GeoNatureError('MONITORING : get_object : {}'.format(e))
raise GeoNatureError(f'MONITORING : get_object {self._module_code} {self._object_type} ({field_name}={value}) : {e}')

def process_post_data_properties(self, post_data):

Expand Down
9 changes: 0 additions & 9 deletions backend/gn_module_monitoring/monitoring/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,15 +156,6 @@ def serialize(self, depth=1):
'id': self._id,
}

if self._object_type == 'module':
monitoring_object_dict['cruved'] = get_scopes_by_action(module_code=self._module_code)
monitoring_object_dict['cruved_objects'] = {}
monitoring_object_dict['cruved_objects']['site'] = get_scopes_by_action(module_code=self._module_code, object_code="GNM_SITES")
monitoring_object_dict['cruved_objects']['sites_group'] = get_scopes_by_action(module_code=self._module_code, object_code="GNM_GRP_SITES")
monitoring_object_dict['cruved_objects']['visite'] = get_scopes_by_action(module_code=self._module_code, object_code="GNM_VISITES")
monitoring_object_dict['cruved_objects']['observation'] = get_scopes_by_action(module_code=self._module_code, object_code="GNM_OBSERVATIONS")


properties['id_parent'] = to_int(self.id_parent())
if(children):
monitoring_object_dict['children'] = children
Expand Down
Loading