Esempio n. 1
0
 def test_get_one_by_id(self):
     user = User(
         first_name = "Joe",
         last_name = "Doe",
         username = "******",
         email = "*****@*****.**",
         password = "******"
     )
     user.save()
     namespace_entity = Namespace_Entity()
     namespace = namespace_entity.insert_one({
         "name": "kevin",
         "is_public": True,
         "user_id": user.pk
     })
     self.assertTrue(namespace)
     self.assertTrue(namespace.id > 0)
     endpoint_entity = Endpoint_Entity();
     entity = endpoint_entity.insert_one({
         "route": "/",
         "method": Endpoint_Entity.GET,
         "target": Endpoint_Entity.DEBUG,
         "route_rules": "{}",
         "headers_rules": "{}",
         "body_rules": "{}",
         "namespace_id": namespace.id
     })
     entity = endpoint_entity.get_one_by_id(entity.id)
     self.assertEqual("get/debug", entity.method + entity.route + entity.target)
Esempio n. 2
0
    def namespace_pk(self):
        regex = re.compile('^[0-9]+$')
        if not bool(regex.match(self.__input)):
            return False

        namespace_entity = Namespace_Entity()
        return namespace_entity.get_one_by_id(self.__input) != False
Esempio n. 3
0
 def test_update_one_by_id(self):
     user = User(first_name="Joe",
                 last_name="Doe",
                 username="******",
                 email="*****@*****.**",
                 password="******")
     user.save()
     namespace_entity = Namespace_Entity()
     endpoint_entity = Endpoint_Entity()
     request_entity = Request_Entity()
     namespace = namespace_entity.insert_one({
         "name": "kevin",
         "is_public": True,
         "user_id": user.pk
     })
     endpoint = endpoint_entity.insert_one({
         "route": "/",
         "method": Endpoint_Entity.GET,
         "target": Endpoint_Entity.DEBUG,
         "route_rules": "{}",
         "headers_rules": "{}",
         "body_rules": "{}",
         "namespace_id": namespace.id
     })
     self.assertTrue(namespace)
     self.assertTrue(namespace.id > 0)
     endpoint_entity = Endpoint_Entity()
     self.assertTrue(
         endpoint_entity.insert_one({
             "route": "/",
             "method": Endpoint_Entity.GET,
             "target": Endpoint_Entity.DEBUG,
             "route_rules": "{}",
             "headers_rules": "{}",
             "body_rules": "{}",
             "namespace_id": namespace.id
         }))
     request = request_entity.insert_one({
         "uri": "/",
         "method": Request_Entity.GET,
         "headers": "{}",
         "body": "{}",
         "status": Request_Entity.DEBUG,
         "endpoint_id": endpoint.id
     })
     self.assertTrue(request)
     self.assertTrue(request.id > 0)
     self.assertTrue(
         request_entity.update_one_by_id(request.id, {"uri": "/new"}))
     request = request_entity.get_one_by_id(request.id)
     self.assertEqual("get/newdebug",
                      request.method + request.uri + request.status)
Esempio n. 4
0
 def test_insert_many(self):
     user = User(
         first_name = "Joe",
         last_name = "Doe",
         username = "******",
         email = "*****@*****.**",
         password = "******"
     )
     user.save()
     namespace_entity = Namespace_Entity()
     namespace = namespace_entity.insert_one({
         "name": "kevin",
         "is_public": True,
         "user_id": user.pk
     })
     self.assertTrue(namespace)
     self.assertTrue(namespace.id > 0)
     endpoint_entity = Endpoint_Entity();
     self.assertTrue(endpoint_entity.insert_many([
         {"route": "/", "method": Endpoint_Entity.GET, "target": Endpoint_Entity.DEBUG, "route_rules": "{}", "headers_rules": "{}", "body_rules": "{}","namespace_id": namespace.id},
         {"route": "/", "method": Endpoint_Entity.POST, "target": Endpoint_Entity.VALIDATE, "route_rules": "{}", "headers_rules": "{}", "body_rules": "{}","namespace_id": namespace.id},
         {"route": "/{id}", "method": Endpoint_Entity.GET, "target": Endpoint_Entity.DYNAMIC, "route_rules": "{}", "headers_rules": "{}", "body_rules": "{}","namespace_id": namespace.id},
     ]))
