Esempio n. 1
0
class IncidentUpdatesComponent(View):
    """Remove Component from Incident Update Private Endpoint Controller"""

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

    @allow_if_authenticated
    def delete(self, request, incident_id, update_id, item_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_update_component.delete_one_by_id(item_id):
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Affected component deleted successfully.")
            }], {}, self.__correlation_id))

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

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __incident_update = None
    __task = None
    __notification = None
    __subscriber = None
    __correlation_id = None

    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.__form.add_validator(ExtraRules())

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

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

        task = self.__task.delay("incident_update", {
            "incident_update_id": update_id,
            "user_id": self.__user_id
        }, self.__user_id)

        result = False

        if task:
            result = self.__notification.create_notification({
                "highlight": "Incident Update",
                "notification": "notifying subscribers with the incident update",
                "url": "#",
                "type": NotificationModule.PENDING,
                "delivered": False,
                "user_id": self.__user_id,
                "task_id": task.id
            })

        if task and result:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Notification delivery started successfully.")
            }], {}, self.__correlation_id))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while starting delivery.")
            }], {}, self.__correlation_id))
Esempio n. 3
0
 def test_form_validation_with_param(self):
     form = Form({
         'test_field1': {
             'value': 'Hello World',
             'validate': {
                 'length_between': {
                     'param': [1, 12],
                     'error': 'Input lenght must be between 1 and 12 characters'
                 }
             }
         },
         'test_field2': {
             'value': 'Hello World',
             'validate': {
                 'length_between': {
                     'param': [1, 9],
                     'error': 'Input lenght must be between 1 and 9 characters'
                 }
             }
         }
     })
     form.process()
     errors = form.get_errors()
     self.assertEqual(0, len(errors['test_field1']))
     self.assertEqual(1, len(errors['test_field2']))
     self.assertEqual(True, 'Input lenght must be between 1 and 9 characters' in errors['test_field2'])
Esempio n. 4
0
 def test_form_validation_with_param(self):
     form = Form({
         'test_field1': {
             'value': 'Hello World',
             'validate': {
                 'length_between': {
                     'param': [1, 12],
                     'error':
                     'Input lenght must be between 1 and 12 characters'
                 }
             }
         },
         'test_field2': {
             'value': 'Hello World',
             'validate': {
                 'length_between': {
                     'param': [1, 9],
                     'error':
                     'Input lenght must be between 1 and 12 characters'
                 }
             }
         }
     })
     form.process()
     errors = form.get_errors()
     self.assertEqual(0, len(errors['test_field1']))
     self.assertEqual(1, len(errors['test_field2']))
     self.assertEqual(
         True, 'Input lenght must be between 1 and 12 characters'
         in errors['test_field2'])
Esempio n. 5
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. 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.__install = InstallModule()
     self.__notification = NotificationModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__form.add_validator(ExtraRules())
Esempio n. 10
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. 11
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. 12
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__incident_update_component = IncidentUpdateComponentModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__user_id = None
     self.__correlation_id = ""
     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.__profile_module = ProfileModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__user_id = None
     self.__correlation_id = ""
     self.__form.add_validator(ExtraRules())
Esempio n. 14
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.__form.add_validator(ExtraRules())
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
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. 17
0
class NewRelicApps(View):

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

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__metric = MetricModule()
        self.__logger = self.__helpers.get_logger(__name__)
        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 ""

        result = False
        try:
            result = self.__metric.get_new_relic_apps()
        except Exception as e:
            self.__logger.error(
                _("Error while listing newrelic applications: %(error)s {'correlationId':'%(correlationId)s'}"
                  ) % {
                      "error": str(e),
                      "correlationId": self.__correlation_id
                  })

        if result is False:
            return JsonResponse(
                self.__response.send_private_failure(
                    [{
                        "type": "error",
                        "message": _("Error! Connecting to New Relic.")
                    }], {}, self.__correlation_id))

        return JsonResponse(
            self.__response.send_private_success([], {'apps': result},
                                                 self.__correlation_id))
