Ejemplo n.º 1
0
class NotifyService:
    """
    Service that wraps the Government of Canada Notifications API
    """

    def __init__(self, api_key=None, end_point=None):
        self.client = None
        if api_key is None or end_point is None:
            logging.info("Notifications disabled, no api key or end point specified.")
        else:
            self.client = NotificationsAPIClient(api_key, base_url=end_point)

    def send_email(self, address, template_id, details):
        """
        Send a new email using the GC notification client

        Args:
            address: The email address
            template_id: The id of the template to use
            details: Dictionary of personalization variables
        """
        if self.client:
            try:
                self.client.send_email_notification(
                    email_address=address,
                    template_id=template_id,
                    personalisation=details,
                )
            except HTTPError as e:
                raise Exception(e)
        else:
            logging.info(f"Notifications disabled. Otherwise would email: {address}.")

    def send_sms(self, phone_number, template_id, details):
        """
        Send a new SMS using the GC notification client

        Args:
            phone_number: The phone number to send to
            template_id: The id of the template to use
            details: Dictionary of personalization variables
        """
        if self.client:
            try:
                self.client.send_sms_notification(
                    phone_number=phone_number,
                    template_id=template_id,
                    personalisation=details,
                )
            except HTTPError as e:
                raise Exception(e)
        else:
            logging.info(
                f"Notifications disabled. Otherwise would text to: {phone_number}."
            )
Ejemplo n.º 2
0
def __send_sms_via_notify(data):
    """
    This method actually makes the post request to the Notify endpoint
    :param data: All of the necessary parameters for a successful SMS Notify request are passed in via the request
    :return: The a 201 and the notify id if the request to Notify is successful
    """
    global NOTIFICATIONS_CLIENT

    # Read serialized email info
    if 'service_name' in data:
        service_name = data['service_name']

        if service_name == 'Pay':
            NOTIFICATIONS_CLIENT = NotificationsAPIClient(
                settings.PAY_NOTIFY_API_KEY)
        elif service_name == 'Nannies':
            NOTIFICATIONS_CLIENT = NotificationsAPIClient(
                settings.NANNIES_NOTIFY_API_KEY)
        elif service_name == 'Change Personal Details':
            NOTIFICATIONS_CLIENT = NotificationsAPIClient(
                settings.CHANGE_PERSONAL_DETAILS_NOTIFY_API_KEY)
        elif service_name == 'New adults in the home':
            NOTIFICATIONS_CLIENT = NotificationsAPIClient(
                settings.NEW_ADULTS_IN_HOME_API_KEY)
        else:
            NOTIFICATIONS_CLIENT = NotificationsAPIClient(
                settings.NOTIFY_API_KEY)
    else:
        NOTIFICATIONS_CLIENT = NotificationsAPIClient(settings.NOTIFY_API_KEY)

    # Read serialized SMS Info
    phone_number = data['phone_number']
    template_id = data['template_id']

    if 'reference' in data:
        reference = data['reference']
    else:
        reference = None

    if 'personalisation' in data:
        personalisation = data['personalisation']
    else:
        personalisation = None

    # Make request to Gov UK Notify API
    response = NOTIFICATIONS_CLIENT.send_sms_notification(
        phone_number=phone_number,
        template_id=template_id,
        personalisation=personalisation,
        reference=reference,
        sms_sender_id=None)

    return JsonResponse(
        {
            "notifyId": response['id'],
            "message": "SMS sent successfully"
        },
        status=201)
Ejemplo n.º 3
0
    def _deliver_token(self, token):
        self._validate_config()
        notifications_client = NotificationsAPIClient(
            settings.OTP_NOTIFY_API_KEY, base_url=settings.OTP_NOTIFY_ENDPOINT)

        try:
            response = notifications_client.send_sms_notification(
                phone_number=self.number,
                template_id=settings.OTP_NOTIFY_TEMPLATE_ID,
                sms_sender_id=settings.OTP_NOTIFY_SENDER_ID,
                personalisation={'token': token},
            )
        except HTTPError as e:
            logger.exception(e.message)
            raise Exception(e.message[0].get("message"))

        return response
Ejemplo n.º 4
0
class GovNotify(Sender):
    def __init__(self, config) -> None:
        super().__init__(config)
        self.template_id: str = ''
        self.template_vars: Optional[Dict] = None
        self.client = NotificationsAPIClient(
            api_key=self.get_api_key() or self.get_config_value(
                env_var='GOV_NOTIFY_KEY', section='GovNotify', key='api_key'))

    @xray_recorder.capture('Get GovNotify Key')
    def get_api_key(self) -> Optional[str]:
        try:
            role = self.get_config_value('SECRET_ROLE', 'AWS', 'secret_role')
            region = self.get_config_value('AWS_REGION', 'AWS', 'region')
            secret_name = self.get_config_value('GOV_NOTIFY_SECRET',
                                                'GovNotify', 'secret_name')

            sts: SClient = boto3.client('sts')
            cred = sts.assume_role(
                RoleArn=role,
                RoleSessionName='GovNotifyKey').get('Credentials')
            sess = boto3.Session(aws_access_key_id=cred['AccessKeyId'],
                                 aws_secret_access_key=cred['SecretAccessKey'],
                                 aws_session_token=cred['SessionToken'],
                                 region_name=region)
            sm: Client = sess.client('secretsmanager')
            sv = sm.get_secret_value(SecretId=secret_name)
            return json.loads(sv.get('SecretString')).get('api_key')
        except (KeyError, ClientError, NoSectionError) as e:
            self.logger.warning(
                'Failed to retrieve secret key from SecretsManager',
                exc_info=e)
            return

    @xray_recorder.capture('Set GovNotify Message')
    def set_message(self, event: Dict):
        super().set_message(event)
        self.template_id = event.get('template_id')
        self.template_vars = event.get('template_vars')
        if self.attachment:
            # Gov notify only supports attaching PDFs that are less than 2MB
            if self.attachment_name.endswith('.pdf') and len(
                    base64.b64decode(self.attachment, validate=True)) < 2e+6:
                self.template_vars['link_to_document'] = {
                    'file': self.attachment
                }
            else:
                self.template_vars['s3_link'] = self.upload_attachment()

    @xray_recorder.capture('Send GovNotify Message')
    def send(self):
        super().send()
        resp = None
        if self.message_type == 'email':
            resp = self.client.send_email_notification(
                template_id=self.template_id,
                personalisation=self.template_vars,
                email_address=self.to,
                email_reply_to_id=self.get_config_value('GOV_NOTIFY_REPLY_TO',
                                                        section='GovNotify',
                                                        key='reply_to_id'))
        elif self.message_type == 'sms':
            resp = self.client.send_sms_notification(
                template_id=self.template_id,
                personalisation=self.template_vars,
                phone_number=self.to)
        elif self.message_type == 'letter':
            raise NotImplementedError
        return resp