Esempio n. 5
0
class Namespace():

    __helpers = Helpers()
    __logger = None
    __namespace_entity = Namespace_Entity()
    __endpoint_entity = Endpoint_Entity()

    def __init__(self):
        self.__logger = self.__helpers.get_logger(__name__)

    def user_owns(self, namespace_id, user_id):
        return self.__namespace_entity.user_owns(namespace_id, user_id)

    def delete_namespace(self, namespace_id):
        return self.__namespace_entity.delete_one_by_id(namespace_id)

    def slug_used(self, slug):
        return (self.__namespace_entity.get_one_by_slug(slug) != False)

    def slug_used_elsewhere(self, namespace_id, slug):
        namespace = self.__namespace_entity.get_one_by_slug(slug)
        return False if namespace == False or namespace.id == namespace_id else True

    def insert_one(self, namespace):
        return self.__namespace_entity.insert_one(namespace)

    def update_one_by_id(self, namespace_id, new_data):
        return self.__namespace_entity.update_one_by_id(namespace_id, new_data)

    def get_one_by_slug(self, slug):
        return self.__namespace_entity.get_one_by_slug(slug)

    def get_many_by_user(self, user_id, order_by="created_at", asc=False):
        namespaces = self.__namespace_entity.get_many_by_user(
            user_id, order_by, asc)
        for namespace in namespaces:
            namespace.endpoints_count = self.__endpoint_entity.count_by_namespace(
                namespace.id)
        return namespaces
Esempio n. 6
0
 def test_insert_many(self):
     user = User(first_name="Joe",
                 last_name="Doe",
                 username="******",
                 email="*****@*****.**",
                 password="******")
     user.save()
     namespace_entity = Namespace_Entity()
     endpoint_entity = Endpoint_Entity()
     request_entity = Request_Entity()
     namespace = namespace_entity.insert_one({
         "name": "kevin",
         "is_public": True,
         "user_id": user.pk
     })
     endpoint = endpoint_entity.insert_one({
         "route": "/",
         "method": Endpoint_Entity.GET,
         "target": Endpoint_Entity.DEBUG,
         "route_rules": "{}",
         "headers_rules": "{}",
         "body_rules": "{}",
         "namespace_id": namespace.id
     })
     self.assertTrue(namespace)
     self.assertTrue(namespace.id > 0)
     endpoint_entity = Endpoint_Entity()
     self.assertTrue(
         endpoint_entity.insert_one({
             "route": "/",
             "method": Endpoint_Entity.GET,
             "target": Endpoint_Entity.DEBUG,
             "route_rules": "{}",
             "headers_rules": "{}",
             "body_rules": "{}",
             "namespace_id": namespace.id
         }))
     request = request_entity.insert_many([{
         "uri": "/",
         "method": Request_Entity.GET,
         "headers": "{}",
         "body": "{}",
         "status": Request_Entity.DEBUG,
         "endpoint_id": endpoint.id
     }, {
         "uri": "/",
         "method": Request_Entity.POST,
         "headers": "{}",
         "body": "{}",
         "status": Request_Entity.DEBUG,
         "endpoint_id": endpoint.id
     }, {
         "uri": "/{id}",
         "method": Request_Entity.GET,
         "headers": "{}",
         "body": "{}",
         "status": Request_Entity.DEBUG,
         "endpoint_id": endpoint.id
     }, {
         "uri": "/{id}",
         "method": Request_Entity.PUT,
         "headers": "{}",
         "body": "{}",
         "status": Request_Entity.DEBUG,
         "endpoint_id": endpoint.id
     }])
     self.assertTrue(request)
