示例#1
0
文件: api.py 项目: pkkup/django-htk
    def create_sso_endpoint(self, sso_key):
        resource_path = DSS_321FORMS_API_RESOURCE_SSO_ENDPOINT % {
            'sso_key' : sso_key,
        }
        request_url = self.get_request_url(resource_path=resource_path)
        response = self.request_post(request_url)
        exception_reported = False

        try:
            data = response.json()
            endpoint = data.get('endpoint')
        except:
            endpoint = None
            request = get_current_request()
            extra_data = self._get_rollbar_extra_data()
            extra_data.update({
                'response_text' : response.text,
            })
            rollbar.report_exc_info(extra_data=extra_data)
            exception_reported = True

        if endpoint is None and not exception_reported:
            request = get_current_request()
            extra_data = self._get_rollbar_extra_data()
            extra_data.update({
                'response_text' : response.text,
            })
            rollbar.report_message('Error retrieving SSO endpoint', request=request, extra_data=extra_data)
        return endpoint
示例#2
0
    def create_sso_endpoint(self, sso_key):
        resource_path = DSS_321FORMS_API_RESOURCE_SSO_ENDPOINT % {
            'sso_key': sso_key,
        }
        request_url = self.get_request_url(resource_path=resource_path)
        response = self.request_post(request_url)
        exception_reported = False

        try:
            data = response.json()
            endpoint = data.get('endpoint')
        except:
            endpoint = None
            request = get_current_request()
            extra_data = self._get_rollbar_extra_data()
            extra_data.update({
                'response_text': response.text,
            })
            rollbar.report_exc_info(extra_data=extra_data)
            exception_reported = True

        if endpoint is None and not exception_reported:
            request = get_current_request()
            extra_data = self._get_rollbar_extra_data()
            extra_data.update({
                'response_text': response.text,
            })
            rollbar.report_message('Error retrieving SSO endpoint',
                                   request=request,
                                   extra_data=extra_data)
        return endpoint
示例#3
0
def get_user_by_email(email):
    """Gets a User by `email`
    Returns None if not found
    """
    from htk.apps.accounts.models import UserEmail
    if is_valid_email(email):
        # check for confirmed email addresses
        user_emails = UserEmail.objects.filter(email__iexact=email, is_confirmed=True)
        num_results = user_emails.count()
        if num_results == 1:
            user = user_emails[0].user
        elif num_results > 1:
            # there should only be one User with this email...
            # if there are more, we have a data error!
            raise NonUniqueEmail(email)
        else:
            # num_results == 0, so check UserModel for active users with email
            UserModel = get_user_model()
            try:
                user = UserModel.objects.get(email__iexact=email, is_active=True)
            except UserModel.MultipleObjectsReturned:
                user = None
                request = get_current_request()
                rollbar.report_exc_info()
                raise NonUniqueEmail(email)
            except UserModel.DoesNotExist:
                # also check newly registered accounts
                # if not user.is_active, handling will get passed downstream
                user = get_incomplete_signup_user_by_email(email)
    else:
        user = None
    return user
示例#4
0
    def generate_sso_key(self):
        request_url = self.get_request_url(
            resource_path=DSS_321FORMS_API_RESOURCE_SSO_GENERATE)
        response = self.request_get(request_url)
        exception_reported = False

        try:
            data = response.json()
            sso_key = data.get('SSOKey')
        except:
            sso_key = None
            extra_data = self._get_rollbar_extra_data()
            extra_data.update({
                'response_text': response.text,
            })
            rollbar.report_exc_info(extra_data=extra_data)
            exception_reported = True

        if sso_key is None and not exception_reported:
            request = get_current_request()
            extra_data = self._get_rollbar_extra_data()
            extra_data.update({
                'response_text': response.text,
            })
            rollbar.report_message('Error generating 321Forms SSO key',
                                   request=request,
                                   extra_data=extra_data)
        return sso_key
