Esempio n. 1
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__register = Register_Module()
     self.__logger = self.__helpers.get_logger(__name__)
Esempio n. 2
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__reset_password = Reset_Password_Module()
     self.__logger = self.__helpers.get_logger(__name__)
Esempio n. 3
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__host_module = Host_Module()
     self.__image_module = Image_Module()
     self.__logger = self.__helpers.get_logger(__name__)
Esempio n. 4
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__incident = IncidentModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__form.add_validator(ExtraRules())
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__component_group = ComponentGroupModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__form.add_validator(ExtraRules())
Esempio n. 6
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__settings_module = Settings_Module()
     self.__acl = ACL()
     self.__logger = self.__helpers.get_logger(__name__)
Esempio n. 7
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__settings = Settings()
     self.__metric = MetricModule()
     self.__form = Form()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__form.add_validator(ExtraRules())
Esempio n. 8
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__reset_password = ResetPasswordModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__correlation_id = ""
     self.__form.add_validator(ExtraRules())
Esempio n. 9
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__host_module = Host_Module()
     self.__task_module = Task_Module()
     self.__notification_module = Notification_Module()
     self.__logger = self.__helpers.get_logger(__name__)
Esempio n. 10
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__install = InstallModule()
     self.__notification = NotificationModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__form.add_validator(ExtraRules())
Esempio n. 11
0
class LatestNotifications(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __notification = None
    __correlation_id = None

    def __init__(self):
        self.__helpers = Helpers()
        self.__form = Form()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__response = Response()
        self.__request = Request()
        self.__notification = NotificationModule()
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated
    def get(self, request):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__user_id = request.user.id

        return JsonResponse(
            self.__response.send_private_success(
                [],
                self.__notification.user_latest_notifications(self.__user_id),
                self.__correlation_id))

    @allow_if_authenticated
    def post(self, request):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__user_id = request.user.id
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post",
                                                       {"notification_id": ""})

        try:
            notification_id = int(request_data["notification_id"])
        except Exception:
            return JsonResponse(
                self.__response.send_private_success([], {},
                                                     self.__correlation_id))

        self.__notification.mark_notification(self.__user_id, notification_id)

        return JsonResponse(
            self.__response.send_private_success([], {},
                                                 self.__correlation_id))
Esempio n. 12
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__settings_module = SettingsModule()
     self.__acl = ACL()
     self.__activity_module = ActivityModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__form.add_validator(ExtraRules())
Esempio n. 13
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__incident_update = IncidentUpdateModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__user_id = None
     self.__correlation_id = ""
     self.__form.add_validator(ExtraRules())
Esempio n. 14
0
class Activities(View):
    """List Activities Private Endpoint Controller"""

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__activity = ActivityModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__user_id = None
        self.__correlation_id = ""
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated
    def get(self, request):

        self.__correlation_id = request.META["X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__user_id = request.user.id
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("get", {
            "offset": 0,
            "limit": 20
        })

        try:
            offset = int(request_data["offset"])
            limit = int(request_data["limit"])
        except Exception:
            offset = 0
            limit = 20

        return JsonResponse(self.__response.send_private_success([], {
            'activities': self.__format_activities(self.__activity.get(self.__user_id, offset, limit)),
            'metadata': {
                'offset': offset,
                'limit': limit,
                'count': self.__activity.count(self.__user_id)
            }
        }, self.__correlation_id))

    def __format_activities(self, activities):
        activities_list = []

        for activity in activities:
            activities_list.append({
                "id": activity.id,
                "activity": activity.activity,
                "created_at": activity.created_at.strftime("%b %d %Y %H:%M:%S")
            })

        return activities_list
Esempio n. 15
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__settings = Settings()
     self.__component = ComponentModule()
     self.__component_group = ComponentGroupModule()
     self.__form = Form()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__user_id = None
     self.__correlation_id = ""
     self.__form.add_validator(ExtraRules())
Esempio n. 16
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__incident_update = IncidentUpdateModule()
     self.__task = Task_Module()
     self.__notification = NotificationModule()
     self.__subscriber = SubscriberModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__incident_update_component = IncidentUpdateComponentModule()
     self.__form.add_validator(ExtraRules())
Esempio n. 17
0
class Requests(View):

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

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

    def get(self, request):
        pass
Esempio n. 18
0
class Request(View):

    __request = Request()
    __response = Response()
    __helpers = Helpers()
    __form = Form()
    __logger = None
    __user_id = None
    __request_id = None
    __request_module = Request_Module()

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

    def delete(self, request, request_id):

        self.__user_id = request.user.id
        self.__request_id = request_id

        if not self.__request_module.user_owns(self.__request_id,
                                               self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Invalid Request.")
                }]))

        if self.__request_module.delete_request(self.__request_id):
            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Request deleted successfully.")
                }]))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while deleting a request.")
                }]))
