Browse Source

view module structure in progress

ash 2 years ago
parent
commit
a7b353fbd0

+ 17 - 0
Backend/Sources/Modules/Inventory/inventory_view.py

@@ -0,0 +1,17 @@
+import View.view_privilege as view_privilege
+from utility.privilege_manager import *
+
+
+inventory_read_only_role  = Privilege_Role(name="read_only")
+inventory_admin_role      = Privilege_Role(name="admin")
+
+
+
+def init():
+
+    view_privilege.manager.create_domain(name="inventory",description="privilege domain for inventory")
+
+    inventory_privilege_domain = view_privilege.manager.get_domain_by_name("inventory")
+    inventory_privilege_domain.add_role(inventory_read_only_role)
+    inventory_privilege_domain.add_role(inventory_admin_role)
+    inventory_privilege_domain.include_role(inventory_admin_role,inventory_read_only_role)

+ 16 - 84
Backend/Sources/View/view_manager.py

@@ -1,25 +1,16 @@
 from array import array
 from array import array
-from msilib.schema import Class
-from re import I
 import threading
 import threading
-from tkinter.ttk import Separator
-from typing import Type
-from xmlrpc.client import boolean
 from flask import session,Flask,request, jsonify
 from flask import session,Flask,request, jsonify
-from flask_restful import Resource, Api
-import flask_restful
-from itsdangerous import json
-from sqlalchemy import delete
+import flask
 from utility.app_logging import logger_name
 from utility.app_logging import logger_name
 import logging
 import logging
 import persistence
 import persistence
 import Model.isp_model as isp_model
 import Model.isp_model as isp_model
 import Model.model_manager as model_manager
 import Model.model_manager as model_manager
 from werkzeug.security import check_password_hash
 from werkzeug.security import check_password_hash
-import anytree
 import View.view_privilege as privileges
 import View.view_privilege as privileges
+import Modules.Inventory.inventory_view as inventory_view
 from datetime import timedelta
 from datetime import timedelta
-from flask_session import Session
 import View.view_error_management as view_error_management
 import View.view_error_management as view_error_management
 logger = logging.getLogger(logger_name + ".VIEW")
 logger = logging.getLogger(logger_name + ".VIEW")
 
 
@@ -28,13 +19,9 @@ logger = logging.getLogger(logger_name + ".VIEW")
 __app__ = Flask("OpenIsp")
 __app__ = Flask("OpenIsp")
 __app__.secret_key = "aseqzdwxc"
 __app__.secret_key = "aseqzdwxc"
 __app__.permanent_session_lifetime = timedelta(minutes=2)
 __app__.permanent_session_lifetime = timedelta(minutes=2)
-__app__.config["SESSION_PERMANENT"] = False
-__app__.config["SESSION_TYPE"] = "filesystem"
 
 
 
 
 __resource_array__ : array
 __resource_array__ : array
-
-
 __id_counter__ : int = 1
 __id_counter__ : int = 1
 
 
 
 
@@ -87,13 +74,13 @@ def init() :
 
 
 
 
 
 
+    privileges.init()
 
 
+    view_error_management.define_error_management(__app__)
     from flask.logging import default_handler
     from flask.logging import default_handler
     __app__.logger.removeHandler(default_handler)
     __app__.logger.removeHandler(default_handler)
-
-
-    privileges.init()
-    view_error_management.define_error_management(__app__)
+    for hand in logger.handlers :
+        __app__.logger.addHandler(hand)
 
 
 @__app__.route('/api/login',methods = ['POST'])
 @__app__.route('/api/login',methods = ['POST'])
 def login():
 def login():
@@ -121,7 +108,7 @@ def login():
 
 
         session["username"] = _username
         session["username"] = _username
         session["account_data"] = model_manager.ModelObjectToJsonString(Item)
         session["account_data"] = model_manager.ModelObjectToJsonString(Item)
-        session["roles_ids"] = [privileges.inventory_read_only_role.id]
+        session["roles_ids"] = [inventory_view.inventory_read_only_role.id]
         logger.info("account " + _username + " logged IN successfully with id : " + session["client_id"])
         logger.info("account " + _username + " logged IN successfully with id : " + session["client_id"])
         resp = jsonify({'message' : 'login successful'})
         resp = jsonify({'message' : 'login successful'})
         resp.status_code = 200
         resp.status_code = 200