示例#5
0
def get_user_by_email(email):
    """Gets a User by `email`
    Returns None if not found
    """
    from htk.apps.accounts.models import UserEmail

    if is_valid_email(email):
        # check for confirmed email addresses
        user_emails = UserEmail.objects.filter(email__iexact=email, is_confirmed=True)
        num_results = user_emails.count()
        if num_results == 1:
            user = user_emails[0].user
        elif num_results > 1:
            # there should only be one User with this email...
            # if there are more, we have a data error!
            raise NonUniqueEmail(email)
        else:
            # num_results == 0, so check UserModel for active users with email
            UserModel = get_user_model()
            try:
                user = UserModel.objects.get(email__iexact=email, is_active=True)
            except UserModel.MultipleObjectsReturned:
                user = None
                request = get_current_request()
                rollbar.report_exc_info()
                raise NonUniqueEmail(email)
            except UserModel.DoesNotExist:
                # also check newly registered accounts
                # if not user.is_active, handling will get passed downstream
                user = get_incomplete_signup_user_by_email(email)
    else:
        user = None
    return user
示例#6
0
    def send_activation_email(self, domain=None, resend=False, template=None, subject=None, sender=None):
        """Sends an activation email
        """
        domain = domain or htk_setting('HTK_DEFAULT_EMAIL_SENDING_DOMAIN')
        self._reset_activation_key(resend=resend)

        try:
            should_send_activation_email = True

            if htk_setting('HTK_ITERABLE_ENABLED'):
                from htk.lib.iterable.utils import get_iterable_api_client
                from htk.lib.iterable.utils import get_campaign_id

                itbl_campaign_id = get_campaign_id('triggered.account.sign_up_confirm_email')

                if itbl_campaign_id:
                    should_send_activation_email = False

                    data = {
                        'activation_uri' : self.get_activation_uri(domain=domain),
                    }

                    itbl = get_iterable_api_client()
                    itbl.send_triggered_email(self.email, itbl_campaign_id, data=data)

            if should_send_activation_email:
                activation_email(self, domain=domain, template=template, subject=subject, sender=sender)
        except:
            request = get_current_request()
            rollbar.report_exc_info(request=request)
示例#7
0
def email_context_generator():
    """Default HTK email context generator
    Returns a dictionary with values for inflating templated emails
    """
    request = get_current_request()
    protocol = 'http'
    if request:
        if request.is_secure():
            protocol = 'https'
        else:
            pass
        domain = request.get_host() or htk_setting('HTK_DEFAULT_DOMAIN')
    else:
        domain = htk_setting('HTK_DEFAULT_DOMAIN')

    base_url = '%(protocol)s://%(domain)s' % {
        'protocol' : protocol,
        'domain' : domain,
    }

    context = {
        'base_url': base_url,
        'site_name': htk_setting('HTK_SITE_NAME'),
        'support_email': htk_setting('HTK_SUPPORT_EMAIL'),
    }
    return context
示例#8
0
    def send_activation_email(self, domain=None, resend=False, template=None, subject=None, sender=None):
        """Sends an activation email
        """
        domain = domain or htk_setting('HTK_DEFAULT_EMAIL_SENDING_DOMAIN')
        self._reset_activation_key(resend=resend)

        try:
            should_send_activation_email = True

            if htk_setting('HTK_ITERABLE_ENABLED'):
                from htk.lib.iterable.utils import get_iterable_api_client
                from htk.lib.iterable.utils import get_campaign_id

                if resend:
                    campaign_key = 'triggered.transactional.account.confirm_email_resend'
                else:
                    campaign_key = 'triggered.transactional.account.sign_up_confirm_email'
                itbl_campaign_id = get_campaign_id(campaign_key)

                if itbl_campaign_id:
                    should_send_activation_email = False

                    data = {
                        'activation_uri' : self.get_activation_uri(domain=domain),
                    }

                    itbl = get_iterable_api_client()
                    itbl.send_triggered_email(self.email, itbl_campaign_id, data=data)

            if should_send_activation_email:
                activation_email(self, domain=domain, template=template, subject=subject, sender=sender)
        except:
            request = get_current_request()
            rollbar.report_exc_info(request=request)