Esempio n. 19
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
Esempio n. 20
0
class Login(View):

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

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

    @stop_request_if_authenticated
    def post(self, request):

        if self.__login.is_authenticated(request):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! User is already authenticated.")
                }]))

        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "username": "",
            "password": ""
        })

        self.__form.add_inputs({
            'username': {
                'value': request_data["username"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'username_or_email': {
                        'error': _("Error! Username or password is invalid.")
                    }
                }
            },
            'password': {
                'value': request_data["password"],
                'validate': {
                    'password': {
                        'error': _("Error! Username or password is invalid.")
                    },
                    'length_between': {
                        'param': [7, 20],
                        'error': _("Error! Username or password 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.__login.authenticate(self.__form.get_input_value("username"),
                                     self.__form.get_input_value("password"),
                                     request):
            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("You logged in successfully.")
                }]))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Username or password is invalid.")
                }]))
Esempio n. 21
0
class Reset_Password(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __reset_password = None
    __logger = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__reset_password = Reset_Password_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    @stop_request_if_authenticated
    def post(self, request):

        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "reset_token": "",
            "new_password": ""
        })

        self.__form.add_inputs({
            'reset_token': {
                'value': request_data["reset_token"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {}
            },
            'new_password': {
                'value': request_data["new_password"],
                'validate': {
                    'password': {
                        'error': _('Error! Password must contain at least uppercase letter, lowercase letter, numbers and special character.')
                    },
                    'length_between': {
                        'param': [7, 20],
                        'error': _('Error! Password length must be from 8 to 20 characters.')
                    }
                }
            }
        })

        self.__form.process()

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

        if not self.__reset_password.check_token(self.__form.get_input_value("reset_token")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Reset token is expired or invalid.")
            }]))

        result = self.__reset_password.reset_password(
            self.__form.get_input_value("reset_token"),
            self.__form.get_input_value("new_password")
        )

        result &= self.__reset_password.delete_reset_request(self.__form.get_input_value("reset_token"))

        if not result:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while resetting password.")
            }]))
        else:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Password updated successfully.")
            }]))
Esempio n. 22
0
class Build_Image(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __task_module = None
    __notification_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__task_module = Task_Module()
        self.__notification_module = Notification_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def post(self, request, host_id):

        self.__user_id = request.user.id
        self.__host_id = host_id

        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "tag": "",
            "dockerfile": "",
            "rm": "",
            "nocache": ""
        })

        self.__form.add_inputs({
            'tag': {
                'value': request_data["tag"],
                'sanitize': {},
                'validate': {}
            },
            'dockerfile': {
                'value': request_data["dockerfile"],
                'sanitize': {},
                'validate': {}
            },
            'rm': {
                'value': request_data["rm"],
                'sanitize': {},
                'validate': {}
            },
            'nocache': {
                'value': request_data["nocache"],
                'sanitize': {},
                'validate': {}
            }
        })

        self.__form.process()

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

        if not self.__host_module.user_owns(self.__host_id, self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Invalid Request.")
                }]))

        _tag = self.__form.get_input_value("tag")
        _fileobj = self.__form.get_input_value("dockerfile")
        _rm = bool(self.__form.get_input_value("rm") == "1")
        _nocache = bool(self.__form.get_input_value("nocache") == "1")

        task = self.__task_module.delay(
            "build_image", {
                "host_id": self.__host_id,
                "fileobj": _fileobj,
                "tag": _tag,
                "rm": _rm,
                "nocache": _nocache
            }, self.__user_id)

        if task:

            self.__notification_module.create_notification({
                "highlight":
                "",
                "notification":
                "building docker image %s" % _tag,
                "url":
                "#",
                "type":
                Notification_Module.PENDING,
                "delivered":
                False,
                "user_id":
                self.__user_id,
                "host_id":
                self.__host_id,
                "task_id":
                task.id
            })

            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Request is in progress!")
                }]))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while creating request.")
                }]))
