瀏覽代碼

privileges in db implemented

ash 2 年之前
父節點
當前提交
302cca7099

+ 146 - 0
.gitignore

@@ -11,3 +11,149 @@ Backend/**/venv
 Backend/venv/**
 **/venv
 Backend\venv
+Backend/venv
+Backend/venv/Lib/site-packages/pip/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/__pycache__/build_env.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/__pycache__/cache.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/__pycache__/configuration.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/__pycache__/exceptions.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/__pycache__/pyproject.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/__pycache__/self_outdated_check.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/__pycache__/wheel_builder.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/cli/__pycache__/autocompletion.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/cli/__pycache__/base_command.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/cli/__pycache__/cmdoptions.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/cli/__pycache__/progress_bars.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/cli/__pycache__/req_command.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/commands/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/commands/__pycache__/install.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/commands/__pycache__/list.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/base.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/installed.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/sdist.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/distributions/__pycache__/wheel.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/index/__pycache__/collector.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/index/__pycache__/package_finder.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/locations/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/base.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/metadata/__pycache__/pkg_resources.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/models/__pycache__/candidate.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/models/__pycache__/direct_url.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/models/__pycache__/format_control.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/models/__pycache__/index.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/models/__pycache__/link.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/models/__pycache__/scheme.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/models/__pycache__/search_scope.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/models/__pycache__/selection_prefs.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/models/__pycache__/target_python.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/models/__pycache__/wheel.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/network/__pycache__/auth.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/network/__pycache__/cache.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/network/__pycache__/download.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/network/__pycache__/lazy_wheel.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/network/__pycache__/session.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/operations/__pycache__/check.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/operations/__pycache__/prepare.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata_legacy.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/metadata.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel_legacy.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/operations/build/__pycache__/wheel.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/editable_legacy.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/legacy.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/operations/install/__pycache__/wheel.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/req/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/req/__pycache__/constructors.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_file.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_install.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_set.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_tracker.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/req/__pycache__/req_uninstall.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/resolution/__pycache__/base.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/base.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/appdirs.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/compatibility_tags.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/deprecation.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/direct_url_helpers.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/filetypes.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/glibc.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/hashes.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/inject_securetransport.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/logging.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/misc.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/models.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/packaging.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/setuptools_build.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/subprocess.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/temp_dir.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/unpacking.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/urls.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/virtualenv.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/utils/__pycache__/wheel.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/bazaar.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/git.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/mercurial.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/subversion.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_internal/vcs/__pycache__/versioncontrol.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/adapter.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/cache.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/compat.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/controller.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/serialize.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/certifi/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/compat.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/scripts.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/distlib/__pycache__/util.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/core.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/idnadata.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/intranges.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/idna/__pycache__/package_data.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/_version.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/msgpack/__pycache__/fallback.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/__about__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_musllinux.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/_structures.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/specifiers.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/packaging/__pycache__/tags.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/pep517/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/pep517/__pycache__/compat.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/pep517/__pycache__/wrappers.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/pkg_resources/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/progress/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/progress/__pycache__/bar.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/progress/__pycache__/spinner.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/compat.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/exceptions.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/models.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/sessions.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/requests/__pycache__/utils.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/providers.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/reporters.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/resolvelib/__pycache__/resolvers.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/_version.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/connection.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/urllib3/__pycache__/connectionpool.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/connection.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/proxy.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/retry.cpython-39.pyc
+Backend/venv/Lib/site-packages/pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-39.pyc

+ 1 - 0
Backend/.gitignore

@@ -1,3 +1,4 @@
 venv
 venv/
 venv\
+**/.pyc

+ 3 - 29
Backend/Sources/Model/isp_model.py

@@ -1,4 +1,4 @@
-from sqlalchemy import Sequence, Column, Integer, String,ForeignKey,Boolean
+from sqlalchemy import JSON, Sequence, Column, Integer, String,ForeignKey,Boolean
 
 import persistence
 
@@ -18,8 +18,8 @@ class user_account(__db_Base) :
     description               = Column(String(500))
     password                  = Column(String)
     is_super_admin            = Column(Boolean, default=False)