示例#9
0
def get_current_site(request=None):
    """Returns the current site if a Request object is available

    Improves upon django.contrib.sites.shortcuts.get_current_site by also allowing subdomains
    """
    if request is None:
        request = get_current_request()

    site = None

    if request:
        from django.contrib.sites.models import Site

        hostname = request.get_host()

        for _site in Site.objects.all():
            # TODO: expensive, cache
            domain = _site.domain
            domain_regex = r'^(?:.*\.)?%s$' % domain.replace('.', '\.')
            if re.match(domain_regex, hostname):
                site = _site
                break
    else:
        pass

    return site
示例#10
0
    def handle_bad_response(self, response=None, error_msg=None):
        request = get_current_request()
        if response is not None:
            api_request = response.request

            extra_data = {
                'api_request': {
                    'url': api_request.url,
                    'method': api_request.method,
                    'body': api_request.body,
                },
                'response': {
                    'status_code': response.status_code,
                    'text': response.text,
                },
            }
        else:
            extra_data = {}

        if error_msg:
            extra_data.update({
                'message': '{}'.format(error_msg),
            })
        else:
            pass

        rollbar.report_message(
            'ZipRecruiter Job API Bad Response',
            request=request,
            extra_data=extra_data
        )
示例#11
0
文件: api.py 项目: pkkup/django-htk
    def generate_sso_key(self):
        request_url = self.get_request_url(resource_path=DSS_321FORMS_API_RESOURCE_SSO_GENERATE)
        response = self.request_get(request_url)
        exception_reported = False

        try:
            data = response.json()
            sso_key = data.get('SSOKey')
        except:
            sso_key = None
            extra_data = self._get_rollbar_extra_data()
            extra_data.update({
                'response_text' : response.text,
            })
            rollbar.report_exc_info(extra_data=extra_data)
            exception_reported = True

        if sso_key is None and not exception_reported:
            request = get_current_request()
            extra_data = self._get_rollbar_extra_data()
            extra_data.update({
                'response_text' : response.text,
            })
            rollbar.report_message('Error generating 321Forms SSO key', request=request, extra_data=extra_data)
        return sso_key
示例#12
0
def associate_user_email(user, email, domain=None, confirmed=False):
    """Associates `email` with `user`

    Resulting UserEmail.is_confirmed = `confirmed`, default False

    Side effect: sends an activation email if `confirmed` == False

    Requires:
    `user` and `email` to be valid
    `email` cannot be confirmed by any other user
    `email` cannot already be associated with THIS `user`
    """
    from htk.apps.accounts.models import UserEmail

    user_email = None
    if user and email:
        existing_user = get_user_by_email(email)
        should_associate = False
        if existing_user is None:
            # email address must not be associated to another account
            should_associate = True
        elif user == existing_user:
            if user.is_active:
                # an existing active account
                should_associate = True
            else:
                # a new registration
                should_associate = True
        else:
            # skip association
            # This email address is either:
            # a) already confirmed on another account
            # b) not already confirmed, and not a new registration
            should_associate = False

        if should_associate:
            user_email = get_user_email(user, email)
            if user_email is None:
                user_email = UserEmail.objects.create(user=user, email=email, is_confirmed=confirmed)
            if confirmed or user_email.is_confirmed:
                # don't need to send activation email for a pre-confirmed address
                # pre-confirmed email can come from a social auth provider
                user_email.confirm_and_activate_account()
            elif not user_email.is_confirmed:
                domain = domain or htk_setting("HTK_DEFAULT_EMAIL_SENDING_DOMAIN")
                try:
                    user_email.send_activation_email(domain)
                except:
                    request = get_current_request()
                    rollbar.report_exc_info()
            else:
                pass
        else:
            pass
    else:
        # invalid user or email
        pass

    return user_email
示例#13
0
 def send_welcome_email(self, template=None, subject=None, sender=None):
     """Sends a welcome email to the user
     """
     try:
         welcome_email(self.user, template=template, subject=subject, sender=sender)
     except:
         request = get_current_request()
         rollbar.report_exc_info(request=request)
示例#14
0
 def send_welcome_email(self, template=None, subject=None, sender=None):
     """Sends a welcome email to the user
     """
     try:
         welcome_email(self.user, template=template, subject=subject, sender=sender)
     except:
         request = get_current_request()
         rollbar.report_exc_info(request=request)