Esempio n. 23
0
class Register(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __register = None
    __logger = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__register = Register_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    @stop_request_if_authenticated
    def post(self, request):

        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "first_name": "",
            "last_name": "",
            "username": "",
            "email": "",
            "password": ""
        })

        self.__form.add_inputs({
            'first_name': {
                'value': request_data["first_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'names': {
                        'error': _('Error! First name contains invalid characters.')
                    },
                    'length_between': {
                        'param': [0, 20],
                        'error': _('Error! First name must be 1 to 20 characters long.')
                    }
                }
            },
            'last_name': {
                'value': request_data["last_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'names': {
                        'error': _('Error! Last name contains invalid characters.')
                    },
                    'length_between': {
                        'param': [0, 20],
                        'error': _('Error! Last name must be 1 to 20 characters long.')
                    }
                }
            },
            'username': {
                'value': request_data["username"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'alpha_numeric': {
                        'error': _('Error! Username must be alpha numeric.')
                    },
                    'length_between': {
                        'param': [4, 10],
                        'error': _('Error! Username must be 5 to 10 characters long.')
                    }
                }
            },
            'email': {
                'value': request_data["email"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'email': {
                        'error': _('Error! Admin email is invalid.')
                    }
                }
            },
            'password': {
                'value': request_data["password"],
                'validate': {
                    'password': {
                        'error': _('Error! Password must contain at least uppercase letter, lowercase letter, numbers and special character.')
                    },
                    'length_between': {
                        'param': [7, 20],
                        'error': _('Error! Password length must be from 8 to 20 characters.')
                    }
                }
            }
        })

        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.__register.username_used(self.__form.get_input_value("username")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Username is already used.")
            }]))

        if self.__register.email_used(self.__form.get_input_value("email")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Email is already used for other account.")
            }]))

        result = self.__register.create_user({
            "username": self.__form.get_input_value("username"),
            "email": self.__form.get_input_value("email"),
            "first_name": self.__form.get_input_value("first_name"),
            "last_name": self.__form.get_input_value("last_name"),
            "password": self.__form.get_input_value("password"),
        })

        if result:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Account created successfully.")
            }]))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while creating your account.")
            }]))
Esempio n. 24
0
class Pull_Image(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __task_module = None
    __notification_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__task_module = Task_Module()
        self.__notification_module = Notification_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def post(self, request, host_id):

        self.__user_id = request.user.id
        self.__host_id = host_id

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post",
                                                       {"image_name": ""})

        self.__form.add_inputs({
            'image_name': {
                'value': request_data["image_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'not_empty': {
                        'error': _('Error! docker image is required!')
                    },
                    'length_between': {
                        'param': [1, 100],
                        'error': _('Error! a valid docker image is required!')
                    }
                }
            }
        })

        self.__form.process()

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

        if not self.__host_module.user_owns(self.__host_id, self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Invalid Request.")
                }]))

        _image_name = self.__form.get_input_value("image_name")

        if ":" not in _image_name:
            _image_name = "%s:latest" % _image_name

        task = self.__task_module.delay("pull_image", {
            "host_id": self.__host_id,
            "image_name": _image_name
        }, self.__user_id)

        if task:

            self.__notification_module.create_notification({
                "highlight":
                "",
                "notification":
                "pulling docker image %s" % _image_name,
                "url":
                "#",
                "type":
                Notification_Module.PENDING,
                "delivered":
                False,
                "user_id":
                self.__user_id,
                "host_id":
                self.__host_id,
                "task_id":
                task.id
            })

            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Request is in progress!")
                }]))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while creating request.")
                }]))