Esempio n. 18
0
    def test_validation_sanitization(self):
        form = Form({
            'test_field': {
                'value': '*****@*****.**',
                'sanitize': {
                    'escape': {}
                },
                'validate': {
                    'email': {
                        'error': 'Please provide a valid email.'
                    }
                }
            }
        })
        form.process()
        inputs = form.get_inputs()
        errors = form.get_errors()
        self.assertEqual([], errors['test_field'])
        self.assertEqual(True, inputs['test_field']['status'])
        self.assertEqual(True, inputs['test_field']['is_exact'])
        self.assertEqual('*****@*****.**', inputs['test_field']['value'])
        self.assertEqual('*****@*****.**', inputs['test_field']['svalue'])

        form = Form({
            'test_field': {
                'value': 'hello@[email protected]',
                'sanitize': {
                    'escape': {}
                },
                'validate': {
                    'email': {
                        'error': 'Please provide a valid email.'
                    }
                }
            }
        })
        form.process()
        inputs = form.get_inputs()
        errors = form.get_errors()
        self.assertEqual(['Please provide a valid email.'], errors['test_field'])
        self.assertEqual(False, inputs['test_field']['status'])
        self.assertEqual(True, inputs['test_field']['is_exact'])
        self.assertEqual('hello@[email protected]', inputs['test_field']['value'])
        self.assertEqual('hello@[email protected]', inputs['test_field']['svalue'])
Esempio n. 19
0
 def test_form(self):
     form = Form({
         'user_email': {
             'value': '',
             'validate': {
                 'not_empty': {
                     'error': 'User email must be provided'
                 },
                 'email': {
                     'error': 'User email is invalid'
                 }
             }
         }
     })
     form.process()
     errors = form.get_errors()
     self.assertEqual(2, len(errors['user_email']))
     self.assertEqual(True, 'User email must be provided' in errors['user_email'])
     self.assertEqual(True, 'User email is invalid' in errors['user_email'])
Esempio n. 20
0
 def test_form(self):
     form = Form({
         'user_email': {
             'value': '',
             'validate': {
                 'not_empty': {
                     'error': 'User email must be provided'
                 },
                 'email': {
                     'error': 'User email is invalid'
                 }
             }
         }
     })
     form.process()
     errors = form.get_errors()
     self.assertEqual(2, len(errors['user_email']))
     self.assertEqual(True, 'User email must be provided'
                      in errors['user_email'])
     self.assertEqual(True, 'User email is invalid' in errors['user_email'])
Esempio n. 21
0
 def test_custom_sanitizer(self):
     form = Form({
         'test_field': {
             'value': 'Hello World',
             'sanitize': {
                 'clear_spaces': {},
                 'lower_case': {}
             }
         }
     })
     form.add_sanitizer(MySanitizer())
     form.process()
     inputs = form.get_inputs()
     self.assertEqual('helloworld', inputs['test_field']['svalue'])
Esempio n. 22
0
 def test_custom_validator(self):
     form = Form({
         'user_name': {
             'value': '',
             'validate': {
                 'username': {
                     'error': 'Invalid Username'
                 }
             }
         }
     })
     form.add_validator(MyValidator())
     form.process()
     errors = form.get_errors()
     self.assertEqual(1, len(errors['user_name']))
     self.assertEqual(True, 'Invalid Username' in errors['user_name'])
Esempio n. 23
0
 def test_custom_sanitizer(self):
     form = Form({
         'test_field': {
             'value': 'Hello World',
             'sanitize': {
                 'clear_spaces': {},
                 'lower_case': {}
             }
         }
     })
     form.add_sanitizer(MySanitizer())
     form.process()
     inputs = form.get_inputs()
     self.assertEqual('helloworld', inputs['test_field']['svalue'])
Esempio n. 24
0
 def test_custom_validator(self):
     form = Form({
         'user_name': {
             'value': '',
             'validate': {
                 'username': {
                     'error': 'Invalid Username'
                 }
             }
         }
     })
     form.add_validator(MyValidator())
     form.process()
     errors = form.get_errors()
     self.assertEqual(1, len(errors['user_name']))
     self.assertEqual(True, 'Invalid Username' in errors['user_name'])