示例#15
0
 def send_welcome_email(self):
     """Sends a welcome email to the user
     """
     try:
         welcome_email(self.user)
     except:
         request = get_current_request()
         rollbar.report_exc_info(request=request)
示例#16
0
def get_authenticated_user():
    """Returns the currently authenticated user, or None
    """
    request = get_current_request()
    if request and hasattr(request, 'user') and request.user.is_authenticated:
        user = request.user
    else:
        user = None
    return user
示例#17
0
    def send_notifications(self):
        if htk_setting('HTK_SLACK_NOTIFICATIONS_ENABLED'):
            from htk.utils.notifications import slack_notify
            try:
                message = '{} <{}> just signed up for the pre-launch waiting list.'.format(
                    self.full_name, self.email)
                slack_notify(message)
            except:
                request = get_current_request()
                rollbar.report_exc_info(request=request)
        else:
            pass

        try:
            prelaunch_email(self)
        except Exception:
            request = get_current_request()
            rollbar.report_exc_info(request=request)
示例#18
0
 def save(self, commit=True):
     user = super(UpdatePasswordForm, self).save(commit=commit)
     from htk.apps.accounts.emails import password_changed_email
     try:
         password_changed_email(user)
     except:
         request = get_current_request()
         rollbar.report_exc_info(request=request)
     return user
示例#19
0
def slack_notify(message):
    """Send a Slack notification message
    """
    from htk.lib.slack.utils import webhook_call as slack_webhook_call
    try:
        channel = htk_setting('HTK_SLACK_NOTIFICATIONS_CHANNEL')
        slack_webhook_call(text=message, channel=channel)
    except:
        request = get_current_request()
        rollbar.report_exc_info(request=request)
示例#20
0
def _report_message(message, level='error', extra_data=None):
    """Wrapper for rollbar.report_message
    """
    try:
        import rollbar
        from htk.utils.request import get_current_request
        request = get_current_request()
        rollbar.report_message(message, level=level, request=request, extra_data=extra_data)
    except:
        pass
示例#21
0
def _report_message(message, level='error', extra_data=None):
    """Wrapper for rollbar.report_message
    """
    try:
        import rollbar
        from htk.utils.request import get_current_request
        request = get_current_request()
        rollbar.report_message(message, level=level, request=request, extra_data=extra_data)
    except:
        pass
示例#22
0
def _report_exc_info(extra_data=None):
    """Wrapper for rollbar.report_exc_info
    """
    try:
        import rollbar
        from htk.utils.request import get_current_request
        request = get_current_request()
        rollbar.report_exc_info(request=request, extra_data=extra_data)
    except:
        pass
示例#23
0
def _report_exc_info(extra_data=None):
    """Wrapper for rollbar.report_exc_info
    """
    try:
        import rollbar
        from htk.utils.request import get_current_request
        request = get_current_request()
        rollbar.report_exc_info(request=request, extra_data=extra_data)
    except:
        pass
示例#24
0
 def get_short_uri(self, domain=None):
     if domain is None:
         request = get_current_request()
         domain = request.get_host() if request else htk_setting('HTK_CANONICAL_DOMAIN')
     else:
         pass
     uri = 'http://%s%s' % (
         domain,
         reverse('shorturl', args=(self.get_code(),)),
     )
     return uri
示例#25
0
 def get_s3_url(self):
     try:
         s3 = S3Manager()
         s3_bucket = self.get_s3_bucket()
         s3_key = self.get_s3_key()
         s3_url = s3.get_url(s3_bucket, s3_key, cache=True)
     except:
         request = get_current_request()
         rollbar.report_exc_info(request=request)
         s3_url = ''
     return s3_url
示例#26
0
 def get_s3_url(self):
     try:
         s3 = S3Manager()
         s3_bucket = self.get_s3_bucket()
         s3_key = self.get_s3_key()
         s3_url = s3.get_url(s3_bucket, s3_key, cache=True)
     except:
         request = get_current_request()
         rollbar.report_exc_info(request=request)
         s3_url = ''
     return s3_url