Esempio n. 7
0
class Request():

    __helpers = Helpers()
    __logger = None
    __namespace_entity = Namespace_Entity()
    __endpoint_entity = Endpoint_Entity()
    __request_entity = Request_Entity()

    def __init__(self):
        self.__logger = self.__helpers.get_logger(__name__)

    def insert_one(self, request):
        return self.__request_entity.insert_one(request)

    def user_owns(self, request_id, user_id):
        return self.__request_entity.user_owns(request_id, user_id)

    def delete_request(self, request_id):
        return self.__request_entity.delete_one_by_id(request_id)

    def get_many_by_endpoint(self, endpoint_id, order_by, asc):
        requests = self.__request_entity.get_many_by_endpoint(
            endpoint_id, order_by, asc)
        for request in requests:
            data = []
            try:
                data = json.loads(request.headers)
            except Exception as e:
                self.delete_request(request.id)

            request.headers = data
            if request.body != '':
                try:
                    request.body = json.loads(request.body)
                    request.body = json.dumps(request.body, indent=4)
                except Exception as e:
                    request.body = ''

        return requests

    def store_request(self, request_data):

        try:
            request_data["body"] = json.loads(request_data["body"])
        except Exception as e:
            request_data["body"] = ''

        headers = []
        for key, value in request_data["headers"].items():
            if key == "KVN-Auth-Token":
                continue
            headers.append({"key": key, "value": request_data["headers"][key]})

        endpoints = self.__endpoint_entity.get_many_by_namespace(
            request_data["namespace"].id, "created_at", True)

        result = 0
        for endpoint in endpoints:

            if not self.__validate_method(endpoint.method,
                                          request_data["method"]):
                continue

            if not self.__validate_uri(endpoint.route, request_data["uri"]):
                continue

            if endpoint.target == "debug":

                self.__request_entity.insert_one({
                    "uri":
                    "/" + request_data["uri"],
                    "method":
                    request_data["method"].lower(),
                    "headers":
                    json.dumps(headers),
                    "body":
                    '{}' if request_data["body"] == '' else json.dumps(
                        request_data["body"]),
                    "status":
                    "debug",
                    "endpoint_id":
                    endpoint.id
                })

                result += 1

            elif endpoint.target == "validate":

                if not self.__validate_body(endpoint.body_rules,
                                            equest_data["body"]):
                    continue

                if not self.__validate_headers(endpoint.headers_rules,
                                               headers):
                    continue

                self.__request_entity.insert_one({
                    "uri":
                    "/" + request_data["uri"],
                    "method":
                    request_data["method"].lower(),
                    "headers":
                    json.dumps(headers),
                    "body":
                    json.dumps(request_data["body"]),
                    "status":
                    "debug",
                    "endpoint_id":
                    endpoint.id
                })

                result += 1

        return result

    def __validate_uri(self, endpoint_uri, request_uri):
        return re.match("^" + endpoint_uri + "$", "/" + request_uri) != None

    def __validate_method(self, endpoint_method, request_method):
        return endpoint_method.lower() == "any" or endpoint_method.lower(
        ) == request_method.lower()

    def __validate_body(self, endpoint_body, request_body):
        return True

    def __validate_headers(self, endpoint_headers, request_headers):
        return True
Esempio n. 8
0
class Endpoint():

    __helpers = Helpers()
    __logger = None
    __namespace_entity = Namespace_Entity()
    __endpoint_entity = Endpoint_Entity()
    __request_entity = Request_Entity()

    def get_one_by_id(self, endpoint_id):
        endpoint = self.__endpoint_entity.get_one_by_id(endpoint_id)
        if endpoint != False:

            try:
                endpoint.header_rule_obj = json.loads(endpoint.headers_rules)
            except Exception as e:
                endpoint.header_rule_obj = []
                return endpoint

            i = 2
            j = 0
            for item in endpoint.header_rule_obj:
                endpoint.header_rule_obj[j]["index"] = i
                i += 1
                j += 1

            return endpoint

        return False

    def count_by_target(self, target, namespace_id):
        return self.__endpoint_entity.count_by_target(target, namespace_id)

    def get_many_by_namespace_id(self,
                                 namespace_id,
                                 order_by="created_at",
                                 asc=False):
        endpoints = self.__endpoint_entity.get_many_by_namespace(
            namespace_id, order_by, asc)
        for endpoint in endpoints:
            if endpoint.target == 'validate':
                endpoint.status = self.__request_entity.get_latest_status(
                    endpoint.id)
            elif endpoint.target == 'dynamic':
                endpoint.status = "dynamic"
            else:
                endpoint.status = "debug"
        return endpoints

    def user_owns(self, endpoint_id, user_id):
        endpoint = self.__endpoint_entity.get_one_by_id(endpoint_id)
        if endpoint == False:
            return False
        return self.__namespace_entity.user_owns(endpoint.namespace.id,
                                                 user_id)

    def delete_endpoint(self, endpoint_id):
        return self.__endpoint_entity.delete_one_by_id(endpoint_id)

    def insert_one(self, endpoint):
        return self.__endpoint_entity.insert_one(endpoint)

    def update_one_by_id(self, endpoint_id, new_data):
        return self.__endpoint_entity.update_one_by_id(endpoint_id, new_data)