@@ -136,13 +123,15 @@ def logout():
 
 
 
 
 @__app__.route('/routes',methods = ['GET'])
 @__app__.route('/routes',methods = ['GET'])
-@privileges.manager.require_authorization(required_role=privileges.inventory_admin_role,ids_getter=get_roles_ids)
+@privileges.manager.require_authorization(required_role=inventory_view.inventory_admin_role,ids_getter=get_roles_ids)
 def routes():
 def routes():
     routes = []
     routes = []
     for route in __app__.url_map.iter_rules():
     for route in __app__.url_map.iter_rules():
         routes.append('%s' % route)
         routes.append('%s' % route)
     return jsonify(routes)
     return jsonify(routes)
 
 
+
+
 def run() :
 def run() :
     global __server_process__
     global __server_process__
     __server_process__ = ServerThread(__app__,"0.0.0.0",8000)
     __server_process__ = ServerThread(__app__,"0.0.0.0",8000)
@@ -157,69 +146,12 @@ def stop() :
     logger.info('View server stopped')
     logger.info('View server stopped')
 
 
 
 
+def add_blueprint(blueprint : flask.Blueprint) :
+    __app__.register_blueprint(blueprint)
 
 
-class ResourceNode(anytree.NodeMixin) :
-    def __init__(self, url_key : str, resource = None, parent=None, children=None):
-        super(ResourceNode, self).__init__()
-        self.url_key = url_key
-        self.parent = parent
-        if children:
-            self.children = children
-
-        if resource :
-            self.resource = resource
-
-
-            # we check if the resource class has an http API method
-            get    = getattr(self, "get",    None)
-            post   = getattr(self, "post",   None)
-            delete = getattr(self, "delete", None)
-            update = getattr(self, "update", None)
-            patch  = getattr(self, "patch",  None)
-
-            if  not callable(get)    and not callable(post) \
-            and not callable(delete) and not callable(update) \
-            and not callable(patch) :
-                raise BaseException("class does have an api class")
-
-
-    url_slice = None
-    resource = None
-
-
-def add_resource_tree(node : ResourceNode) :
-
-    if not node.is_root() :
-        raise BaseException("node is not a root node")
-
-    logger.debug("adding resource tree for API")
-    logger.debug(anytree.RenderTree(node, style=anytree.AsciiStyle()).by_attr("url_slice"))
-
-    for node in anytree.PreOrderIter(node) :
-        logger.debug("iterating though node " + node.url_key)
-
-        if node.resource is not None :
-            logger.debug("resource found")
-
-            url = ""
-            parent : ResourceNode
-            for parent in node.ancestors :
-                url = url + node.separator + parent.url_key
-
-            print("url built for the node : " + url)
-
-            __api__.add_resource(node.resource, url)
-            __resource_array__.append(node)
-
-#node.ancestors ( all parent )
-
-def delete_resource_tree(node : ResourceNode, cascade : boolean = True) :
-
-    if not cascade and not node.is_leaf() :
-        raise BaseException("cannot delete only a node when it's not a leaf !")
-
-
-    raise BaseException("Not implemented yet") #TODO
-
+@privileges.manager.require_authorization(required_role=inventory_view.inventory_read_only_role,ids_getter=get_roles_ids)
+def tab():
+    return jsonify([2,5,7])
 
 
 
 
+__app__.add_url_rule("/tab","/tab",tab)

+ 3 - 12
Backend/Sources/View/view_privilege.py

@@ -1,20 +1,11 @@
-from asyncore import read
 from utility.privilege_manager import *
 from utility.privilege_manager import *
+import Modules.Inventory.inventory_view as inventory_view
 
 
-manager                   = Privilege_Manager()
-inventory_read_only_role  = Privilege_Role(name="read_only")
-inventory_admin_role      = Privilege_Role(name="admin")
-
+manager = Privilege_Manager()
 
 
 def init() :
 def init() :
+    inventory_view.init()
 
 
-    manager.create_domain(name="inventory",description="privilege domain for inventory")
-
-    inventory_privilege_domain = manager.get_domain_by_name("inventory")
-    inventory_privilege_domain.add_role(inventory_read_only_role)
-    inventory_privilege_domain.add_role(inventory_admin_role)
-
-    inventory_privilege_domain.include_role(inventory_admin_role,inventory_read_only_role)
 
 
 
 
 
 

+ 19 - 4
Backend/Sources/utility/privilege_manager.py

