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
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
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
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
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)
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
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)
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
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 )
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
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
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)
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)
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
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)
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
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)
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
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
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
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
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
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
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
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
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
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
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
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)
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)
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
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
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)
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
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 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)
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
def _log_error(): request = get_current_request() extra_data = { } rollbar.report_exc_info(request=request, extra_data=extra_data)
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
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