Esempio n. 25
0
class Subscriber(View):

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

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

    @allow_if_authenticated
    def post(self, request, subscriber_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", {
                "type": "",
                "email": "",
                "phone": "",
                "endpoint": "",
                "auth_token": "",
                "status": ""
            })

        if request_data["type"] == "email":

            self.__form.add_inputs({
                'type': {
                    'value': request_data["type"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'any_of': {
                            'param': [["email", "phone", "endpoint"]],
                            'error': _('Error! Type is invalid.')
                        }
                    }
                },
                'email': {
                    'value': request_data["email"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {}
                },
                'status': {
                    'value': request_data["status"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'any_of': {
                            'param': [["pending", "verified", "unverified"]],
                            'error': _('Error! Status is invalid.')
                        }
                    }
                }
            })

        elif request_data["type"] == "phone":

            self.__form.add_inputs({
                'type': {
                    'value': request_data["type"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'any_of': {
                            'param': [["email", "phone", "endpoint"]],
                            'error': _('Error! Type is invalid.')
                        }
                    }
                },
                'phone': {
                    'value': request_data["phone"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {}
                },
                'status': {
                    'value': request_data["status"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'any_of': {
                            'param': [["pending", "verified", "unverified"]],
                            'error': _('Error! Status is invalid.')
                        }
                    }
                }
            })

        else:

            self.__form.add_inputs({
                'type': {
                    'value': request_data["type"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'any_of': {
                            'param': [["email", "phone", "endpoint"]],
                            'error': _('Error! Type is invalid.')
                        }
                    }
                },
                'email': {
                    'value': request_data["email"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {}
                },
                'endpoint': {
                    'value': request_data["endpoint"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {}
                },
                'auth_token': {
                    'value': request_data["auth_token"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {}
                },
                'status': {
                    'value': request_data["status"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'any_of': {
                            'param': [["pending", "verified", "unverified"]],
                            'error': _('Error! Status 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))

        if request_data["type"] == "email":

            result = self.__subscriber.update_one_by_id(
                subscriber_id, {
                    "status": self.__form.get_sinput("status"),
                    "type": self.__form.get_sinput("type"),
                    "email": self.__form.get_sinput("email"),
                    "phone": "",
                    "endpoint": "",
                    "auth_token": ""
                })

        elif request_data["type"] == "phone":

            result = self.__subscriber.update_one_by_id(
                subscriber_id, {
                    "status": self.__form.get_sinput("status"),
                    "type": self.__form.get_sinput("type"),
                    "email": "",
                    "phone": self.__form.get_sinput("phone"),
                    "endpoint": "",
                    "auth_token": ""
                })

        else:

            result = self.__subscriber.update_one_by_id(
                subscriber_id, {
                    "status": self.__form.get_sinput("status"),
                    "type": self.__form.get_sinput("type"),
                    "email": self.__form.get_sinput("email"),
                    "phone": "",
                    "endpoint": self.__form.get_sinput("endpoint"),
                    "auth_token": self.__form.get_sinput("auth_token")
                })

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

    @allow_if_authenticated
    def delete(self, request, subscriber_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.__subscriber.delete_one_by_id(subscriber_id):
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Subscriber deleted successfully.")
                    }], {}, self.__correlation_id))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while deleting subscriber.")
                }], {}, self.__correlation_id))
class ForgotPassword(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __forgot_password = None
    __logger = None
    __correlation_id = None

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

    @stop_request_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", {
            "email": ""
        })

        self.__form.add_inputs({
            'email': {
                'value': request_data["email"],
                'sanitize': {
                    'escape': {},
                    'strip': {}
                },
                'validate': {
                    'sv_email': {
                        'error': _('Error! Email 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))

        if not self.__forgot_password.check_email(self.__form.get_sinput("email")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Email is not exist.")
            }], {}, self.__correlation_id))

        reset_request = self.__forgot_password.reset_request_exists(self.__form.get_sinput("email"))

        if reset_request:
            if self.__forgot_password.is_spam(reset_request):
                return JsonResponse(self.__response.send_private_failure([{
                    "type": "error",
                    "message": _("Sorry! You already exceeded the maximum number of reset requests!")
                }], {}, self.__correlation_id))
            token = self.__forgot_password.update_request(reset_request)
        else:
            token = self.__forgot_password.create_request(self.__form.get_sinput("email"))

        if not token:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while creating reset request.")
            }], {}, self.__correlation_id))

        message = self.__forgot_password.send_message(self.__form.get_sinput("email"), token)

        if not message:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while sending reset instructions.")
            }], {}, self.__correlation_id))
        else:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Reset instructions sent successfully.")
            }], {}, self.__correlation_id))
