Пример #1
0
def incident_update(incident_update_id, user_id):

    incident_update_notification_module = IncidentUpdateNotificationModule()
    subscriber_module = SubscriberModule()
    task_module = TaskModule()

    for subscriber in subscriber_module.get_iterator():
        notification = incident_update_notification_module.is_subscriber_notified(
            incident_update_id, subscriber.id)
        if notification:
            # Send notification.id to the queue again
            task_module.delay("notify_subscriber",
                              {"notification_id": notification.id}, user_id)

        else:
            # Create new notification and send to queue
            new_notification = incident_update_notification_module.insert_one({
                "status":
                "pending",
                "incident_update_id":
                incident_update_id,
                "subscriber_id":
                subscriber.id
            })
            if new_notification:
                # Send new_notification.id to the Queue
                task_module.delay("notify_subscriber",
                                  {"notification_id": new_notification.id},
                                  user_id)

    return {"status": "passed", "result": "{}", "notify_type": "passed"}
Пример #2
0
class SubscriberEdit(View):
    """Subscriber Edit Page Controller"""

    template_name = 'templates/admin/subscriber/edit.html'

    @login_if_not_authenticated
    def get(self, request, subscriber_id):

        self.__context = Context()
        self.__subscriber = SubscriberModule()
        self.__correlation_id = request.META[
            "X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        subscriber = self.__subscriber.get_one_by_id(subscriber_id)

        if not subscriber:
            raise Http404("Subscriber not found.")

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

        return render(request, self.template_name, self.__context.get())
Пример #3
0
 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())
Пример #4
0
 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())
Пример #5
0
def incident_update(incident_update_id, user_id, correlation_id=""):
    logger = Helpers().get_logger(__name__)

    logger.info(
        _("Worker started processing incident_update task with parameters %(parameters)s {'correlationId':'%(correlationId)s'}"
          ) % {
              "parameters": json.dumps({}),
              "correlationId": correlation_id
          })

    incident_update_notification_module = IncidentUpdateNotificationModule()
    subscriber_module = SubscriberModule()
    task_module = TaskModule()

    for subscriber in subscriber_module.get_iterator():
        notification = incident_update_notification_module.is_subscriber_notified(
            incident_update_id, subscriber.id)
        if notification:
            # Send notification.id to the queue again
            task_module.delay("notify_subscriber",
                              {"notification_id": notification.id}, user_id)

        else:
            # Create new notification and send to queue
            new_notification = incident_update_notification_module.insert_one({
                "status":
                "pending",
                "incident_update_id":
                incident_update_id,
                "subscriber_id":
                subscriber.id
            })
            if new_notification:
                # Send new_notification.id to the Queue
                task_module.delay("notify_subscriber",
                                  {"notification_id": new_notification.id},
                                  user_id)

    return {"status": "passed", "result": "{}", "notify_type": "passed"}
def verify_subscriber(subscriber_id, correlation_id=""):
    logger = Helpers().get_logger(__name__)

    logger.info(
        _("Worker started processing verify_subscriber task with parameters %(parameters)s {'correlationId':'%(correlationId)s'}"
          ) % {
              "parameters": json.dumps({}),
              "correlationId": correlation_id
          })

    subscriber_module = SubscriberModule()
    subscriber = subscriber_module.get_one_by_id(subscriber_id)

    if not subscriber:
        return {"status": "passed", "result": "{}"}

    if subscriber.type == SubscriberModule.EMAIL:
        result = __verify_email()
    elif subscriber.type == SubscriberModule.PHONE:
        result = __verify_phone()
    elif subscriber.type == SubscriberModule.ENDPOINT:
        result = __verify_endpoint()

    return result
Пример #7
0
    def get(self, request, subscriber_id):

        self.__subscriber = SubscriberModule()
        subscriber = self.__subscriber.get_one_by_id(subscriber_id)

        if not subscriber:
            raise Http404("Subscriber not found.")

        self.autoload_options()
        self.autoload_user(
            request.user.id if request.user.is_authenticated else None)
        self.context_push({
            "page_title":
            _("Edit Subscriber · %s") %
            self.context_get("app_name", os.getenv("APP_NAME", "Silverback")),
            "subscriber":
            subscriber
        })

        return render(request, self.template_name, self.context_get())
Пример #8
0
 def __init__(self):
     self.__subscriber = SubscriberModule()
Пример #9
0
class StatusSubscribe(View, Controller):
    """Subscribe Private Endpoint Controller"""
    def __init__(self):
        self.__subscriber = SubscriberModule()

    def post(self, request):

        request_data = self.get_request_data(request, "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 self.json([{
                "type": "error",
                "message": _("Error! Invalid request.")
            }])

        self.form().process()

        if not self.form().is_passed():
            return self.json(self.form().get_errors())

        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 self.json([{
                "type": "success",
                "message": _("You have successfully subscribed.")
            }])
        else:
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Something goes wrong while subscribing.")
            }])
Пример #10
0
class Subscriber(View):

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

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

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

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

        request_data = self.__request.get_request_data(
            "post", {
                "type": "",
                "email": "",
                "phone": "",
                "endpoint": "",
                "auth_token": "",
                "status": ""
            })

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

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

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

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

        else:

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

        self.__form.process()

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

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

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

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

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

        else:

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

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

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

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

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

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while deleting subscriber.")
                }], {}, self.__correlation_id))
Пример #11
0
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
Пример #12
0
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
Пример #13
0
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))
Пример #14
0
class Subscriber(View, Controller):
    """Update and Delete Subscriber Private Endpoint Controller"""
    def __init__(self):
        self.__subscriber = SubscriberModule()

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

        request_data = self.get_request_data(
            request, "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': {
                        'sv_email': {
                            'error': _('Error! Email is invalid.')
                        }
                    }
                },
                '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': {
                        'sv_phone': {
                            'error': _('Error! Phone number is invalid.')
                        }
                    }
                },
                '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': {
                        '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': {}
                    }
                },
                '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 self.json(self.form().get_errors())

        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 self.json([{
                "type": "success",
                "message": _("Subscriber updated successfully.")
            }])
        else:
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Something goes wrong while updating subscriber.")
            }])

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

        if self.__subscriber.delete_one_by_id(subscriber_id):
            return self.json([{
                "type": "success",
                "message": _("Subscriber deleted successfully.")
            }])

        else:
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Something goes wrong while deleting subscriber.")
            }])
Пример #15
0
class Subscribers(View, Controller):
    """Create and List Subscribers Private Endpoint Controller"""
    def __init__(self):
        self.__subscriber = SubscriberModule()

    @allow_if_authenticated
    def post(self, request):

        request_data = self.get_request_data(
            request, "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': {
                        'sv_email': {
                            'error': _('Error! Email is invalid.')
                        }
                    }
                },
                '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': {
                        'sv_phone': {
                            'error': _('Error! Phone number is invalid.')
                        }
                    }
                },
                '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': {
                        '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': {}
                    }
                },
                '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 self.json(self.form().get_errors())

        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 self.json([{
                "type": "success",
                "message": _("Subscriber created successfully.")
            }])
        else:
            return self.json([{
                "type":
                "error",
                "message":
                _("Error! Something goes wrong while creating subscriber.")
            }])

    @allow_if_authenticated
    def get(self, request):

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

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

        return self.json(
            [], {
                'subscribers':
                self.__format_subscribers(
                    self.__subscriber.get_all(offset, limit)),
                'metadata': {
                    'offset': offset,
                    'limit': limit,
                    'count': self.__subscriber.count_all()
                }
            })

    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