-    max_simultaneous_conn     = Column(Integer, default=5)
-    privileges_roles_id       = Column(String)
+    custom_data               = Column(JSON)
+    privileges_data           = Column(JSON)
     # for privilege we can use an int in the used as a bitset later for an array of privilege
 
 class user_account_isp_link(__db_Base):
@@ -28,31 +28,5 @@ class user_account_isp_link(__db_Base):
     user_account_id        = Column(Integer, ForeignKey('tUser_accounts.id'))
     isp_id                 = Column(Integer, ForeignKey('tIsp.id'))
     note                   = Column(String(500))
-    isp_privilege_json     = Column(String)
     contact_mail           = Column(String(100))
     contact_number         = Column(String(100))
-
-
-"""
-class user_account_role_link(__db_Base):
-    __tablename__          = 'tUser_account_role_link'
-    link_id                = Column(Integer, Sequence('tUser_account_isp_links_seq'), primary_key=True,nullable=False)
-    user_account_id        = Column(Integer, ForeignKey('tUser_accounts.id'))
-    role_id                = Column(Integer, ForeignKey('tPrivilege_Role_Storage.id'))
-
-class Privilege_Role_Storage(__db_Base) :
-    __tablename__       = 'tPrivilege_Role_Storage'
-    id                  = Column(Integer, Sequence('Privilege_Role_Storage_seq'), primary_key=True,nullable=False)
-    name                = Column(String(50))
-    description         = Column(String(500))
-    exclusive           = Column(Boolean,default=False)
-    domain_id           = Column(Integer, ForeignKey('tPrivilege_Domain_Storage.id'), primary_key=True)
-    aggregated_roles_id = Column(String)
-
-
-class Privilege_Domain_Storage(__db_Base) :
-    __tablename__ = 'tPrivilege_Domain_Storage'
-    id                        = Column(Integer, Sequence('Privilege_Domain_Storage_seq'), primary_key=True,nullable=False)
-    name                      = Column(String(50), primary_key=True, nullable=False)
-    description               = Column(String(500))
-"""

+ 4 - 4
Backend/Sources/Model/model_manager.py

@@ -37,7 +37,7 @@ def init() :
 
 
 # from https://stackoverflow.com/questions/5022066/how-to-serialize-sqlalchemy-result-to-json
-class JsonAlchemyEncoder(json.JSONEncoder):
+class ComplexEncoder(json.JSONEncoder):
 
     def default(self, obj):
         if isinstance(obj.__class__, DeclarativeMeta):
@@ -60,7 +60,7 @@ class JsonAlchemyEncoder(json.JSONEncoder):
 # from https://howtodoinjava.com/json/custom-deserialization/
 
 
-class JsonAlchemyDecoder(json.JSONDecoder):
+class ComplexDecoder(json.JSONDecoder):
     def __init__(self):
         json.JSONDecoder.__init__(
             self,
@@ -87,7 +87,7 @@ def setModelItemAttributesFromJson(Item, JsonString):
     attributes_dict = null
     try:
         attributes_dict = json.loads(
-            JsonString, cls=JsonAlchemyDecoder)
+            JsonString, cls=ComplexDecoder)
     except:
         raise "input is not a Json String"
 
@@ -106,4 +106,4 @@ def setModelItemAttributesFromJson(Item, JsonString):
 
 def ModelObjectToJsonString(object):
 
-    return json.dumps(object, cls=JsonAlchemyEncoder)
+    return json.dumps(object, cls=ComplexEncoder)

+ 2 - 2
Backend/Sources/View/view_error_management.py

@@ -15,8 +15,8 @@ def define_error_management(app) :
         return jsonify(response), 500
 
     @app.errorhandler(privileges.PrivilegeError)
-    def handle_error(err) :
+    def handle_privilege_error(err) :
         """Return JSON instead of HTML for any other server error"""
-        logger.error(f"APIAuthError Exception: {str(err)}")
+        logger.error(f"PrivilegeError Exception: {str(err)}")
         response = {"error": str(err) }
         return jsonify(response), 500

+ 17 - 8
Backend/Sources/View/view_manager.py