Esempio n. 25
0
class Incidents(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __incident = None
    __correlation_id = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__incident = IncidentModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated
    def post(self, request):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "name": "",
            "status": "",
            "datetime": "",
        })

        self.__form.add_inputs({
            'name': {
                'value': request_data["name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 200],
                        'error':
                        _('Error! Incident name must be 1 to 200 characters long.'
                          )
                    }
                }
            },
            'datetime': {
                'value': request_data["datetime"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'status': {
                'value': request_data["status"],
                'validate': {
                    'any_of': {
                        'param': [["open", "closed"]],
                        'error': _('Error! Incident is invalid.')
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(
                self.__response.send_errors_failure(self.__form.get_errors(),
                                                    {}, self.__correlation_id))

        result = self.__incident.insert_one({
            "name":
            self.__form.get_sinput("name"),
            "status":
            self.__form.get_sinput("status"),
            "datetime":
            DateTimeField().clean(self.__form.get_sinput("datetime")),
            "uri":
            self.__incident.generate_uri(6)
        })

        if result:
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Incident created successfully.")
                    }], {}, self.__correlation_id))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while creating incident.")
                }], {}, self.__correlation_id))

    @allow_if_authenticated
    def get(self, request):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("get", {
            "offset": "",
            "limit": ""
        })

        try:
            offset = int(request_data["offset"])
            limit = int(request_data["limit"])
        except Exception:
            offset = 0
            limit = 0

        return JsonResponse(
            self.__response.send_private_success(
                [], {
                    'incidents':
                    self.__format_incidents(
                        self.__incident.get_all(offset, limit)),
                    'metadata': {
                        'offset': offset,
                        'limit': limit,
                        'count': self.__incident.count_all()
                    }
                }, self.__correlation_id))

    def __format_incidents(self, incidents):
        incidents_list = []

        for incident in incidents:
            incidents_list.append({
                "id":
                incident.id,
                "name":
                incident.name,
                "uri":
                incident.uri,
                "status":
                incident.status.title(),
                "created_at":
                incident.created_at.strftime("%b %d %Y %H:%M:%S"),
                "view_url":
                reverse("app.web.admin.incident.view",
                        kwargs={'incident_id': incident.id}),
                "view_status_url":
                reverse("app.web.status_page_single",
                        kwargs={'uri': incident.uri}),
                "edit_url":
                reverse("app.web.admin.incident.edit",
                        kwargs={'incident_id': incident.id}),
                "delete_url":
                reverse("app.api.private.v1.admin.incident.endpoint",
                        kwargs={'incident_id': incident.id})
            })

        return incidents_list
Esempio n. 26
0
class Incident(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __incident = None
    __correlation_id = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__incident = IncidentModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated
    def post(self, request, incident_id):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "name": "",
            "status": "",
            "datetime": "",
        })

        self.__form.add_inputs({
            'name': {
                'value': request_data["name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [1, 200],
                        'error':
                        _('Error! Incident name must be 1 to 200 characters long.'
                          )
                    }
                }
            },
            'datetime': {
                'value': request_data["datetime"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'status': {
                'value': request_data["status"],
                'validate': {
                    'any_of': {
                        'param': [["open", "closed"]],
                        'error': _('Error! Incident is invalid.')
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(
                self.__response.send_errors_failure(self.__form.get_errors(),
                                                    {}, self.__correlation_id))

        result = self.__incident.update_one_by_id(
            incident_id, {
                "name":
                self.__form.get_sinput("name"),
                "status":
                self.__form.get_sinput("status"),
                "datetime":
                DateTimeField().clean(self.__form.get_sinput("datetime"))
            })

        if result:
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Incident updated successfully.")
                    }], {}, self.__correlation_id))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while updating incident.")
                }], {}, self.__correlation_id))

    @allow_if_authenticated
    def delete(self, request, incident_id):

        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__user_id = request.user.id

        if self.__incident.delete_one_by_id(incident_id):
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Incident deleted successfully.")
                    }], {}, self.__correlation_id))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while deleting incident.")
                }], {}, self.__correlation_id))
