Example #1
0
class Namespace_Edit(View):

    template_name = 'templates/admin/namespaces/edit.html'
    __context = Context()
    __namespace_module = Namespace_Module()

    def get(self, request, namespace_slug):

        namespace = self.__namespace_module.get_one_by_slug(namespace_slug)

        if namespace == False or request.user.id != namespace.user.id:
            raise Http404("Namespace not found.")

        self.__context.autoload_options()
        self.__context.autoload_user(
            request.user.id if request.user.is_authenticated else None)
        self.__context.push({
            "page_title":
            _("Edit %s Namespace · %s") %
            (namespace.name,
             self.__context.get("app_name", os.getenv("APP_NAME", "Kevin"))),
            "namespace":
            namespace
        })

        return render(request, self.template_name, self.__context.get())
Example #2
0
class Namespaces_List(View):

    template_name = 'templates/admin/namespaces/list.html'
    __context = Context()
    __namespace_module = Namespace_Module()
    __namespaces_statistics = NamespacesStatistics()

    def get(self, request):

        self.__context.autoload_options()
        self.__context.autoload_user(
            request.user.id if request.user.is_authenticated else None)
        self.__context.push({
            "page_title":
            _("Namespaces · %s") %
            self.__context.get("app_name", os.getenv("APP_NAME", "Kevin"))
        })

        self.__context.push({
            "namespaces":
            self.__namespace_module.get_many_by_user(request.user.id),
            "donut":
            self.__namespaces_statistics.overall_count_chart(request.user.id),
            "line_chart":
            self.__namespaces_statistics.count_over_time_chart(
                20, request.user.id)
        })

        return render(request, self.template_name, self.__context.get())
Example #3
0
class Endpoint_View(View):

    template_name = 'templates/admin/namespaces/endpoints/view.html'
    __context = Context()
    __namespace_module = Namespace_Module()
    __namespaces_statistics = NamespacesStatistics()
    __endpoint_module = Endpoint_Module()
    __endpoints_statistics = EndpointsStatistics()
    __request_module = Request_Module()

    def get(self, request, namespace_slug, endpoint_id):

        namespace = self.__namespace_module.get_one_by_slug(namespace_slug)

        if namespace == False or request.user.id != namespace.user.id:
            raise Http404("Namespace not found.")

        endpoint = self.__endpoint_module.get_one_by_id(endpoint_id)

        if endpoint == False or namespace.id != endpoint.namespace.id:
            raise Http404("Endpoint not found.")

        self.__context.autoload_options()
        self.__context.autoload_user(
            request.user.id if request.user.is_authenticated else None)
        self.__context.push({
            "page_title":
            _("%s Endpoint Activity · %s") %
            (namespace.name,
             self.__context.get("app_name", os.getenv("APP_NAME", "Kevin"))),
            "namespace":
            namespace,
            "endpoint":
            endpoint,
            "requests":
            self.__request_module.get_many_by_endpoint(endpoint.id,
                                                       "created_at", False),
            "donut":
            self.__endpoints_statistics.count_requests_by_status(endpoint.id),
            "line_chart":
            self.__endpoints_statistics.count_requests_over_time_chart(
                20, endpoint.id)
        })

        return render(request, self.template_name, self.__context.get())
Example #4
0
class Namespace_Create(View):

    template_name = 'templates/admin/namespaces/create.html'
    __context = Context()
    __namespace_module = Namespace_Module()

    def get(self, request):

        self.__context.autoload_options()
        self.__context.autoload_user(
            request.user.id if request.user.is_authenticated else None)
        self.__context.push({
            "page_title":
            _("Create a Namespace · %s") %
            self.__context.get("app_name", os.getenv("APP_NAME", "Kevin"))
        })

        return render(request, self.template_name, self.__context.get())