示例#27
0
 def get_short_uri(self, domain=None):
     if domain is None:
         request = get_current_request()
         domain = request.get_host() if request else htk_setting(
             'HTK_CANONICAL_DOMAIN')
     else:
         pass
     uri = 'http://%s%s' % (
         domain,
         reverse('shorturl', args=(self.get_code(), )),
     )
     return uri
示例#28
0
 def save(self, user, *args, **kwargs):
     user = super(ChangePasswordForm, self).save(*args, **kwargs)
     try:
         password_changed_email(user)
     except:
         from htk.utils.request import get_current_request
         request = get_current_request()
         extra_data = {
             'user' : user,
             'email' : user.profile.confirmed_email or email,
         }
         rollbar.report_exc_info(request=request, extra_data=extra_data)
     return user
示例#29
0
 def has_follower(self, user=None):
     """Check if the currently logged-in user is following self.user
     """
     if user is None:
         request = get_current_request()
         user = request.user
     else:
         pass
     if user:
         value = user.profile.get_following().filter(id=self.user.id).exists()
     else:
         value = False
     return value
示例#30
0
    def cancel_subscription(self, subscription_id):
        """Cancels a Subscription for this Customer

        https://stripe.com/docs/api#cancel_subscription
        """
        subscription = self.retrieve_subscription(subscription_id)
        if subscription:
            try:
                subscription.delete()
            except stripe.error.InvalidRequestError, e:
                request = get_current_request()
                rollbar.report_exc_info(request=request)
            was_deleted = True
示例#31
0
def should_use_https():
    """Determines whether the current context should use HTTPS
    """
    use_https = settings.SECURE_SSL_HOST or settings.SECURE_SSL_REDIRECT or False

    if not use_https:
        # try to get from request
        from htk.utils.request import get_current_request
        request = get_current_request()

        use_https = request and request.is_secure()

    return use_https
示例#32
0
    def cancel_subscription(self, subscription_id):
        """Cancels a Subscription for this Customer

        https://stripe.com/docs/api#cancel_subscription
        """
        subscription = self.retrieve_subscription(subscription_id)
        if subscription:
            try:
                subscription.delete()
            except stripe.error.InvalidRequestError, e:
                request = get_current_request()
                rollbar.report_exc_info(request=request)
            was_deleted = True
示例#33
0
 def has_follower(self, user=None):
     """Check if the currently logged-in user is following self.user
     """
     if user is None:
         request = get_current_request()
         user = request.user
     else:
         pass
     if user:
         value = user.profile.get_following().filter(id=self.user.id).exists()
     else:
         value = False
     return value
示例#34
0
def is_allowed_to_emulate_users(user):
    """Determines whether `user` is allowed to emulate other users
    """
    allowed = False
    if user is not None and user.is_authenticated():
        try:
            user_profile = user.profile
            if user_profile.is_company_officer:
                allowed = True
        except:
            request = get_current_request()
            rollbar.report_exc_info(request=request)
    return allowed
示例#35
0
def get_oembed_html_for_service(url, service):
    """Returns the oEmbed HTML for `service` (YouTube, Vimeo, etc)

    Makes an HTTP request, so we should probably cache its response
    """
    c = OembedResponseCache(prekey=url)
    html = c.get()
    if html is None:
        request = None
        success = False
        try:
            oembed_base_url = OEMBED_BASE_URLS[service]
            oembed_url = oembed_base_url % urllib.quote(url)
            response = requests.get(oembed_url)
            if response.status_code >= 400:
                pass
            else:
                data = response.json()
                html = data['html']
                c.cache_store(html)
                success = True
        except:
            request = get_current_request()
            rollbar.report_exc_info(request=request)

        if success:
            pass
        else:
            html = 'Failed to get oEmbed for URL: %s' % url
            if request is None:
                request = get_current_request()
            else:
                pass
            rollbar.report_message('Bad oembed url <%s>' % (url), 'warning',
                                   request)
    else:
        pass
    return html