Esempio n. 27
0
class Profile(View):

    __request = Request()
    __response = Response()
    __helpers = Helpers()
    __form = Form()
    __settings = None
    __logger = None
    __user_id = None
    __profile_module = Profile_Module()


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


    def post(self, request):

        self.__user_id = request.user.id

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post", {
            "action" : ""
        })

        self.__form.add_inputs({
            'action': {
                'value': request_data["action"],
                'validate': {
                    'any_of':{
                        'param': [["_update_profile", "_update_password", "_update_access_token", "_update_refresh_token"]],
                        'error': _("Error! Invalid Request.")
                    }
                }
            }
        })

        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.__form.get_input_value("action") == "_update_profile":
            return self.__update_profile(request)
        elif self.__form.get_input_value("action") == "_update_password":
            return self.__update_password(request)
        elif self.__form.get_input_value("action") == "_update_access_token":
            return self.__update_access_token(request)
        elif self.__form.get_input_value("action") == "_update_refresh_token":
            return self.__update_refresh_token(request)


    def __update_profile(self, request):

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post", {
            "first_name" : "",
            "last_name" : "",
            "username" : "",
            "email" : "",
            "job_title" : "",
            "company" : "",
            "address" : "",
            "github_url" : "",
            "twitter_url" : "",
            "facebook_url" : ""
        })

        self.__form.add_inputs({
            'first_name': {
                'value': request_data["first_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'names': {
                        'error': _('Error! First name contains invalid characters.')
                    },
                    'length_between':{
                        'param': [0, 20],
                        'error': _('Error! First name must be 1 to 20 characters long.')
                    }
                }
            },
            'last_name': {
                'value': request_data["last_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'names': {
                        'error': _('Error! Last name contains invalid characters.')
                    },
                    'length_between':{
                        'param': [0, 20],
                        'error': _('Error! Last name must be 1 to 20 characters long.')
                    }
                }
            },
            'username': {
                'value': request_data["username"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'alpha_numeric': {
                        'error': _('Error! Username must be alpha numeric.')
                    },
                    'length_between':{
                        'param': [4, 10],
                        'error': _('Error! Username must be 5 to 10 characters long.')
                    }
                }
            },
            'email': {
                'value': request_data["email"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'email': {
                        'error': _('Error! Admin email is invalid.')
                    }
                }
            },
            'job_title': {
                'value': request_data["job_title"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between':{
                        'param': [0, 80],
                        'error': _('Error! Job title is very long.')
                    },
                    'optional': {}
                }
            },
            'company': {
                'value': request_data["company"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between':{
                        'param': [0, 80],
                        'error': _('Error! Company is very long.')
                    },
                    'optional': {}
                }
            },
            'address': {
                'value': request_data["address"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between':{
                        'param': [0, 80],
                        'error': _('Error! Address is very long.')
                    },
                    'optional': {}
                }
            },
            'github_url': {
                'value': request_data["github_url"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'url': {
                        'error': _('Error! Github url is invalid.')
                    },
                    'length_between':{
                        'param': [0, 80],
                        'error': _('Error! Github url is very long.')
                    },
                    'optional': {}
                }
            },
            'twitter_url': {
                'value': request_data["twitter_url"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'url': {
                        'error': _('Error! Twitter url is invalid.')
                    },
                    'length_between':{
                        'param': [0, 80],
                        'error': _('Error! Twitter url is very long.')
                    },
                    'optional': {}
                }
            },
            'facebook_url': {
                'value': request_data["facebook_url"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'url': {
                        'error': _('Error! Facebook url is invalid.')
                    },
                    'length_between':{
                        'param': [0, 80],
                        'error': _('Error! Facebook url is very long.')
                    },
                    'optional': {}
                }
            }
        })

        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.__profile_module.username_used_elsewhere(self.__user_id, self.__form.get_input_value("username")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Username is already used.")
            }]))


        if self.__profile_module.email_used_elsewhere(self.__user_id, self.__form.get_input_value("email")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Email is already used.")
            }]))

        result = self.__profile_module.update_profile(self.__user_id, {
            "first_name": self.__form.get_input_value("first_name"),
            "last_name": self.__form.get_input_value("last_name"),
            "username": self.__form.get_input_value("username"),
            "email": self.__form.get_input_value("email"),
            "job_title": self.__form.get_input_value("job_title"),
            "company": self.__form.get_input_value("company"),
            "address": self.__form.get_input_value("address"),
            "github_url": self.__form.get_input_value("github_url"),
            "twitter_url": self.__form.get_input_value("twitter_url"),
            "facebook_url": self.__form.get_input_value("facebook_url")
        })

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

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


    def __update_password(self, request):

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post", {
            "old_password" : "",
            "new_password" : ""
        })

        self.__form.add_inputs({
            'old_password': {
                'value': request_data["old_password"],
                'validate': {
                    'password': {
                        'error': _("Error! Old password is invalid.")
                    },
                    'length_between':{
                        'param': [7, 20],
                        'error': _("Error! Old password is invalid.")
                    }
                }
            },
            'new_password': {
                'value': request_data["new_password"],
                'validate': {
                    'password': {
                        'error': _('Error! New Password must contain at least uppercase letter, lowercase letter, numbers and special character.')
                    },
                    'length_between':{
                        'param': [7, 20],
                        'error': _('Error! New Password length must be from 8 to 20 characters.')
                    }
                }
            }
        })

        self.__form.process()

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

        if not self.__profile_module.validate_password(self.__user_id, self.__form.get_input_value("old_password")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Old password is invalid.")
            }]))

        result = self.__profile_module.change_password(self.__user_id, self.__form.get_input_value("new_password"))

        if result:
            self.__profile_module.restore_session(self.__user_id, request)
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Password updated successfully.")
            }]))

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


    def __update_access_token(self, request):

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post", {
            "token" : "",
        })

        self.__form.add_inputs({
            'token': {
                'value': request_data["token"],
                'validate': {
                    'token':{
                        'error': _("Error! The provided token invalid, Please refresh the page.")
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed() and request_data["token"] != "":
            return JsonResponse(self.__response.send_private_failure(self.__form.get_errors(with_type=True)))


        result = self.__profile_module.update_access_token(self.__user_id)

        if result != False:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Access token updated successfully.")
            }], {"token": result}))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while updating access token.")
            }]))


    def __update_refresh_token(self, request):

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post", {
            "token" : "",
        })

        self.__form.add_inputs({
            'token': {
                'value': request_data["token"],
                'validate': {
                    'token':{
                        'error': _("Error! The provided token invalid, Please refresh the page.")
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed() and request_data["token"] != "":
            return JsonResponse(self.__response.send_private_failure(self.__form.get_errors(with_type=True)))


        result = self.__profile_module.update_refresh_token(self.__user_id)

        if result != False:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Refresh token updated successfully.")
            }], {"token": result}))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while updating refresh token.")
            }]))