Example #5
0
class Ping(View):

    __request = Request()
    __response = Response()
    __helpers = Helpers()
    __form = Form()
    __logger = None

    __namespace_module = Namespace_Module()
    __endpoint_module = Endpoint_Module()
    __request_module = Request_Module()
    __profile_module = Profile_Module()
    __context = Context()

    __headers = None

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

    @method_decorator(csrf_exempt)
    def dispatch(self, request, endpoint_path):
        path_items = endpoint_path.split("/")
        namespace_slug = path_items[0]
        endpoint_path = endpoint_path.replace(namespace_slug, "").lstrip("/")

        self.__headers = self.__get_headers(request)

        namespace = self.__namespace_module.get_one_by_slug(namespace_slug)

        if namespace == False:
            return JsonResponse(
                self.__response.send_public_failure([{
                    "error":
                    "Error! Namespace not found."
                }]))

        if not namespace.is_public:
            if not "KVN-Auth-Token" in self.__headers:
                return JsonResponse(
                    self.__response.send_public_failure([{
                        "error":
                        "Error! Access Denied."
                    }]))

            profile = self.__profile_module.get_profile_by_access_token(
                self.__headers["KVN-Auth-Token"])

            if profile == False:
                return JsonResponse(
                    self.__response.send_public_failure([{
                        "error":
                        "Error! Access Token Expired or Invalid."
                    }]))

            if profile.user.id != namespace.user.id:
                return JsonResponse(
                    self.__response.send_public_failure([{
                        "error":
                        "Error! Access Denied."
                    }]))

            self.__context.load_options({"access_tokens_expire_after": 24})
            expire_after = int(
                self.__context.get("access_tokens_expire_after", 24))

            if profile.access_token_updated_at < self.__helpers.time_after(
                {"hours": -24}):
                return JsonResponse(
                    self.__response.send_public_failure([{
                        "error":
                        "Error! Access Token Expired."
                    }]))

        result = self.__request_module.store_request({
            "method":
            request.method,
            "uri":
            endpoint_path,
            "headers":
            self.__headers,
            "body":
            request.body.decode('utf-8'),
            "namespace":
            namespace
        })

        if result:
            return JsonResponse(self.__response.send_public_success([]))
        else:
            return JsonResponse(
                self.__response.send_public_failure([{
                    "error":
                    "Error! Endpoint not found."
                }]))

    def __get_headers(self, request):
        headers = {
            "Content-Length": request.META['CONTENT_LENGTH'],
            "Content-Type": request.META['CONTENT_TYPE']
        }
        for header, value in request.META.items():
            if not header.startswith('HTTP'):
                continue
            header = '-'.join(
                [h.capitalize() for h in header[5:].lower().split('_')])
            headers[header] = value

        return headers
Example #6
0
class Namespaces(View):

    __request = Request()
    __response = Response()
    __helpers = Helpers()
    __form = Form()
    __logger = None
    __user_id = None
    __namespace_module = Namespace_Module()


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


    #def get(self, request):
    #    pass


    def post(self, request):

        self.__user_id = request.user.id

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post", {
            "name" : "",
            "slug" : "",
            "is_public": "off"
        })

        self.__form.add_inputs({
            'name': {
                'value': request_data["name"],
                'validate': {
                    'namespace_name': {
                        'error': _("Error! Namespace Name is invalid.")
                    },
                    'length_between':{
                        'param': [3, 41],
                        'error': _("Error! Namespace slug length must be from 4 to 40 characters.")
                    }
                }
            },
            'slug': {
                'value': request_data["slug"],
                'validate': {
                    'namespace_slug': {
                        'error': _('Error! Namespace slug is not valid.')
                    },
                    'length_between':{
                        'param': [3, 21],
                        'error': _('Error! Namespace slug length must be from 4 to 20 characters.')
                    }
                }
            },
            'is_public': {
                'value': request_data["is_public"],
                'validate': {
                    'any_of':{
                        'param': [["on", "off"]],
                        'error': _('Error! Is public value is invalid.')
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(self.__response.send_private_failure(self.__form.get_errors(with_type=True)))

        if self.__namespace_module.slug_used(self.__form.get_input_value("slug")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Namespace slug is already used.")
            }]))

        result = self.__namespace_module.insert_one({
            "name": self.__form.get_input_value("name"),
            "slug": self.__form.get_input_value("slug"),
            "is_public": (self.__form.get_input_value("is_public") == "on"),
            "user_id": self.__user_id
        })

        if result:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Namespace created successfully.")
            }]))

        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while creating namespace.")
            }]))