示例#36
0
def slack_notify(message, level=None):
    """Send a Slack notification message

    `level` is one of ['critical', 'severe', 'danger', 'warning', 'info']
    """
    from htk.lib.slack.utils import webhook_call as slack_webhook_call
    try:
        channels = htk_setting('HTK_SLACK_NOTIFICATION_CHANNELS')
        level = level if level in channels else 'info'
        channel = channels.get(level, htk_setting('HTK_SLACK_DEBUG_CHANNEL'))
        slack_webhook_call(text=message, channel=channel)
    except:
        request = get_current_request()
        rollbar.report_exc_info(request=request)
示例#37
0
def get_oembed_html_for_service(url, service):
    """Returns the oEmbed HTML for `service` (YouTube, Vimeo, etc)

    Makes an HTTP request, so we should probably cache its response
    """
    c = OembedResponseCache(prekey=url)
    html = c.get()
    if html is None:
        request = None
        success = False
        try:
            oembed_base_url = OEMBED_BASE_URLS[service]
            oembed_url = oembed_base_url % urllib.quote(url)
            response = requests.get(oembed_url)
            if response.status_code >= 400:
                pass
            else:
                data = response.json()
                html = data['html']
                c.cache_store(html)
                success = True
        except:
            request = get_current_request()
            rollbar.report_exc_info(request=request)

        if success:
            pass
        else:
            html = 'Failed to get oEmbed for URL: %s' % url
            if request is None:
                request = get_current_request()
            else:
                pass
            rollbar.report_message('Bad oembed url <%s>' % (url), 'warning', request)
    else:
        pass
    return html
示例#38
0
def slack_notify(message, level=None):
    """Send a Slack notification message

    `level` is one of ['critical', 'severe', 'danger', 'warning', 'info', 'debug',]
    """
    from htk.lib.slack.utils import webhook_call as slack_webhook_call
    try:
        channels = htk_setting('HTK_SLACK_NOTIFICATION_CHANNELS')
        default_level = 'debug' if (settings.ENV_DEV or settings.TEST) else 'info'
        level = level if level in channels else default_level
        channel = channels.get(level, htk_setting('HTK_SLACK_DEBUG_CHANNEL'))
        slack_webhook_call(text=message, channel=channel)
    except:
        request = get_current_request()
        rollbar.report_exc_info(request=request)
示例#39
0
def get_oembed_html_for_service(url, service):
    """Returns the oEmbed HTML for `service` (YouTube, Vimeo, etc)

    Makes an HTTP request, so we should probably cache its response
    """
    c = OembedResponseCache(prekey=url)
    html = c.get()
    if html is None:
        request = None
        success = False
        try:
            oembed_base_url = OEMBED_BASE_URLS[service]
            oembed_url = oembed_base_url % {
                'url': urllib.quote(url),
            }
            response = requests.get(oembed_url)
            if response.status_code >= 400:
                pass
            else:
                data = response.json()
                html = data['html']
                c.cache_store(html)
                success = True
        except:
            request = get_current_request()
            extra_data = {
                'message': 'Bad oembed URL',
                'oembed_url': oembed_url,
                'url': url,
                'response': {
                    'status_code': response.status_code,
                    'content': response.content,
                }
            }
            rollbar.report_exc_info(level='warning',
                                    request=request,
                                    extra_data=extra_data)

        if success:
            pass
        else:
            html = '<a href="%(url)s" target="_blank">%(url)s</a>' % {
                'url': url,
            }
    else:
        pass
    return html
示例#40
0
文件: utils.py 项目: pkkup/django-htk
def get_oembed_html_for_service(url, service):
    """Returns the oEmbed HTML for `service` (YouTube, Vimeo, etc)

    Makes an HTTP request, so we should probably cache its response
    """
    c = OembedResponseCache(prekey=url)
    html = c.get()
    if html is None:
        request = None
        success = False
        try:
            oembed_base_url = OEMBED_BASE_URLS[service]
            oembed_url = oembed_base_url % {
                'url' : urllib.quote(url),
            }
            response = requests.get(oembed_url)
            if response.status_code >= 400:
                pass
            else:
                data = response.json()
                html = data['html']
                c.cache_store(html)
                success = True
        except:
            request = get_current_request()
            extra_data = {
                'message' : 'Bad oembed URL',
                'oembed_url' : oembed_url,
                'url' : url,
                'response' : {
                    'status_code' : response.status_code,
                    'content' : response.content,
                }
            }
            rollbar.report_exc_info(level='warning', request=request, extra_data=extra_data)

        if success:
            pass
        else:
            html = '<a href="%(url)s" target="_blank">%(url)s</a>' % {
                'url' : url,
            }
    else:
        pass
    return html