@@ -11,7 +11,7 @@ def __generate_id__() :
 
 
 class APIAuthError(Exception):
 class APIAuthError(Exception):
   code = 403
   code = 403
-  description = "Authentication Error"
+  description = "Access Denied"
 
 
 
 
 import logging
 import logging
@@ -66,6 +66,7 @@ class Privilege_Domain :
     def add_role(self,role : Privilege_Role) :
     def add_role(self,role : Privilege_Role) :
         for tmp_role in self.__roles__ :
         for tmp_role in self.__roles__ :
             if tmp_role.name == role.name :
             if tmp_role.name == role.name :
+                logger.error("can't have role with the same name in a specific domain")
                 raise BaseException("can't have role with the same name in a specific domain")
                 raise BaseException("can't have role with the same name in a specific domain")
         self.__roles__.add(role)
         self.__roles__.add(role)
 
 
@@ -95,10 +96,12 @@ class Privilege_Domain :
     def include_role(self,role1 : Privilege_Role, role2 : Privilege_Role) :
     def include_role(self,role1 : Privilege_Role, role2 : Privilege_Role) :
 
 
         if role1 not in self.__roles__ or role2 not in self.__roles__ :
         if role1 not in self.__roles__ or role2 not in self.__roles__ :
-            raise BaseException("roles are not in domains.")
+            logger.error("roles are not in domains.")
+            raise Exception("roles are not in domains.")
 
 
         if role1.exclusive :
         if role1.exclusive :
-            raise "cannot include role, destination role is exclusive"
+            logger.error("cannot include role, destination role is exclusive")
+            raise Exception("cannot include role, destination role is exclusive")
 
 
         role1.aggregated_roles.add(role2)
         role1.aggregated_roles.add(role2)
 
 
@@ -166,18 +169,22 @@ class Privilege_Manager :
     def create_domain(self, name : str, description : str = None) :
     def create_domain(self, name : str, description : str = None) :
         for item in self.__domains__ :
         for item in self.__domains__ :
             if item.name == name :
             if item.name == name :
+                logger.error("cannot have two privilege domain with the same name !")
                 raise BaseException("cannot have two privilege domain with the same name !")
                 raise BaseException("cannot have two privilege domain with the same name !")
 
 
         domain = Privilege_Domain(name=name,description=description)
         domain = Privilege_Domain(name=name,description=description)
         self.__domains__.add(domain)
         self.__domains__.add(domain)
+        logger.info("domain with name " + name + "created")
 
 
 
 
     def remove_domain(self, name : str) :
     def remove_domain(self, name : str) :
         for item in list(self.__domains__) :
         for item in list(self.__domains__) :
             if item.name == name :
             if item.name == name :
                 self.__domains__.remove(item)
                 self.__domains__.remove(item)
+                logger.info("domain with name " + name + "removed")
                 return
                 return
 
 
+        logger.error("privilege domain remove failed ! item with name " + name + "not found")
         raise BaseException("privilege domain remove failed ! item not found")
         raise BaseException("privilege domain remove failed ! item not found")
 
 
     @property
     @property
@@ -239,15 +246,23 @@ class Privilege_Manager :
                 if item == role :
                 if item == role :
                     return domain
                     return domain
 
 
+        logger.error("this role is not associated with any domain")
         raise BaseException("this role is not associated with any domain")
         raise BaseException("this role is not associated with any domain")
 
 
+    def roles_to_ids(roles : list[Privilege_Role]) :
+        ret = []
+        for role in roles :
+            ret.append(role.aggregated_roles_ids)
+
+        return ret
+
     #its a DECORATOR
     #its a DECORATOR
     def require_authorization(self,required_role : Privilege_Role, ids_getter : callable) :
     def require_authorization(self,required_role : Privilege_Role, ids_getter : callable) :
 
 
         def wrapper_of_wrap(f) :
         def wrapper_of_wrap(f) :
             def wrap(*args, **kwargs):
             def wrap(*args, **kwargs):
                 if not self.is_role_registered(required_role) :
                 if not self.is_role_registered(required_role) :
-                    raise BaseException("role is not registered everywhere")
+                    raise BaseException("role is not registered anywhere")
                 logger.debug("checking authorization with roles for function " + f.__name__ + ": " )
                 logger.debug("checking authorization with roles for function " + f.__name__ + ": " )
                 logger.debug("required role :  " + required_role.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.
                 for role in self.get_roles_by_ids(ids_getter()) : #an user can have multiple roles and each role can include other roles.