Esempio n. 9
0
class NamespacesStatistics():

    __helpers = Helpers()
    __logger = None
    __namespace_entity = Namespace_Entity()
    __endpoint_entity = Endpoint_Entity()
    __request_entity = Request_Entity()

    def __init__(self):
        self.__logger = self.__helpers.get_logger(__name__)

    def overall_count_chart(self, user_id=None):
        public_count = self.__namespace_entity.count_by_visibility(
            True, user_id)
        private_count = self.__namespace_entity.count_by_visibility(
            False, user_id)
        total_count = public_count + private_count

        if total_count > 0:
            public_percent = round((public_count / total_count) * 100)
            private_percent = round((private_count / total_count) * 100)
        else:
            public_percent = 0
            private_percent = 0

        return {"public": public_percent, "private": private_percent}

    def count_over_time_chart(self, days_num, user_id=None):
        data = {
            "public":
            self.__namespace_entity.count_by_visibility_date(
                True, str(days_num), user_id),
            "private":
            self.__namespace_entity.count_by_visibility_date(
                False, str(days_num), user_id),
            "public_list": {},
            "private_list": {},
            "final": {
                "public": [],
                "private": [],
                "total": []
            }
        }

        for item in data["public"]:
            data["public_list"][str(item.count_date)] = item.id

        for item in data["private"]:
            data["private_list"][str(item.count_date)] = item.id

        days_count = days_num

        while days_count > -1:
            current_date = timezone.now().date() - timedelta(days_count)
            current_date = str(current_date)

            if current_date in data["public_list"]:
                current_public = data["public_list"][current_date]
                data["final"]["public"].append(current_public)
            else:
                current_public = 0
                data["final"]["public"].append(current_public)

            if current_date in data["private_list"]:
                current_private = data["private_list"][current_date]
                data["final"]["private"].append(current_private)
            else:
                current_private = 0
                data["final"]["private"].append(current_private)

            data["final"]["total"].append(current_private + current_public)

            days_count -= 1

        data["final"]["private"] = ",".join(
            str(x) for x in data["final"]["private"])
        data["final"]["public"] = ",".join(
            str(x) for x in data["final"]["public"])
        data["final"]["total"] = ",".join(
            str(x) for x in data["final"]["total"])

        return {
            "private": data["final"]["private"],
            "public": data["final"]["public"],
            "total": data["final"]["total"]
        }

    def count_endpoints_by_target(self, namespace_id):
        debug_count = self.__endpoint_entity.count_by_target(
            Endpoint_Entity.DEBUG, namespace_id)
        validate_count = self.__endpoint_entity.count_by_target(
            Endpoint_Entity.VALIDATE, namespace_id)
        dynamic_count = self.__endpoint_entity.count_by_target(
            Endpoint_Entity.DYNAMIC, namespace_id)
        total_count = debug_count + validate_count + dynamic_count

        if total_count > 0:
            debug_percent = round((debug_count / total_count) * 100)
            validate_percent = round((validate_count / total_count) * 100)
            dynamic_percent = round((dynamic_count / total_count) * 100)
        else:
            debug_percent = 0
            validate_percent = 0
            dynamic_percent = 0

        return {
            "debug": debug_percent,
            "validate": validate_percent,
            "dynamic": dynamic_percent
        }

    def count_requests_over_time_chart(self, days_num, namespace_id):

        data = {"requests_list": {}, "requests": []}

        endpoins_in_namespace = self.__endpoint_entity.get_many_ids_by_namespace(
            namespace_id)
        items = self.__request_entity.count_by_endpoint_date(
            days_num, endpoins_in_namespace)
        for item in items:
            data["requests_list"][str(item.count_date)] = item.id

        days_count = days_num

        while days_count > -1:
            current_date = timezone.now().date() - timedelta(days_count)
            current_date = str(current_date)

            if current_date in data["requests_list"]:
                requests = data["requests_list"][current_date]
                data["requests"].append(requests)
            else:
                requests = 0
                data["requests"].append(requests)

            days_count -= 1

        data["requests"] = ",".join([str(x) for x in data["requests"]])

        return {"requests": data["requests"]}