Esempio n. 28
0
class Tag_Image_By_Id(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __task_module = None
    __notification_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__task_module = Task_Module()
        self.__notification_module = Notification_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def post(self, request, host_id):

        self.__user_id = request.user.id
        self.__host_id = host_id

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post", {
            "long_id": "",
            "repository": "",
            "tag": "",
            "force": ""
        })

        self.__form.add_inputs({
            'long_id': {
                'value': request_data["long_id"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'repository': {
                'value': request_data["repository"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'tag': {
                'value': request_data["tag"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'force': {
                'value': request_data["force"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            }
        })

        self.__form.process()

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

        if not self.__host_module.user_owns(self.__host_id, self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Invalid Request.")
                }]))

        _long_id = self.__form.get_input_value("long_id")
        _repository = self.__form.get_input_value("repository")
        _tag = self.__form.get_input_value("tag")
        _force = self.__form.get_input_value("force")

        task = self.__task_module.delay(
            "tag_image_by_id", {
                "host_id": self.__host_id,
                "long_id": _long_id,
                "repository": _repository,
                "tag": _tag,
                "force": _force
            }, self.__user_id)

        if task:

            self.__notification_module.create_notification({
                "highlight":
                "",
                "notification":
                _("Tag docker image as %s:%s") % (_repository, _tag),
                "url":
                "#",
                "type":
                Notification_Module.PENDING,
                "delivered":
                False,
                "user_id":
                self.__user_id,
                "host_id":
                self.__host_id,
                "task_id":
                task.id
            })

            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Request is in progress!")
                }]))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while creating request.")
                }]))