示例#41
0
    def wrapped(*args, **kwargs):
        # try to get a request, may not always succeed
        request = get_current_request()
        # notify a maximum of once per function per request/session
        if request:
            if DEPRECATED_ROLLBAR_NOTIFIED not in request.session:
                deprecated_notifications = {}
                request.session[DEPRECATED_ROLLBAR_NOTIFIED] = deprecated_notifications
            deprecated_notifications = request.session[DEPRECATED_ROLLBAR_NOTIFIED]
            key = '%s' % func
            # first get it
            already_notified = deprecated_notifications.get(key, False)
            # then mark it
            deprecated_notifications[key] = True
        else:
            already_notified = False

        if not already_notified:
            rollbar.report_message('Deprecated function call warning: %s' % func, 'warning', request)
        return func(*args, **kwargs)
示例#42
0
def default_event_type_resolver(event):
    """The Hacktoolkit-flavored default event type resolver for Alexa webhook events
    """
    event_handlers = get_event_handlers(event)

    try:
        request = event.get('request', {})
        request_type = request.get('type')
        if request_type == 'LaunchRequest':
            intent_name = 'launch'
        elif request_type == 'IntentRequest':
            intent_name = event['request'].get('intent', {}).get('name', None)
        else:
            intent_name = None
    except:
        from htk.utils.request import get_current_request
        request = get_current_request()
        extra_data = { 'event' : event, }
        rollbar.report_exc_info(request=request, extra_data=extra_data)

    event_type = intent_name if intent_name in event_handlers else 'default'
    return event_type
示例#43
0
    def handle_bad_response(self, response):
        request = get_current_request()
        api_request = response.request

        extra_data = self._get_rollbar_extra_data()
        extra_data.update({
            'api_request': {
                'url': api_request.url,
                'method': api_request.method,
                'body': api_request.body,
            },
            'response': {
                'status_code': response.status_code,
                'text': response.text,
            },
        })

        rollbar.report_message(
            '321Forms API Bad Response',
            request=request,
            extra_data=extra_data
        )
def default_event_type_resolver(event):
    """The Hacktoolkit-flavored default event type resolver for Alexa webhook events
    """
    event_handlers = get_event_handlers(event)

    try:
        request = event.get('request', {})
        request_type = request.get('type')
        if request_type == 'LaunchRequest':
            intent_name = 'launch'
        elif request_type == 'IntentRequest':
            intent_name = event['request'].get('intent', {}).get('name', None)
        else:
            intent_name = None
    except:
        from htk.utils.request import get_current_request
        request = get_current_request()
        extra_data = { 'event' : event, }
        rollbar.report_exc_info(request=request, extra_data=extra_data)

    event_type = intent_name if intent_name in event_handlers else 'default'
    return event_type
示例#45
0
def safe_stripe_call(func, *args, **kwargs):
    """Wrapper function for calling Stripe API

    Handles all the possible errors
    https://stripe.com/docs/api/python#errors
    """
    result = None
    try:
        result = func(*args, **kwargs)
    except stripe.error.CardError, e:
        # Since it's a decline, stripe.error.CardError will be caught
        #body = e.json_body
        #err  = body['error']

        #print "Status is: %s" % e.http_status
        #print "Type is: %s" % err.get('type')
        #print "Code is: %s" % err.get('code')
        ## param is '' in this case
        #print "Param is: %s" % err.get('param')
        #print "Message is: %s" % err.get('message')
        request = get_current_request()
        rollbar.report_exc_info(request=request)