Esempio n. 27
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. 28
0
class ResetPassword(View):

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

    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.__form.add_validator(ExtraRules())

    @stop_request_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", {
            "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': {
                    'sv_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_errors_failure(self.__form.get_errors(),
                                                    {}, self.__correlation_id))

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

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

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

        if not result:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while resetting password.")
                }], {}, self.__correlation_id))
        else:
            return JsonResponse(
                self.__response.send_private_success(
                    [{
                        "type": "success",
                        "message": _("Password updated successfully.")
                    }], {}, self.__correlation_id))
Esempio n. 29
0
class User(View):
    """Update and Delete User Private Endpoint Controller"""
    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__user = UserModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__user_id = None
        self.__correlation_id = ""
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated_and_has_permission("manage_settings")
    def post(self, request, user_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", {
                "first_name": "",
                "last_name": "",
                "username": "",
                "role": "",
                "email": "",
                "update_password": "",
                "password": ""
            })

        if request_data["update_password"] == "":
            self.__form.add_inputs({
                'first_name': {
                    'value': request_data["first_name"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_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': {
                        'sv_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': {
                        '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': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_email': {
                            'error': _('Error! Email is invalid.')
                        }
                    }
                },
                'role': {
                    'value': request_data["role"],
                    'validate': {
                        'any_of': {
                            'param': [["admin", "user"]],
                            'error': _('Error! Role is invalid.')
                        }
                    }
                }
            })
        else:
            self.__form.add_inputs({
                'first_name': {
                    'value': request_data["first_name"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_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': {
                        'sv_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': {
                        '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': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_email': {
                            'error': _('Error! Email is invalid.')
                        }
                    }
                },
                'password': {
                    'value': request_data["password"],
                    'validate': {
                        'sv_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.'
                              )
                        }
                    }
                },
                'role': {
                    'value': request_data["role"],
                    'validate': {
                        'any_of': {
                            'param': [["admin", "user"]],
                            'error': _('Error! Role 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))

        if self.__user.username_used_elsewhere(
                user_id, self.__form.get_sinput("username")):
            return JsonResponse(
                self.__response.send_private_failure(
                    [{
                        "type": "error",
                        "message": _("Error! Username is already used.")
                    }], {}, self.__correlation_id))

        if self.__user.email_used_elsewhere(user_id,
                                            self.__form.get_sinput("email")):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Email is already used for other account.")
                }], {}, self.__correlation_id))

        if request_data["update_password"] == "":

            result = self.__user.update_one_by_id(
                user_id, {
                    "username":
                    self.__form.get_sinput("username"),
                    "email":
                    self.__form.get_sinput("email"),
                    "first_name":
                    self.__form.get_sinput("first_name"),
                    "last_name":
                    self.__form.get_sinput("last_name"),
                    "is_superuser":
                    True
                    if self.__form.get_sinput("role") == "admin" else False
                })

        else:

            result = self.__user.update_one_by_id(
                user_id, {
                    "username":
                    self.__form.get_sinput("username"),
                    "email":
                    self.__form.get_sinput("email"),
                    "first_name":
                    self.__form.get_sinput("first_name"),
                    "last_name":
                    self.__form.get_sinput("last_name"),
                    "password":
                    self.__form.get_sinput("password"),
                    "is_superuser":
                    True
                    if self.__form.get_sinput("role") == "admin" else False
                })

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

    @allow_if_authenticated_and_has_permission("manage_settings")
    def delete(self, request, user_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.__user_id == user_id:
            return JsonResponse(
                self.__response.send_private_failure(
                    [{
                        "type": "error",
                        "message": _("Error! You can't delete your account.")
                    }], {}, self.__correlation_id))

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

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while deleting a user.")
                }], {}, self.__correlation_id))