@@ -12,6 +12,8 @@ import View.view_privilege as privileges
 import Modules.Inventory.inventory_view as inventory_view
 from datetime import timedelta
 import View.view_error_management as view_error_management
+from flask_limiter import Limiter
+from flask_limiter.util import get_remote_address
 logger = logging.getLogger(logger_name + ".VIEW")
 
 
@@ -25,6 +27,8 @@ __resource_array__ : array
 __id_counter__ : int = 1
 
 
+limiter = Limiter(__app__,key_func=get_remote_address,default_limits=["500 per minute"])
+limiter.logger = logger
 
 
 from werkzeug.serving import make_server
@@ -45,17 +49,23 @@ class ServerThread(threading.Thread):
 
 __server_process__ : ServerThread
 
-def get_roles_ids() :
-    return session["roles_ids"]
+def get_user_privilege() :
+    return privileges.get_privileges_from_user(session["user_account_id"])
 
 
 def init() :
 
     @__app__.before_request
     def before_request_func():
-        print(request.headers.__dict__)
+
         global __id_counter__
-        logger.debug("before_request is running!")
+        logger.debug("before_request processing")
+        logger.debug("request from " + request.remote_addr)
+        logger.debug("request header" + str(request.headers.__dict__))
+
+        logger.debug("request body" + request.json)
+
+
         if not "client_id" in session :
             session["client_id"] = str(__id_counter__)
         logger.debug("client_id is " + session["client_id"])
@@ -107,8 +117,7 @@ def login():
 
 
         session["username"] = _username
-        session["account_data"] = model_manager.ModelObjectToJsonString(Item)
-        session["roles_ids"] = [inventory_view.inventory_read_only_role.id]
+        session["user_account_id"] = Item.id
         logger.info("account " + _username + " logged IN successfully with id : " + session["client_id"])
         resp = jsonify({'message' : 'login successful'})
         resp.status_code = 200
@@ -123,7 +132,7 @@ def logout():
 
 
 @__app__.route('/routes',methods = ['GET'])
-@privileges.manager.require_authorization(required_role=inventory_view.inventory_admin_role,ids_getter=get_roles_ids)
+@privileges.manager.require_authorization(required_role=inventory_view.inventory_admin_role,get_privilege_func=get_user_privilege)
 def routes():
     routes = []
     for route in __app__.url_map.iter_rules():
@@ -149,7 +158,7 @@ def stop() :
 def add_blueprint(blueprint : flask.Blueprint) :
     __app__.register_blueprint(blueprint)
 
-@privileges.manager.require_authorization(required_role=inventory_view.inventory_read_only_role,ids_getter=get_roles_ids)
+@privileges.manager.require_authorization(required_role=inventory_view.inventory_read_only_role,get_privilege_func=get_user_privilege)
 def tab():
     return jsonify([2,5,7])
 

+ 31 - 2
Backend/Sources/View/view_privilege.py

@@ -1,14 +1,43 @@
 from utility.privilege_manager import *
 import Modules.Inventory.inventory_view as inventory_view
+import persistence
+from Model.isp_model import user_account
 
 manager = Privilege_Manager()
+privileges_users : set[ Privilege_Manager.Privilege_User] = set()
+
 
 def init() :
     inventory_view.init()
+    load_privilege_data()
 
 
 
 
-
-def populate_manager() :
+def save_privilege_data() :
     None
+
+def load_privilege_data() :
+    with persistence.get_Session_Instance() as sess :
+        users = sess.query(user_account)
+
+        user : user_account
+        for user in users :
+            privileges = Privilege_Manager.Privilege_User(manager,user.privileges_data,user.is_super_admin,user.id)
+            privileges_users.add(privileges)
+            logger.debug("user privilege for account : " + user.nickname + " with id " + str(user.id) + " parsed")
+            roles_string : list[str] = list()
+            for role in privileges.get_roles() :
+                roles_string.append(manager.get_role_domain(role) + ' : ' + role.name)
+            logger.debug("roles found : " + str(roles_string))
+
+
+def get_privileges_from_user(user_id : int) :
+    for user in privileges_users :
+        if user.id == user_id :
+            return user
+
+    raise Exception("user privileges not found with id " + str(user_id))
+
+
+#TODO flask blueprint for privilege management here