Esempio n. 29
0
class Settings(View):

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

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

    def post(self, request):

        self.__request.set_request(request)
        request_data = self.__request.get_request_data(
            "post", {
                "app_name": "",
                "app_email": "",
                "app_url": "",
                "app_description": "",
                "google_analytics_account": "",
                "reset_mails_messages_count": "",
                "reset_mails_expire_after": "",
                "access_tokens_expire_after": ""
            })

        self.__form.add_inputs({
            'app_name': {
                'value': request_data["app_name"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'alpha_numeric': {
                        'error':
                        _('Error! Application name must be alpha numeric.')
                    },
                    'length_between': {
                        'param': [3, 10],
                        'error':
                        _('Error! Application name must be 5 to 10 characters long.'
                          )
                    }
                }
            },
            'app_email': {
                'value': request_data["app_email"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'email': {
                        'error': _('Error! Application email is invalid.')
                    }
                }
            },
            'app_url': {
                'value': request_data["app_url"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'url': {
                        'error': _('Error! Application url is invalid.')
                    }
                }
            },
            'app_description': {
                'value': request_data["app_description"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [0, 300],
                        'error': _('Error! App description is very long.')
                    },
                    'optional': {}
                }
            },
            'google_analytics_account': {
                'value': request_data["google_analytics_account"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [0, 30],
                        'error':
                        _('Error! Google analytics account is invalid.')
                    },
                    'optional': {}
                }
            },
            'reset_mails_messages_count': {
                'value': request_data["reset_mails_messages_count"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'digit': {
                        'error': _('Error! Reset mails count is invalid.')
                    },
                    'greater_than': {
                        'error': _('Error! Reset mails count is invalid.'),
                        'param': [0]
                    }
                }
            },
            'reset_mails_expire_after': {
                'value': request_data["reset_mails_expire_after"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'digit': {
                        'error':
                        _('Error! Reset mails expiry interval is invalid.')
                    },
                    'greater_than': {
                        'error': _('Error! Reset mails count is invalid.'),
                        'param': [0]
                    }
                }
            },
            'access_tokens_expire_after': {
                'value': request_data["access_tokens_expire_after"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'digit': {
                        'error':
                        _('Error! Access token expiry interval is invalid.')
                    },
                    'greater_than': {
                        'error':
                        _('Error! Access token expiry interval is invalid.'),
                        'param': [0]
                    }
                }
            },
        })

        self.__form.process()

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

        result = self.__settings_module.update_options({
            "app_name":
            self.__form.get_input_value("app_name"),
            "app_email":
            self.__form.get_input_value("app_email"),
            "app_url":
            self.__form.get_input_value("app_url"),
            "app_description":
            self.__form.get_input_value("app_description"),
            "google_analytics_account":
            self.__form.get_input_value("google_analytics_account"),
            "reset_mails_messages_count":
            self.__form.get_input_value("reset_mails_messages_count"),
            "reset_mails_expire_after":
            self.__form.get_input_value("reset_mails_expire_after"),
            "access_tokens_expire_after":
            self.__form.get_input_value("access_tokens_expire_after")
        })

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

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while updating settings.")
                }]))
Esempio n. 30
0
class Search_Community_Images(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __image_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__image_module = Image_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def post(self, request, host_id):

        self.__user_id = request.user.id
        self.__host_id = host_id

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post", {"term": ""})

        self.__form.add_inputs({
            'term': {
                'value': request_data["term"],
                'validate': {
                    'not_empty': {
                        'error': _('Error! Search term is required!')
                    },
                    'length_between': {
                        'param': [1, 100],
                        'error': _('Error! a valid search term is required!')
                    }
                }
            }
        })

        self.__form.process()

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

        if not self.__host_module.user_owns(self.__host_id, self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Invalid Request.")
                }]))

        if self.__image_module.set_host(self.__host_id).check_health():
            result = self.__image_module.search(
                self.__form.get_input_value("term"))
            print(result)
            return JsonResponse(self.__response.send_private_success([], {}))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong with your host!")
                }]))