Esempio n. 30
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. 31
0
class Users(View):
    """Create and List Users Private Endpoint Controller"""
    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__user = UserModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__user_id = None
        self.__correlation_id = ""
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated_and_has_permission("manage_settings")
    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", {
                "invitation": "",
                "first_name": "",
                "last_name": "",
                "username": "",
                "role": "",
                "email": "",
                "password": ""
            })

        if request_data["invitation"] != "":

            self.__form.add_inputs({
                'first_name': {
                    'value': request_data["first_name"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_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': {
                        'sv_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': {
                        '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': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_email': {
                            'error': _('Error! User email is invalid.')
                        }
                    }
                },
                'password': {
                    'value': request_data["password"],
                    'validate': {
                        'sv_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.'
                              )
                        }
                    }
                },
                'role': {
                    'value': request_data["role"],
                    'validate': {
                        'any_of': {
                            'param': [["admin", "user"]],
                            'error': _('Error! Role is invalid.')
                        }
                    }
                }
            })

        else:

            self.__form.add_inputs({
                'email': {
                    'value': request_data["email"],
                    'sanitize': {
                        'strip': {}
                    },
                    'validate': {
                        'sv_email': {
                            'error': _('Error! User email is invalid.')
                        }
                    }
                },
                'role': {
                    'value': request_data["role"],
                    'validate': {
                        'any_of': {
                            'param': [["admin", "user"]],
                            'error': _('Error! Role 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))

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

        if request_data["invitation"] != "" and self.__user.username_used(
                self.__form.get_sinput("username")):
            return JsonResponse(
                self.__response.send_private_failure(
                    [{
                        "type": "error",
                        "message": _("Error! Username is already used.")
                    }], {}, self.__correlation_id))

        if request_data["invitation"] != "":

            result = self.__user.insert_one({
                "username":
                self.__form.get_sinput("username"),
                "email":
                self.__form.get_sinput("email"),
                "first_name":
                self.__form.get_sinput("first_name"),
                "last_name":
                self.__form.get_sinput("last_name"),
                "password":
                self.__form.get_sinput("password"),
                "is_staff":
                False,
                "is_active":
                True,
                "is_superuser":
                True if self.__form.get_sinput("role") == "admin" else False
            })

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

            self.__user.delete_register_request_by_email(
                self.__form.get_sinput("email"))

            token = self.__user.create_register_request(
                self.__form.get_sinput("email"),
                self.__form.get_sinput("role"))

            if not token:
                return JsonResponse(
                    self.__response.send_private_failure([{
                        "type":
                        "error",
                        "message":
                        _("Error! Something goes wrong while creating reset request."
                          )
                    }], {}, self.__correlation_id))

            message = self.__user.send_register_request_message(
                self.__form.get_sinput("email"), token)

            if not message:
                return JsonResponse(
                    self.__response.send_private_failure([{
                        "type":
                        "error",
                        "message":
                        _("Error! Something goes wrong while sending register request."
                          )
                    }], {}, self.__correlation_id))
            else:
                return JsonResponse(
                    self.__response.send_private_success([{
                        "type":
                        "success",
                        "message":
                        _("Register Request instructions sent successfully.")
                    }], {}, self.__correlation_id))

    @allow_if_authenticated_and_has_permission("manage_settings")
    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": 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(
                [], {
                    'users':
                    self.__format_users(self.__user.get_all(offset, limit)),
                    'metadata': {
                        'offset': offset,
                        'limit': limit,
                        'count': self.__user.count_all()
                    }
                }, self.__correlation_id))

    def __format_users(self, users):
        users_list = []

        for user in users:
            users_list.append({
                "id":
                user.id,
                "username":
                user.username,
                "first_name":
                user.first_name,
                "last_name":
                user.last_name,
                "email":
                user.email,
                "role":
                "Admin" if user.is_superuser == 1 else "User",
                "created_at":
                user.date_joined.strftime("%b %d %Y %H:%M:%S"),
                "edit_url":
                reverse("app.web.admin.user.edit", kwargs={'user_id':
                                                           user.id}),
                "delete_url":
                reverse("app.api.private.v1.admin.user.endpoint",
                        kwargs={'user_id': user.id})
            })

        return users_list
Esempio n. 32
0
class Register(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __user = None
    __logger = None
    __correlation_id = None

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

    @stop_request_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", {
            "register_request_token": "",
            "first_name": "",
            "last_name": "",
            "username": "",
            "email": "",
            "password": ""
        })

        self.__form.add_inputs({
            'first_name': {
                'value': request_data["first_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'sv_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': {
                    'sv_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': {
                    'sv_email': {
                        'error': _('Error! Admin email is invalid.')
                    }
                }
            },
            'password': {
                'value': request_data["password"],
                'validate': {
                    'sv_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_errors_failure(self.__form.get_errors(), {}, self.__correlation_id))

        register_request = self.__user.get_register_request_by_token(request_data["register_request_token"])

        if not register_request:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Register token is invalid or expired.")
            }], {}, self.__correlation_id))

        payload = json.loads(register_request.payload)

        if self.__user.username_used(self.__form.get_sinput("username")):
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Username is already used.")
            }], {}, self.__correlation_id))

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

        result = self.__user.insert_one({
            "username": self.__form.get_sinput("username"),
            "email": self.__form.get_sinput("email"),
            "first_name": self.__form.get_sinput("first_name"),
            "last_name": self.__form.get_sinput("last_name"),
            "password": self.__form.get_sinput("password"),
            "is_staff": False,
            "is_active": True,
            "is_superuser": True if payload["role"] == "admin" else False
        })

        if result:
            self.__user.delete_register_request_by_token(request_data["register_request_token"])
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Account created successfully.")
            }], {}, self.__correlation_id))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while creating your account.")
            }], {}, self.__correlation_id))
