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'])
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'])
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'])
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'])
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'])
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))
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))
class BuilderSettings(View): __request = None __response = None __helpers = None __form = None __logger = None __user_id = None __settings = None __correlation_id = None def __init__(self): self.__request = Request() self.__response = Response() self.__helpers = Helpers() self.__settings = Settings() self.__form = Form() self.__logger = self.__helpers.get_logger(__name__) 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", { "builder_headline": "", "builder_favicon_url": "", "builder_logo_url": "", "builder_about": "" }) self.__form.add_inputs({ 'builder_headline': { 'value': request_data["builder_headline"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [0, 100], 'error': _('Error! Headline is very long.') }, 'optional': {} } }, 'builder_favicon_url': { 'value': request_data["builder_favicon_url"], 'sanitize': { 'escape': {}, 'strip': {} }, 'validate': { 'sv_url': { 'error': _('Error! Favicon URL is invalid.') } } }, 'builder_logo_url': { 'value': request_data["builder_logo_url"], 'sanitize': { 'escape': {}, 'strip': {} }, 'validate': { 'sv_url': { 'error': _('Error! Logo URL is invalid.') } } }, 'builder_about': { 'value': request_data["builder_about"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [0, 20000], 'error': _('Error! About is very long.') }, 'optional': {} } }, }) 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.update_options({ "builder_headline": self.__form.get_sinput("builder_headline"), "builder_favicon_url": self.__form.get_sinput("builder_favicon_url"), "builder_logo_url": self.__form.get_sinput("builder_logo_url"), "builder_about": self.__form.get_sinput("builder_about") }) if result: 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))
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 Profile(View): """Update Profile Private Endpoint Controller""" 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()) @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", { "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_errors_failure(self.__form.get_errors(), {}, self.__correlation_id)) if self.__form.get_sinput("action") == "_update_profile": return self.__update_profile(request) elif self.__form.get_sinput("action") == "_update_password": return self.__update_password(request) elif self.__form.get_sinput("action") == "_update_access_token": return self.__update_access_token(request) elif self.__form.get_sinput("action") == "_update_refresh_token": return self.__update_refresh_token(request) def __update_profile(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", { "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': { '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! 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': { 'strip': {} }, 'validate': { 'sv_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': { 'strip': {} }, 'validate': { 'sv_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': { 'strip': {} }, 'validate': { 'sv_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_errors_failure(self.__form.get_errors(), {}, self.__correlation_id)) if self.__profile_module.username_used_elsewhere(self.__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.__profile_module.email_used_elsewhere(self.__user_id, self.__form.get_sinput("email")): return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Email is already used.") }], {}, self.__correlation_id)) result = self.__profile_module.update_profile(self.__user_id, { "first_name": self.__form.get_sinput("first_name"), "last_name": self.__form.get_sinput("last_name"), "username": self.__form.get_sinput("username"), "email": self.__form.get_sinput("email"), "job_title": self.__form.get_sinput("job_title"), "company": self.__form.get_sinput("company"), "address": self.__form.get_sinput("address"), "github_url": self.__form.get_sinput("github_url"), "twitter_url": self.__form.get_sinput("twitter_url"), "facebook_url": self.__form.get_sinput("facebook_url") }) if result: return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("Profile updated successfully.") }], {}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while updating your profile.") }], {}, self.__correlation_id)) def __update_password(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", { "old_password": "", "new_password": "" }) self.__form.add_inputs({ 'old_password': { 'value': request_data["old_password"], 'validate': { 'sv_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': { 'sv_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_errors_failure(self.__form.get_errors(), {}, self.__correlation_id)) if not self.__profile_module.validate_password(self.__user_id, self.__form.get_sinput("old_password")): return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Old password is invalid.") }], {}, self.__correlation_id)) result = self.__profile_module.change_password(self.__user_id, self.__form.get_sinput("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.") }], {}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while updating your password.") }], {}, self.__correlation_id)) def __update_access_token(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", { "token": "", }) self.__form.add_inputs({ 'token': { 'value': request_data["token"], 'validate': { 'sv_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_errors_failure(self.__form.get_errors(), {}, self.__correlation_id)) result = self.__profile_module.update_access_token(self.__user_id) if result: return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("Access token updated successfully.") }], {"token": result}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while updating access token.") }], {}, self.__correlation_id)) def __update_refresh_token(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", { "token": "", }) self.__form.add_inputs({ 'token': { 'value': request_data["token"], 'validate': { 'sv_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_errors_failure(self.__form.get_errors(), {}, self.__correlation_id)) result = self.__profile_module.update_refresh_token(self.__user_id) if result: return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("Refresh token updated successfully.") }], {"token": result}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while updating refresh token.") }], {}, self.__correlation_id))
class Metric(View): """Update and Delete Metric Private Endpoint Controller""" 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.__user_id = None self.__correlation_id = "" self.__form.add_validator(ExtraRules()) @allow_if_authenticated def post(self, request, metric_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", { "title": "", "description": "", "source": "", "application": "", "metric": "", "x_axis": "", "y_axis": "" }) self.__form.add_inputs({ 'title': { 'value': request_data["title"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [1, 60], 'error': _('Error! Metric title must be 1 to 60 characters long.' ) } } }, 'description': { 'value': request_data["description"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [0, 150], 'error': _('Error! Metric description must be less than 150 characters long.' ) }, 'optional': {} } }, 'source': { 'value': request_data["source"], 'sanitize': { 'strip': {} }, 'validate': { 'any_of': { 'param': [["newrelic"]], 'error': _('Error! Source is invalid.') } } }, 'application': { 'value': request_data["application"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [1, 60], 'error': _('Error! Application must be 1 to 60 characters long.' ) } } }, 'metric': { 'value': request_data["metric"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [1, 60], 'error': _('Error! Metric must be 1 to 60 characters long.') } } }, 'x_axis': { 'value': request_data["x_axis"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [1, 40], 'error': _('Error! X-Axis label must be 1 to 40 characters long.' ) } } }, 'y_axis': { 'value': request_data["y_axis"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [1, 40], 'error': _('Error! Y-Axis label must be 1 to 40 characters long.' ) } } } }) self.__form.process() if not self.__form.is_passed(): return JsonResponse( self.__response.send_errors_failure(self.__form.get_errors(), {}, self.__correlation_id)) current_metric = self.__metric.get_one_by_title( self.__form.get_sinput("title")) if current_metric and not current_metric["id"] == metric_id: return JsonResponse( self.__response.send_private_failure( [{ "type": "error", "message": _("Error! Metric title is used before.") }], {}, self.__correlation_id)) result = self.__metric.update_one_by_id( metric_id, { "title": self.__form.get_sinput("title"), "description": self.__form.get_sinput("description"), "source": self.__form.get_sinput("source"), "x_axis": self.__form.get_sinput("x_axis"), "y_axis": self.__form.get_sinput("y_axis"), "data": '{"application":"%s", "metric":"%s"}' % (self.__form.get_sinput("application"), self.__form.get_sinput("metric")) }) if result: return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("Metric updated successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while updating metric.") }], {}, self.__correlation_id)) @allow_if_authenticated def delete(self, request, metric_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.__metric.delete_one_by_id(metric_id): return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("Metric deleted successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while deleting metric.") }], {}, self.__correlation_id))
class Metrics(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 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", { "title": "", "description": "", "source": "", "application": "", "metric": "", "x_axis": "", "y_axis": "" }) self.__form.add_inputs({ 'title': { 'value': request_data["title"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'description': { 'value': request_data["description"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'source': { 'value': request_data["source"], 'validate': { 'any_of': { 'param': [["newrelic"]], 'error': _('Error! Source is invalid.') } } }, 'application': { 'value': request_data["application"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'metric': { 'value': request_data["metric"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'x_axis': { 'value': request_data["x_axis"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'y_axis': { 'value': request_data["y_axis"], 'sanitize': { 'strip': {} }, 'validate': {} } }) 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.__metric.insert_one({ "title": self.__form.get_sinput("title"), "description": self.__form.get_sinput("description"), "source": self.__form.get_sinput("source"), "x_axis": self.__form.get_sinput("x_axis"), "y_axis": self.__form.get_sinput("y_axis"), "data": '{"application":"%s", "metric":"%s"}' % (self.__form.get_sinput("application"), self.__form.get_sinput("metric")) }) if result: return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("Metric created successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while creating metric.") }], {}, 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( [], { 'metrics': self.__format_metrics(self.__metric.get_all(offset, limit)), 'metadata': { 'offset': offset, 'limit': limit, 'count': self.__metric.count_all() } }, self.__correlation_id)) def __format_metrics(self, metrics): metrics_list = [] for metric in metrics: metrics_list.append({ "id": metric.id, "title": metric.title, "source": metric.source.title(), "created_at": metric.created_at.strftime("%b %d %Y %H:%M:%S"), "edit_url": reverse("app.web.admin.metric.edit", kwargs={'metric_id': metric.id}), "delete_url": reverse("app.api.private.v1.admin.metric.endpoint", kwargs={'metric_id': metric.id}) }) return metrics_list
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
class IncidentUpdates(View): __request = None __response = None __helpers = None __form = None __logger = None __user_id = None __incident = None __incident_update = None __task = None __notification = None __subscriber = None __incident_update_notification = None __correlation_id = None def __init__(self): self.__request = Request() self.__response = Response() self.__helpers = Helpers() self.__form = Form() self.__incident = IncidentModule() self.__incident_update = IncidentUpdateModule() self.__task = Task_Module() self.__notification = NotificationModule() self.__subscriber = SubscriberModule() self.__incident_update_notification = IncidentUpdateNotificationModule() 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.__user_id = request.user.id self.__request.set_request(request) request_data = self.__request.get_request_data("post", { "status": "", "notify_subscribers": "", "message": "", "datetime": "", }) self.__form.add_inputs({ 'message': { 'value': request_data["message"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'datetime': { 'value': request_data["datetime"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'status': { 'value': request_data["status"], 'validate': { 'any_of': { 'param': [["investigating", "identified", "monitoring", "update", "resolved"]], 'error': _('Error! Status is invalid.') } } }, 'notify_subscribers': { 'value': request_data["notify_subscribers"], 'validate': { 'any_of': { 'param': [["on", "off"]], 'error': _('Error! Notify subscribers 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.insert_one({ "notify_subscribers": self.__form.get_sinput("notify_subscribers"), "datetime": DateTimeField().clean(self.__form.get_sinput("datetime")), "total_suscribers": self.__subscriber.count_by_status(SubscriberModule.VERIFIED), "message": self.__form.get_sinput("message"), "status": self.__form.get_sinput("status"), "incident_id": incident_id }) if self.__form.get_sinput("status") == "resolved": self.__incident.update_one_by_id(incident_id, { "status": "closed" }) else: self.__incident.update_one_by_id(incident_id, { "status": "open" }) if result: return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("Incident update created successfully.") }], {}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while creating update.") }], {}, self.__correlation_id)) @allow_if_authenticated def get(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("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([], { 'updates': self.__format_incident_updates(self.__incident_update.get_all(incident_id, offset, limit), incident_id), 'metadata': { 'offset': offset, 'limit': limit, 'count': self.__incident_update.count_all(incident_id) } }, self.__correlation_id)) def __format_incident_updates(self, updates, incident_id): updates_list = [] for update in updates: notified_subscribers = self.__incident_update_notification.count_by_update_status( update.id, IncidentUpdateNotificationModule.SUCCESS ) progress = int(notified_subscribers/update.total_suscribers) * 100 if update.total_suscribers > 0 else 0 updates_list.append({ "id": update.id, "status": update.status.title(), "notify_subscribers": update.notify_subscribers.title(), "datetime": update.datetime.strftime("%b %d %Y %H:%M:%S"), "progress": progress if progress <= 100 else 100, "created_at": update.created_at.strftime("%b %d %Y %H:%M:%S"), "view_url": reverse("app.web.admin.incident_update.view", kwargs={'incident_id': incident_id, "update_id": update.id}), "edit_url": reverse("app.web.admin.incident_update.edit", kwargs={'incident_id': incident_id, "update_id": update.id}), "delete_url": reverse("app.api.private.v1.admin.incident_update.endpoint", kwargs={'incident_id': incident_id, "update_id": update.id}) }) return updates_list
class IncidentUpdatesComponents(View): __request = None __response = None __helpers = None __form = None __logger = None __user_id = None __incident_update = None __task = None __notification = None __subscriber = None __incident_update_component = 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.__incident_update_component = IncidentUpdateComponentModule() 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 self.__request.set_request(request) request_data = self.__request.get_request_data("post", { "type": "", "component_id": "" }) self.__form.add_inputs({ 'component_id': { 'value': request_data["component_id"], 'validate': { 'sv_numeric': { 'error': _('Error! Component is required.') } } }, 'type': { 'value': request_data["type"], 'validate': { 'any_of': { 'param': [["operational", "degraded_performance", "partial_outage", "major_outage", "maintenance"]], 'error': _('Error! Type is required.') } } } }) 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_component.insert_one({ "component_id": int(self.__form.get_sinput("component_id")), "type": self.__form.get_sinput("type"), "incident_update_id": int(update_id) }) if result: return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("Affected component created successfully.") }], {}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while creating affected component.") }], {}, self.__correlation_id))
class IncidentUpdate(View): __request = None __response = None __helpers = None __form = None __logger = None __user_id = None __incident_update = None __correlation_id = None 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.__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.__request.set_request(request) request_data = self.__request.get_request_data("post", { "status": "", "notify_subscribers": "", "message": "", "datetime": "", }) self.__form.add_inputs({ 'message': { 'value': request_data["message"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'datetime': { 'value': request_data["datetime"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'status': { 'value': request_data["status"], 'validate': { 'any_of': { 'param': [["investigating", "identified", "monitoring", "update", "resolved"]], 'error': _('Error! Status is invalid.') } } }, 'notify_subscribers': { 'value': request_data["notify_subscribers"], 'validate': { 'any_of': { 'param': [["on", "off"]], 'error': _('Error! Notify subscribers 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.update_one_by_id(update_id, { "notify_subscribers": self.__form.get_sinput("notify_subscribers"), "datetime": DateTimeField().clean(self.__form.get_sinput("datetime")), "message": self.__form.get_sinput("message"), "status": self.__form.get_sinput("status") }) if result: return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("Incident update updated successfully.") }], {}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while updating update.") }], {}, self.__correlation_id)) @allow_if_authenticated def delete(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 if self.__incident_update.delete_one_by_id(update_id): return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("Incident update deleted successfully.") }], {}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while deleting incident update.") }], {}, self.__correlation_id))
class Components(View): """Create and List Components Private Endpoint Controller""" def __init__(self): self.__request = Request() self.__response = Response() self.__helpers = Helpers() self.__form = Form() self.__component = ComponentModule() self.__component_group = ComponentGroupModule() self.__logger = self.__helpers.get_logger(__name__) self.__form.add_validator(ExtraRules()) self.__user_id = None 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.__request.set_request(request) request_data = self.__request.get_request_data("post", { "name": "", "description": "", "uptime": "", "group": "" }) self.__form.add_inputs({ 'name': { 'value': request_data["name"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [1, 60], 'error': _('Error! Component name must be 1 to 60 characters long.' ) } } }, 'description': { 'value': request_data["description"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [0, 150], 'error': _('Error! Component name description must be less than 150 characters long.' ) }, 'optional': {} } }, 'uptime': { 'value': request_data["uptime"], 'validate': { 'any_of': { 'param': [["on", "off"]], 'error': _('Error! Uptime is invalid.') } } }, 'group': { 'value': int(request_data["group"]), 'sanitize': { 'strip': {} }, 'validate': { 'greater_than': { 'error': _('Error! Component group is invalid.'), 'param': [0] }, 'optional': {} } } }) self.__form.process() if not self.__form.is_passed(): return JsonResponse( self.__response.send_errors_failure(self.__form.get_errors(), {}, self.__correlation_id)) # Check if component name not used if self.__component.get_one_by_name(self.__form.get_sinput("name")): return JsonResponse( self.__response.send_private_failure( [{ "type": "error", "message": _("Error! Component name is used before.") }], {}, self.__correlation_id)) # Check if group id is valid if self.__form.get_sinput( "group") and not self.__component_group.get_one_by_id( self.__form.get_sinput("group")): return JsonResponse( self.__response.send_private_failure( [{ "type": "error", "message": _("Error! Component group is invalid.") }], {}, self.__correlation_id)) result = self.__component.insert_one({ "name": self.__form.get_sinput("name"), "description": self.__form.get_sinput("description"), "uptime": self.__form.get_sinput("uptime"), "group_id": None if self.__form.get_sinput("group") == "" else self.__form.get_sinput("group") }) if result: return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("Component created successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while creating component.") }], {}, 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": 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( [], { 'components': self.__format_components( self.__component.get_all(offset, limit)), 'metadata': { 'offset': offset, 'limit': limit, 'count': self.__component.count_all() } }, self.__correlation_id)) def __format_components(self, components): components_list = [] for component in components: components_list.append({ "id": component.id, "name": component.name, "description": component.description, "uptime": component.uptime, "group": "---" if component.group is None else component.group.name, "created_at": component.created_at.strftime("%b %d %Y %H:%M:%S"), "edit_url": reverse("app.web.admin.component.edit", kwargs={'component_id': component.id}), "delete_url": reverse("app.api.private.v1.admin.component.endpoint", kwargs={'component_id': component.id}) }) return components_list
class Component(View): """Update and Delete Component Private Endpoint Controller""" def __init__(self): self.__request = Request() self.__response = Response() self.__helpers = Helpers() self.__form = Form() self.__component = ComponentModule() self.__component_group = ComponentGroupModule() self.__logger = self.__helpers.get_logger(__name__) self.__form.add_validator(ExtraRules()) self.__user_id = None self.__correlation_id = "" @allow_if_authenticated def post(self, request, component_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": "", "description": "", "uptime": "", "group": "" }) self.__form.add_inputs({ 'name': { 'value': request_data["name"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [1, 60], 'error': _('Error! Component name must be 1 to 60 characters long.' ) } } }, 'description': { 'value': request_data["description"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [0, 150], 'error': _('Error! Component name description must be less than 150 characters long.' ) }, 'optional': {} } }, 'uptime': { 'value': request_data["uptime"], 'validate': { 'any_of': { 'param': [["on", "off"]], 'error': _('Error! Uptime is invalid.') } } }, 'group': { 'value': int(request_data["group"]), 'sanitize': { 'strip': {} }, 'validate': { 'greater_than': { 'error': _('Error! Component group is invalid.'), 'param': [0] }, 'optional': {} } } }) self.__form.process() if not self.__form.is_passed(): return JsonResponse( self.__response.send_errors_failure(self.__form.get_errors(), {}, self.__correlation_id)) # Check if component name not used elsewhere current_component = self.__component.get_one_by_name( self.__form.get_sinput("name")) if current_component and not current_component["id"] == component_id: return JsonResponse( self.__response.send_private_failure( [{ "type": "error", "message": _("Error! Component name is used before.") }], {}, self.__correlation_id)) # Check if group id is valid if self.__form.get_sinput( "group") and not self.__component_group.get_one_by_id( self.__form.get_sinput("group")): return JsonResponse( self.__response.send_private_failure( [{ "type": "error", "message": _("Error! Component group is invalid.") }], {}, self.__correlation_id)) result = self.__component.update_one_by_id( component_id, { "name": self.__form.get_sinput("name"), "description": self.__form.get_sinput("description"), "uptime": self.__form.get_sinput("uptime"), "group_id": None if self.__form.get_sinput("group") == "" else self.__form.get_sinput("group") }) if result: return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("Component updated successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while updating component.") }], {}, self.__correlation_id)) @allow_if_authenticated def delete(self, request, component_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.__component.delete_one_by_id(component_id): return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("Component deleted successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while deleting component.") }], {}, self.__correlation_id))
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))
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))
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))
class ComponentGroup(View): __request = None __response = None __helpers = None __form = None __logger = None __user_id = None __component_group = None __correlation_id = None 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()) @allow_if_authenticated def post(self, request, group_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": "", "description": "", "uptime": "" }) self.__form.add_inputs({ 'name': { 'value': request_data["name"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [1, 90], 'error': _('Error! Component group name must be 1 to 90 characters long.') } } }, 'description': { 'value': request_data["description"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'uptime': { 'value': request_data["uptime"], 'validate': { 'any_of': { 'param': [["on", "off"]], 'error': _('Error! Uptime 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.__component_group.update_one_by_id(group_id, { "name": self.__form.get_sinput("name"), "description": self.__form.get_sinput("description"), "uptime": self.__form.get_sinput("uptime") }) if result: return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("Component group updated successfully.") }], {}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while updating group.") }], {}, self.__correlation_id)) @allow_if_authenticated def delete(self, request, group_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.__component_group.delete_one_by_id(group_id): return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("Component group deleted successfully.") }], {}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while deleting group.") }], {}, self.__correlation_id))
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))
class StatusSubscribe(View): """Subscribe Private Endpoint Controller""" 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.__correlation_id = "" self.__form.add_validator(ExtraRules()) 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", { "type": "", "email": "", "phone": "", "endpoint": "", "auth_token": "" }) if request_data["type"] == "email": self.__form.add_inputs({ 'email': { 'value': request_data["email"], 'sanitize': { 'strip': {} }, 'validate': { 'sv_email': { 'error': _('Error! Email is invalid.') } } } }) elif request_data["type"] == "phone": self.__form.add_inputs({ 'phone': { 'value': request_data["phone"], 'sanitize': { 'strip': {} }, 'validate': { 'sv_phone': { 'error': _('Error! Phone number is invalid.') } } } }) elif request_data["type"] == "endpoint": self.__form.add_inputs({ 'email': { 'value': request_data["email"], 'sanitize': { 'strip': {} }, 'validate': { 'sv_email': { 'error': _('Error! Email is invalid.') } } }, 'endpoint': { 'value': request_data["endpoint"], 'sanitize': { 'strip': {} }, 'validate': { 'sv_url': { 'error': _('Error! Endpoint URL is invalid.') } } }, 'auth_token': { 'value': request_data["auth_token"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [0, 80], 'error': _('Error! Token is very long.') }, 'optional': {} } } }) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Invalid request.") }], {}, self.__correlation_id)) self.__form.process() if not self.__form.is_passed(): return JsonResponse(self.__response.send_errors_failure(self.__form.get_errors(), {}, self.__correlation_id)) external_id = self.__helpers.generate_uuid() while self.__subscriber.get_one_by_external_id(external_id) is not False: external_id = self.__helpers.generate_uuid() if request_data["type"] == "email": result = self.__subscriber.insert_one({ "status": "pending", "type": "email", "email": self.__form.get_sinput("email"), "phone": "", "endpoint": "", "auth_token": "", "external_id": external_id }) elif request_data["type"] == "phone": result = self.__subscriber.insert_one({ "status": "pending", "type": "phone", "email": "", "phone": self.__form.get_sinput("phone"), "endpoint": "", "auth_token": "", "external_id": external_id }) else: result = self.__subscriber.insert_one({ "status": "pending", "type": "endpoint", "email": self.__form.get_sinput("email"), "phone": "", "endpoint": self.__form.get_sinput("endpoint"), "auth_token": self.__form.get_sinput("auth_token"), "external_id": external_id }) if result: return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("You have successfully subscribed.") }], {}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while subscribing.") }], {}, self.__correlation_id))
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
class Login(View): __request = None __response = None __helpers = None __form = None __login = None __logger = None __correlation_id = None def __init__(self): self.__request = Request() self.__response = Response() self.__helpers = Helpers() self.__form = Form() self.__login = LoginModule() 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 "" if self.__login.is_authenticated(request): return JsonResponse( self.__response.send_private_failure( [{ "type": "error", "message": _("Error! User is already authenticated.") }], {}, self.__correlation_id)) 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': { 'sv_username_or_email': { 'error': _("Error! Username or password is invalid.") } } }, 'password': { 'value': request_data["password"], 'validate': { 'sv_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_errors_failure(self.__form.get_errors(), {}, self.__correlation_id)) if self.__login.authenticate(self.__form.get_sinput("username"), self.__form.get_sinput("password"), request): return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("You logged in successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure( [{ "type": "error", "message": _("Error! Username or password is invalid.") }], {}, self.__correlation_id))
class Install(View): __request = None __response = None __helpers = None __form = None __install = None __logger = None __notification = None __correlation_id = None 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()) @stop_request_if_installed def post(self, request): self.__correlation_id = request.META[ "X-Correlation-ID"] if "X-Correlation-ID" in request.META else "" if self.__install.is_installed(): return JsonResponse( self.__response.send_private_failure( [{ "type": "error", "message": _("Error! Application is already installed.") }], {}, self.__correlation_id)) self.__request.set_request(request) request_data = self.__request.get_request_data( "post", { "app_name": "", "app_email": "", "app_url": "", "admin_username": "", "admin_email": "", "admin_password": "" }) 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': [2, 30], 'error': _('Error! Application name must be 2 to 30 characters long.' ) } } }, 'app_email': { 'value': request_data["app_email"], 'sanitize': { 'escape': {}, 'strip': {} }, 'validate': { 'sv_email': { 'error': _('Error! Application email is invalid.') } } }, 'app_url': { 'value': request_data["app_url"], 'sanitize': { 'escape': {}, 'strip': {} }, 'validate': { 'sv_url': { 'error': _('Error! Application url is invalid.') } } }, 'admin_username': { 'value': request_data["admin_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.') } } }, 'admin_email': { 'value': request_data["admin_email"], 'sanitize': { 'escape': {}, 'strip': {} }, 'validate': { 'sv_email': { 'error': _('Error! Admin email is invalid.') } } }, 'admin_password': { 'value': request_data["admin_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)) self.__install.set_app_data(self.__form.get_sinput("app_name"), self.__form.get_sinput("app_email"), self.__form.get_sinput("app_url")) self.__install.set_admin_data(self.__form.get_sinput("admin_username"), self.__form.get_sinput("admin_email"), self.__form.get_sinput("admin_password")) try: user_id = self.__install.install() except Exception as exception: self.__logger.error( _("Internal server error during installation: %(exception)s {'correlationId':'%(correlationId)s'}" ) % { "exception": exception, "correlationId": self.__correlation_id }) if user_id: self.__notification.create_notification({ "highlight": _('Installation'), "notification": _('Silverback installed successfully'), "url": "#", "type": NotificationModule.MESSAGE, "delivered": False, "user_id": user_id, "task_id": None }) return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("Application installed successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong during installing.") }], {}, self.__correlation_id))
class Subscribers(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): 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)) external_id = self.__helpers.generate_uuid() while self.__subscriber.get_one_by_external_id( external_id) is not False: external_id = self.__helpers.generate_uuid() if request_data["type"] == "email": result = self.__subscriber.insert_one({ "status": self.__form.get_sinput("status"), "type": self.__form.get_sinput("type"), "email": self.__form.get_sinput("email"), "phone": "", "endpoint": "", "auth_token": "", "external_id": external_id }) elif request_data["type"] == "phone": result = self.__subscriber.insert_one({ "status": self.__form.get_sinput("status"), "type": self.__form.get_sinput("type"), "email": "", "phone": self.__form.get_sinput("phone"), "endpoint": "", "auth_token": "", "external_id": external_id }) else: result = self.__subscriber.insert_one({ "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"), "external_id": external_id }) if result: return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("Subscriber created successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while creating subscriber.") }], {}, 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( [], { 'subscribers': self.__format_subscribers( self.__subscriber.get_all(offset, limit)), 'metadata': { 'offset': offset, 'limit': limit, 'count': self.__subscriber.count_all() } }, self.__correlation_id)) def __format_subscribers(self, subscribers): subscribers_list = [] for subscriber in subscribers: subscribers_list.append({ "id": subscriber.id, "status": subscriber.status.title(), "type": subscriber.type, "email": subscriber.email, "phone": subscriber.phone, "endpoint": subscriber.endpoint, "auth_token": subscriber.auth_token, "created_at": subscriber.created_at.strftime("%b %d %Y %H:%M:%S"), "edit_url": reverse("app.web.admin.subscriber.edit", kwargs={'subscriber_id': subscriber.id}), "delete_url": reverse("app.api.private.v1.admin.subscriber.endpoint", kwargs={'subscriber_id': subscriber.id}) }) return subscribers_list
class Metric(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 post(self, request, metric_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", { "title": "", "description": "", "source": "", "application": "", "metric": "", "x_axis": "", "y_axis": "" }) self.__form.add_inputs({ 'title': { 'value': request_data["title"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'description': { 'value': request_data["description"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'source': { 'value': request_data["source"], 'validate': { 'any_of': { 'param': [["newrelic"]], 'error': _('Error! Source is invalid.') } } }, 'application': { 'value': request_data["application"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'metric': { 'value': request_data["metric"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'x_axis': { 'value': request_data["x_axis"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'y_axis': { 'value': request_data["y_axis"], 'sanitize': { 'strip': {} }, 'validate': {} } }) 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.__metric.update_one_by_id( metric_id, { "title": self.__form.get_sinput("title"), "description": self.__form.get_sinput("description"), "source": self.__form.get_sinput("source"), "x_axis": self.__form.get_sinput("x_axis"), "y_axis": self.__form.get_sinput("y_axis"), "data": '{"application":"%s", "metric":"%s"}' % (self.__form.get_sinput("application"), self.__form.get_sinput("metric")) }) if result: return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("Metric updated successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while updating metric.") }], {}, self.__correlation_id)) @allow_if_authenticated def delete(self, request, metric_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.__metric.delete_one_by_id(metric_id): return JsonResponse( self.__response.send_private_success( [{ "type": "success", "message": _("Metric deleted successfully.") }], {}, self.__correlation_id)) else: return JsonResponse( self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while deleting metric.") }], {}, self.__correlation_id))
class ComponentGroups(View): __request = None __response = None __helpers = None __form = None __logger = None __user_id = None __component_group = None __correlation_id = None 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()) @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": "", "description": "", "uptime": "", }) self.__form.add_inputs({ 'name': { 'value': request_data["name"], 'sanitize': { 'strip': {} }, 'validate': { 'length_between': { 'param': [1, 90], 'error': _('Error! Component group name must be 1 to 90 characters long.') } } }, 'description': { 'value': request_data["description"], 'sanitize': { 'strip': {} }, 'validate': {} }, 'uptime': { 'value': request_data["uptime"], 'validate': { 'any_of': { 'param': [["on", "off"]], 'error': _('Error! Uptime 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.__component_group.insert_one({ "name": self.__form.get_sinput("name"), "description": self.__form.get_sinput("description"), "uptime": self.__form.get_sinput("uptime") }) if result: return JsonResponse(self.__response.send_private_success([{ "type": "success", "message": _("Component group created successfully.") }], {}, self.__correlation_id)) else: return JsonResponse(self.__response.send_private_failure([{ "type": "error", "message": _("Error! Something goes wrong while creating group.") }], {}, 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([], { 'groups': self.__format_groups(self.__component_group.get_all(offset, limit)), 'metadata': { 'offset': offset, 'limit': limit, 'count': self.__component_group.count_all() } }, self.__correlation_id)) def __format_groups(self, groups): groups_list = [] for group in groups: groups_list.append({ "id": group.id, "name": group.name, "description": group.description, "components": self.__component_group.count_components(group.id), "created_at": group.created_at.strftime("%b %d %Y %H:%M:%S"), "edit_url": reverse("app.web.admin.component_group.edit", kwargs={'group_id': group.id}), "delete_url": reverse("app.api.private.v1.admin.component_group.endpoint", kwargs={'group_id': group.id}) }) return groups_list