+ 65 - 6
Backend/Sources/utility/privilege_manager.py

@@ -1,5 +1,7 @@
 from __future__ import annotations
-import functools
+import json
+
+from itsdangerous import json
 __id_counter__ = 0
 
 def __generate_id__() :
@@ -156,15 +158,56 @@ class Privilege_Domain :
 
 
 
+class Privilege_Manager :
 
+    class Privilege_User :
 
-class Privilege_Manager :
+        def __init__(self,manager : Privilege_Manager, privileges_data_str : str,is_super_admin : bool = False,id : int = None) -> None:
 
+            if not id :
+                self.__id__ = __generate_id__()
+            else :
+                self.__id__ = id
+
+            self.is_super_admin : bool = is_super_admin
+            self.manager = manager
+
+
+            self.roles : set[Privilege_Role] = set()
+
+            if privileges_data_str :
+                privileges_data : dict = json.load(privileges_data_str)
+
+
+                for key in privileges_data.keys() :
+                    self.roles.add(manager.get_role_by_domain_and_name(key,privileges_data[key]))
+
+
+        def get_roles(self) -> set[Privilege_Role]:
+            return self.roles
+
+        def roles_to_jsonStr(self) -> str :
+            ret_dict = dict()
+            for role in self.roles :
+                domain = self.manager.get_role_domain(role)
+
+                ret_dict[domain.name] = role.name
+
+            return json.dump(json.load(ret_dict))
+
+        @property
+        def id(self):
+            return self.__id__
 
 
-    __domains__ :  set[Privilege_Domain] = set()
 
 
+
+
+
+    __domains__ :  set[Privilege_Domain] = set()
+    __users__   :  set[Privilege_User] = set()
+
     def create_domain(self, name : str, description : str = None) :
         for item in self.__domains__ :
             if item.name == name :
@@ -266,8 +309,9 @@ class Privilege_Manager :
 
         return ret
 
+
     #its a DECORATOR
-    def require_authorization(self,required_role : Privilege_Role, ids_getter : callable) :
+    def require_authorization(self,required_role : Privilege_Role, get_privilege_func : callable) :
 
         def wrapper_of_wrap(f) :
             def wrap(*args, **kwargs):
@@ -275,11 +319,18 @@ class Privilege_Manager :
                     raise BaseException("role is not registered anywhere")
                 logger.debug("checking authorization with roles for function " + f.__name__ + ": " )
                 logger.debug("required role :  " + required_role.name )
-                for role in self.get_roles_by_ids(ids_getter()) : #an user can have multiple roles and each role can include other roles.
+                privileges : Privilege_Manager.Privilege_User = get_privilege_func()
+
+                if privileges.is_super_admin :
+                    logger.debug("user is super admin, access granted")
+                    return f(*args, **kwargs)
+
+                for role in privileges.roles : #an user can have multiple roles and each role can include other roles.
                     logger.debug("checking role : " + role.name)
                     for aggregated_role in role.aggregated_roles :
 
                         if aggregated_role == required_role :
+                            logger.debug("access granted")
                             return f(*args, **kwargs)
 
                 def raiser(*args, **kwargs):
@@ -358,6 +409,7 @@ def test() :
 
     try :
         hello_admin(23,45)
+        return False
     except Exception as Ex:
         print(str(Ex))
 
@@ -367,8 +419,15 @@ def test() :
     hello_admin(23,45)
 
     hello_intermediate()
-    hello_speciale()
 
 
+    try :
+        hello_speciale()
+        return False
+    except Exception as Ex:
+        print(str(Ex))
+
+    return True
+
 if __name__ == "__main__" :
     test()

+ 4 - 2
Backend/Tests/privilege_test.py

@@ -4,7 +4,9 @@ import sys
 sys.path.append("..")
 sys.path.append("..\\Sources")
 import Sources.utility.privilege_manager as priv
-
+import Sources.main as main
 
 def test_privilege_manager() :
-    priv.test()
+    main.init()
+    if not priv.test() :
+        raise Exception()