Esempio n. 33
0
class Settings(View):
    """Update Settings Private Endpoint Controller"""
    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.__correlation_id = ""
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated_and_has_permission("manage_settings")
    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", {
                "app_name": "",
                "app_email": "",
                "app_url": "",
                "app_description": "",
                "google_analytics_account": "",
                "reset_mails_messages_count": "",
                "reset_mails_expire_after": "",
                "access_tokens_expire_after": "",
                "prometheus_token": "",
                "newrelic_api_key": ""
            })

        self.__form.add_inputs({
            'app_name': {
                'value': request_data["app_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'alpha_numeric': {
                        'error':
                        _('Error! Application name must be alpha numeric.')
                    },
                    'length_between': {
                        'param': [2, 30],
                        'error':
                        _('Error! Application name must be 2 to 30 characters long.'
                          )
                    }
                }
            },
            'app_email': {
                'value': request_data["app_email"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'sv_email': {
                        'error': _('Error! Application email is invalid.')
                    }
                }
            },
            'app_url': {
                'value': request_data["app_url"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'sv_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': {}
                }
            },
            "prometheus_token": {
                'value': request_data["prometheus_token"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [0, 100],
                        'error': _('Error! Prometheus token is invalid.')
                    },
                    'optional': {}
                }
            },
            "newrelic_api_key": {
                'value': request_data["newrelic_api_key"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'length_between': {
                        'param': [0, 100],
                        'error': _('Error! Prometheus token is invalid.')
                    },
                    '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': int(request_data["reset_mails_messages_count"]),
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'greater_than': {
                        'error': _('Error! Reset mails count is invalid.'),
                        'param': [0]
                    }
                }
            },
            'reset_mails_expire_after': {
                'value': int(request_data["reset_mails_expire_after"]),
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'greater_than': {
                        'error': _('Error! Reset mails count is invalid.'),
                        'param': [0]
                    }
                }
            },
            'access_tokens_expire_after': {
                'value': int(request_data["access_tokens_expire_after"]),
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    '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_errors_failure(self.__form.get_errors(),
                                                    {}, self.__correlation_id))

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

        if result:

            self.__activity_module.track(
                request.user.id, _('You updated application settings.'))

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

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

    __helpers = None
    __form = None
    __logger = None
    __option_entity = OptionEntity()
    __user_entity = UserEntity()
    __data = {
        "AUTHOR": AUTHOR,
        "COPYRIGHT": COPYRIGHT,
        "LICENSE": LICENSE,
        "VERSION": VERSION,
        "MAINTAINER": MAINTAINER,
        "EMAIL": EMAIL,
        "STATUS": STATUS,
        "REPO_URL": REPO_URL,
        "AUTHOR_URL": AUTHOR_URL,
        "RELEASES": RELEASES,
        "SUPPORT_URL": SUPPORT_URL
    }

    def json(self,
             messages,
             payload={},
             status="success",
             status_code=HTTPStatus.OK):
        response = {"status": status}

        # if validation messages
        if isinstance(messages, dict):
            errors = []
            for input_key, error_list in messages.items():
                for error in error_list:
                    errors.append({"type": "error", "message": error})
            messages = errors

        if not isinstance(messages, list):
            raise ServerError(
                _("Invalid messages type %s passed to controller.json") %
                (type(messages)))

        response["messages"] = messages

        # Change status to failure if one message has type error
        for message in messages:
            if message["type"] == "error":
                response["status"] = "failure"

        if len(payload) > 0:
            response["payload"] = payload

        return JsonResponse(response, status=status_code)

    def correlation(self, request):
        return request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""

    def logger(self, request):
        if not self.__logger:
            self.__helpers = self.helpers()
            self.__logger = self.__helpers.get_logger(__name__)

        return self.__logger

    def get_request_data(self, request, method, predicted):
        request_data = {}
        log_data = {}
        data_bag = request.POST if method.lower() == "post" else request.GET

        for key, default in predicted.items():
            if "password" in key:
                log_data[key] = "<hidden>" if key in data_bag else default
            elif "token" in key:
                log_data[key] = "<hidden>" if key in data_bag else default
            else:
                log_data[key] = data_bag[key] if key in data_bag else default
            request_data[key] = data_bag[key] if key in data_bag else default

        self.logger(request).info(
            _("Required request data: %(data)s") %
            {"data": self.helpers().json_dumps(log_data)})

        return request_data

    def helpers(self):
        if not self.__helpers:
            self.__helpers = Helpers()
        return self.__helpers

    def form(self):
        if not self.__form:
            self.__form = Form()
            self.__form.add_validator(ExtraRules())
        return self.__form

    def load_options(self, options):
        options_to_load = {}
        for key in options.keys():
            options_to_load[key] = options[key]
            if key not in self.__data.keys():
                self.__data[key] = options[key]

        if len(options_to_load.keys()) > 0:
            new_options = self.__option_entity.get_many_by_keys(
                options_to_load.keys())
            for option in new_options:
                self.__data[option.key] = option.value

    def autoload_options(self):
        options = self.__option_entity.get_many_by_autoload(True)
        for option in options:
            self.__data[option.key] = option.value

    def autoload_user(self, user_id):
        user_data = {
            "user_first_name": "",
            "user_last_name": "",
            "user_username": "",
            "user_email": "",
            "user_avatar": ""
        }

        if user_id is not None:
            user = self.__user_entity.get_one_by_id(user_id)
            if user is not False:
                user_data["user_first_name"] = user.first_name
                user_data["user_last_name"] = user.last_name
                user_data["user_username"] = user.username
                user_data["user_email"] = user.email
                user_data["user_avatar"] = Gravatar(user.email).get_image()

        self.__data.update(user_data)

    def context_push(self, new_data):
        self.__data.update(new_data)

    def context_get(self, key=None, default=None):
        if key is not None:
            return self.__data[key] if key in self.__data else default
        return self.__data
Esempio n. 35
0
 def form(self):
     if not self.__form:
         self.__form = Form()
         self.__form.add_validator(ExtraRules())
     return self.__form