示例#46
0
文件: utils.py 项目: pkkup/django-htk
def safe_stripe_call(func, *args, **kwargs):
    """Wrapper function for calling Stripe API

    Handles all the possible errors
    https://stripe.com/docs/api/python#errors
    """
    result = None
    try:
        result = func(*args, **kwargs)
    except stripe.error.CardError as e:
        # Since it's a decline, stripe.error.CardError will be caught
        #body = e.json_body
        #err  = body['error']

        #print "Status is: %s" % e.http_status
        #print "Type is: %s" % err.get('type')
        #print "Code is: %s" % err.get('code')
        ## param is '' in this case
        #print "Param is: %s" % err.get('param')
        #print "Message is: %s" % err.get('message')
        request = get_current_request()
        rollbar.report_exc_info(request=request)
    except stripe.error.InvalidRequestError as e:
        # Invalid parameters were supplied to Stripe's API
        request = get_current_request()
        rollbar.report_exc_info(request=request)
    except stripe.error.AuthenticationError as e:
        # Authentication with Stripe's API failed
        # (maybe you changed API keys recently)
        request = get_current_request()
        rollbar.report_exc_info(request=request)
    except stripe.error.APIConnectionError as e:
        # Network communication with Stripe failed
        request = get_current_request()
        rollbar.report_exc_info(request=request)
    except stripe.error.StripeError as e:
        # Display a very generic error to the user, and maybe send
        # yourself an email
        request = get_current_request()
        rollbar.report_exc_info(request=request)
    except Exception as e:
        # Something else happened, completely unrelated to Stripe
        request = get_current_request()
        rollbar.report_exc_info(request=request)
    return result
示例#47
0
 def _log_error():
     request = get_current_request()
     extra_data = {
     }
     rollbar.report_exc_info(request=request, extra_data=extra_data)
示例#48
0
 def can_emulate_user(self):
     from htk.utils.request import get_current_request
     request = get_current_request()
     can_emulate = self.user.profile.is_company_employee or request.original_user.profile.is_company_employee
     return can_emulate
示例#49
0
def associate_user_email(user, email, replacing=None, domain=None, email_template=None, email_subject=None, email_sender=None, confirmed=False):
    """Associates `email` with `user`

    Resulting UserEmail.is_confirmed = `confirmed`, default False

    Side effect: sends an activation email if `confirmed` == False

    Requires:
    `user` and `email` to be valid
    `email` cannot be confirmed by any other user
    `email` cannot already be associated with THIS `user`

    If `replacing` is specified, it denotes that it is being replaced by `email`
    """
    from htk.apps.accounts.models import UserEmail
    user_email = None
    if user and email:
        existing_user = get_user_by_email(email)
        should_associate = False
        if existing_user is None:
            # email address must not be associated to another account
            should_associate = True
        elif user == existing_user:
            if user.is_active:
                # an existing active account
                should_associate = True
            else:
                # a new registration
                should_associate = True
        else:
            # skip association
            # This email address is either:
            # a) already confirmed on another account
            # b) not already confirmed, and not a new registration
            should_associate = False

        if should_associate:
            user_email = get_user_email(user, email)
            if user_email is None:
                user_email = UserEmail.objects.create(user=user, email=email, is_confirmed=confirmed, replacing=replacing)

            if confirmed or user_email.is_confirmed:
                # don't need to send activation email for a pre-confirmed address
                # pre-confirmed email can come from a social auth provider
                user_email.confirm_and_activate_account()
                if replacing:
                    from htk.apps.accounts.utils.notifiers import notify_user_email_update
                    notify_user_email_update(user, replacing, email)

            elif not user_email.is_confirmed:
                domain = domain or htk_setting('HTK_DEFAULT_EMAIL_SENDING_DOMAIN')
                try:
                    user_email.send_activation_email(domain, template=email_template, subject=email_subject, sender=email_sender)
                except:
                    request = get_current_request()
                    rollbar.report_exc_info()
            else:
                pass
        else:
            pass
    else:
        # invalid user or email
        pass

    return user_email
示例#50
0
 def can_emulate_user(self):
     from htk.utils.request import get_current_request
     request = get_current_request()
     can_emulate = self.user.profile.is_company_employee or request.original_user.profile.is_company_employee
     return can_emulate