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 activation_email(user_email, use_https=False, domain=None, template=None, subject=None): """Sends an activation/confirmation email for user to confirm email address """ user = user_email.user email = user_email.email domain = domain or htk_setting('HTK_DEFAULT_EMAIL_SENDING_DOMAIN') context = { 'user': user, 'email': email, 'protocol': use_https and 'https' or 'http', 'domain': domain, 'site_name': htk_setting('HTK_SITE_NAME'), 'confirm_email_path': reverse( htk_setting('HTK_ACCOUNTS_CONFIRM_EMAIL_URL_NAME'), args=(user_email.activation_key,) ), } if template is None: template='accounts/activation' if subject is None: subject = 'Confirm your email address, %s' % email activation_uri = '%(protocol)s://%(domain)s%(confirm_email_path)s' % context context['activation_uri'] = activation_uri bcc = htk_setting('HTK_DEFAULT_EMAIL_BCC') send_email( template=template, subject=subject, to=[email,], context=context, bcc=bcc )
def create_user_profile(sender, instance, created, **kwargs): """signal handler for User post-save """ if created: user = instance from htk.apps.accounts.utils.general import get_user_profile_model UserProfileModel = get_user_profile_model() profile = UserProfileModel.objects.create(user=user) profile.save() if not settings.TEST and htk_setting('HTK_SLACK_NOTIFICATIONS_ENABLED'): try: from htk.utils.notifications import slack_notify slack_notify('A new user has registered on the site %s: *%s <%s>*' % ( get_site_name(), user.profile.get_display_name(), user.email, )) if htk_setting('HTK_SLACK_BOT_ENABLED'): slack_notify('htk: emaildig %s' % user.email) except: rollbar.report_exc_info() if not settings.TEST and htk_setting('HTK_ITERABLE_ENABLED'): try: from htk.lib.iterable.utils import get_iterable_api_client itbl = get_iterable_api_client() itbl.notify_sign_up(user) except: rollbar.report_exc_info() if htk_setting('HTK_INVITATIONS_LIFECYCLE_SIGNALS_ENABLED'): from htk.apps.invitations.services import InvitationsService invitations_service = InvitationsService() invitations_service.process_user_created(user)
def check_email(request, details, user=None, *args, **kwargs): """Ask the user to enter the email if we don't have one yet The pipeline process was cut prior to this custom pipeline function, and will resume to this same function after completing """ response = None if user is None: social_email = details.get('email') collected_email = request.session.get(SOCIAL_REGISTRATION_SETTING_EMAIL) if social_email: # email available from social auth user = get_user_by_email(social_email) if user and user.is_active: # a user is already associated with this email # TODO: there is an error with linking accounts... request.session[SOCIAL_REGISTRATION_SETTING_EMAIL] = social_email if user.has_usable_password(): # user should log into the existing account with a password url_name = htk_setting('HTK_ACCOUNTS_REGISTER_SOCIAL_LOGIN_URL_NAME') else: # no password was set, so user must log in with another social auth account url_name = htk_setting('HTK_ACCOUNTS_REGISTER_SOCIAL_ALREADY_LINKED_URL_NAME') response = redirect(url_name) elif collected_email: # email provided by user details['email'] = collected_email response = { 'details' : details } else: # no email provided from social auth request.session[SOCIAL_REGISTRATION_SETTING_MISSING_EMAIL] = True url_name = htk_setting('HTK_ACCOUNTS_REGISTER_SOCIAL_EMAIL_URL_NAME') response = redirect(url_name) return response
def send_markdown_email( subject='', sender=None, to=None, cc=None, bcc=None, markdown_content='' ): """Sends an email w/ text and HTML produced from Markdown """ sender = sender or htk_setting('HTK_DEFAULT_EMAIL_SENDER', HTK_DEFAULT_EMAIL_SENDER) to = to or htk_setting('HTK_DEFAULT_EMAIL_RECIPIENTS', HTK_DEFAULT_EMAIL_RECIPIENTS) bcc = bcc or [] cc = cc or [] if settings.ENV_DEV: subject = '[%s-dev] %s' % (htk_setting('HTK_SYMBOLIC_SITE_NAME'), subject,) msg = EmailMultiAlternatives(subject=subject, body=markdown_content, from_email=sender, to=to, bcc=bcc, cc=cc) import markdown html_content = markdown.markdown(markdown_content) msg.attach_alternative(html_content, 'text/html') msg.send()
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 save(self, domain=None, email_template=None, email_subject=None, email_sender=None, commit=True): domain = domain or htk_setting('HTK_DEFAULT_EMAIL_SENDING_DOMAIN') user = super(NameEmailUserRegistrationForm, self).save(commit=False) email = self.email # temporarily assign a unique username so that we can create the record and the user can log in if htk_setting('HTK_ACCOUNTS_REGISTER_SET_PRETTY_USERNAME_FROM_EMAIL', False): user.username = email_to_username_pretty_unique(email) else: user.username = email_to_username_hash(email) #password1 = self.cleaned_data.get('password1') #user.set_password(password1) if commit: user.save() # associate user and email from htk.apps.accounts.utils import associate_user_email user_email = associate_user_email(user, email, domain=domain, email_template=email_template, email_subject=email_subject, email_sender=email_sender) # mark has_username_set user_profile = user.profile user_profile.has_username_set = True user_profile.save() # send welcome email was_activated = user.is_active if was_activated: user_profile.send_welcome_email() return user
def email_context_generator(): """Dummy email context generator Returns a dictionary """ request = GlobalRequestMiddleware.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'), } return context
def get_shopify_api_cli(shop_name=None, api_key=None, api_secret=None): from htk.lib.shopify_lib.api import HtkShopifyAPIClient shop_name = shop_name if shop_name else htk_setting('HTK_SHOPIFY_SHOP_NAME') api_key = api_key if api_key else htk_setting('HTK_SHOPIFY_API_KEY') api_secret = api_secret if api_secret else htk_setting('HTK_SHOPIFY_API_SECRET') api = HtkShopifyAPIClient(shop_name=shop_name, api_key=api_key, api_secret=api_secret) return api
def send_activation_reminder_email(self): """Sends an account activation reminder email Piggybacks off of `self.send_activation_email` """ template = htk_setting('HTK_ACCOUNT_ACTIVATION_REMINDER_EMAIL_TEMPLATE') subject = 'Reminder to activate your account on %s' % htk_setting('HTK_SITE_NAME') self.send_activation_email(resend=True, template=template, subject=subject)
def get_event_handler(event_type): event_handlers = htk_setting('HTK_ZUORA_EVENT_HANDLERS') event_type = event_type if event_type in event_handlers else 'default' if htk_setting('HTK_ZUORA_HANDLE_UNHANDLED_EVENTS') else None event_handler_module = event_handlers.get(event_type) if event_handler_module: event_handler = resolve_method_dynamically(event_handler_module) else: event_handler = None return event_handler
def get_event_handler_usages(event): event_handler_usages = copy.copy(htk_setting('HTK_SLACK_EVENT_HANDLER_USAGES')) webhook_settings = event.get('webhook_settings', {}) # add in additional event group handler usages extra_event_handler_usages = htk_setting('HTK_SLACK_EVENT_HANDLER_USAGES_EXTRA') for event_group, usages in extra_event_handler_usages.iteritems(): if webhook_settings.get(event_group, False) is True: event_handler_usages.update(usages) return event_handler_usages
def __init__(self, mongodb_connection=None, mongodb_name=None, api=None): if mongodb_connection is None: self.mongodb_connection = htk_setting('HTK_MONGODB_CONNECTION') else: self.mongodb_connection = mongodb_connection if mongodb_name is None: self.mongodb_name = htk_setting('HTK_MONGODB_NAME') else: self.mongodb_name = mongodb_name self.mongodb_initialized = False super(HtkShopifyMongoDBArchiver, self).__init__(api=api)
def set_input_placeholder_labels(form): """Set placeholder attribute to the field label on form input fields, if it doesn't have a placeholder set """ if htk_setting('HTK_FORMS_USE_CUSTOM_PLACEHOLDER_VALUES'): custom_labels = htk_setting('HTK_FORMS_CUSTOM_PLACEHOLDER_VALUES') else: custom_labels = {} for name, field in form.fields.items(): if field.widget.__class__ in TEXT_STYLE_INPUTS: if not field.widget.attrs.get('placeholder'): placeholder_value = custom_labels.get(name, field.label) field.widget.attrs['placeholder'] = placeholder_value
def password_changed_email(user): context = { 'user': user, 'email': user.email, 'domain': htk_setting('HTK_DEFAULT_DOMAIN'), 'site_name': htk_setting('HTK_SITE_NAME'), } send_email( template='accounts/password_changed', subject='Password changed on %s' % context['site_name'], to=[user.email], context=context )
def is_dev_host(host): """Determines whether `host` is a dev host """ canonical_domain = htk_setting('HTK_CANONICAL_DOMAIN') dev_host_regexps = htk_setting('HTK_DEV_HOST_REGEXPS') is_dev = False for r in dev_host_regexps: if re.match(r'%s%s' % (r, canonical_domain,), host): is_dev = True break else: pass return is_dev
def welcome_email(user): context = { 'user': user, 'site_name': htk_setting('HTK_SITE_NAME'), } bcc = htk_setting('HTK_DEFAULT_EMAIL_BCC') send_email( template='accounts/welcome', subject='Welcome to %s, %s' % (htk_setting('HTK_SITE_NAME'), user.email,), to=[user.email], context=context, bcc=bcc )
def get_activation_uri(self, use_https=False, domain=None): domain = domain or htk_setting('HTK_DEFAULT_EMAIL_SENDING_DOMAIN') values = { 'protocol' : 'https' if use_https else 'http', 'domain' : domain, 'confirm_email_path' : reverse( htk_setting('HTK_ACCOUNTS_CONFIRM_EMAIL_URL_NAME'), args=(self.activation_key,) ), } activation_uri = '%(protocol)s://%(domain)s%(confirm_email_path)s' % values return activation_uri
def get_event_handlers(event): """Gets all the event handlers available for `event` Specifically, this is the set of event handlers in {HTK_ALEXA_SKILL_EVENT_HANDLERS} """ event_handlers = copy.copy(htk_setting('HTK_ALEXA_SKILL_EVENT_HANDLERS')) # add in additional event group handlers extra_event_handlers = htk_setting('HTK_ALEXA_SKILL_EVENT_HANDLERS_EXTRAS') for event_group, handlers in extra_event_handlers.iteritems(): event_handlers.update(handlers) return event_handlers
def create_user_profile(sender, instance, created, **kwargs): """signal handler for User post-save """ if created: user = instance UserProfileModel = get_user_profile_model() profile = UserProfileModel.objects.create(user=user) profile.save() if htk_setting('HTK_SLACK_NOTIFICATIONS_ENABLED'): slack_notify('A new user has registered on the site %s: *%s <%s>*' % ( htk_setting('HTK_SITE_NAME'), user.profile.get_display_name(), user.email, ))
def password_changed_email(user): context = { 'user': user, 'email': user.email, 'domain': htk_setting('HTK_DEFAULT_DOMAIN'), 'site_name': htk_setting('HTK_SITE_NAME'), } subject = htk_setting('HTK_ACCOUNT_EMAIL_SUBJECT_PASSWORD_CHANGED') % context send_email( template='accounts/password_changed', subject=subject, to=[user.email], context=context )
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 log_event(event, request=None, log_level='info', message=None): """Log the Stripe event `event` """ live_mode = event.get('livemode', False) should_log = live_mode or htk_setting('HTK_STRIPE_LOG_TEST_MODE_EVENTS') if should_log: logger_type = htk_setting('HTK_STRIPE_EVENT_LOGGER') if logger_type == 'rollbar': _log_event_rollbar(event, request=None, log_level='info', message=None) else: # unrecognized Stripe event logger pass else: # do nothing pass
def simple_email( subject='', message='', sender=None, to=None, fail_silently=False ): """Sends a simple email """ sender = sender or htk_setting('HTK_DEFAULT_EMAIL_SENDER', HTK_DEFAULT_EMAIL_SENDER) to = to or htk_setting('HTK_DEFAULT_EMAIL_RECIPIENTS', HTK_DEFAULT_EMAIL_RECIPIENTS) if settings.ENV_DEV: fail_silently = True subject = '[%s-dev] %s' % (htk_setting('HTK_SYMBOLIC_SITE_NAME'), subject,) send_mail(subject, message, sender, to, fail_silently=fail_silently)
def get_weather(lat, lng): base_url = 'https://api.darksky.net/forecast/%(api_key)s/%(lat)s,%(lng)s' #base_url = 'https://api.forecast.io/forecast/%(api_key)s/%(lat)s,%(lng)s' api_key = htk_setting('HTK_DARKSKY_API_KEY') or htk_setting('HTK_FORECASTIO_API_KEY') url = base_url % { 'api_key' : api_key, 'lat' : lat, 'lng' : lng, } response = requests.get(url) if response.status_code == 200: weather = json.loads(response.content) else: weather = None return weather
def __init__(self): from htk.apps.accounts.cachekeys import AccountActivationReminderEmailCooldown template = htk_setting('HTK_ACCOUNT_ACTIVATION_REMINDER_EMAIL_TEMPLATE') super(AccountActivationReminderEmails, self).__init__( cooldown_class=AccountActivationReminderEmailCooldown, template=template )
def create_customer(card=None, email=None, description=""): """Create a Customer https://stripe.com/docs/tutorials/charges#saving-credit-card-details-for-later https://stripe.com/docs/api/python#create_customer """ live_mode = (settings.ENV_STAGE or settings.ENV_PROD) and htk_setting("HTK_STRIPE_LIVE_MODE") _initialize_stripe(live_mode=live_mode) params = {"email": email, "description": description} if card: params["card"] = card else: pass stripe_customer = safe_stripe_call(stripe.Customer.create, **params) if stripe_customer: StripeCustomerModel = get_stripe_customer_model() if StripeCustomerModel: customer = StripeCustomerModel.objects.create(stripe_id=stripe_customer.id, live_mode=live_mode) else: customer = None else: customer = None return customer, stripe_customer
def save(self, domain=None, commit=True): domain = domain or htk_setting('HTK_DEFAULT_EMAIL_SENDING_DOMAIN') user = super(UserRegistrationForm, self).save(commit=False) email = self.email # temporarily assign a unique username so that we can create the record and the user can log in user.username = email_to_username_hash(email) # we'll store the primary email in the User object user.email = email if not htk_setting('HTK_ACCOUNT_ACTIVATE_UPON_REGISTRATION', False): # require user to confirm email account before activating it user.is_active = False if commit: user.save() from htk.apps.accounts.utils import associate_user_email user_email = associate_user_email(user, email, domain) return user
def members_changelist_url(self): app_label = htk_setting('HTK_DEFAULT_APP_LABEL') members_changelist_url = '%s?organization__id__exact=%s' % ( reverse('admin:%s_%s_changelist' % (app_label, 'customer',)), self.id, ) return members_changelist_url
def get_geoip_country(): geoip_country_db = htk_setting('HTK_LIB_GEOIP_COUNTRY_DB') if geoip_country_db: gi_country = pygeoip.GeoIP(geoip_country_db) else: gi_country = None return gi_country
def activate(self, email_template=None, email_subject=None, email_sender=None): """Activate the User if not already activated """ was_activated = False user = self.user if not user.is_active: user.is_active = True user.save() was_activated = user.is_active if was_activated: # trigger notifications for an activated account should_send_welcome_email = True if htk_setting('HTK_ITERABLE_ENABLED'): try: itbl_opts = htk_setting('HTK_ITERABLE_OPTIONS') should_send_welcome_email = not itbl_opts.get( 'override_welcome_email', False) from htk.lib.iterable.utils import get_iterable_api_client itbl = get_iterable_api_client() itbl.notify_account_activation(user) except: rollbar.report_exc_info() if should_send_welcome_email: self.send_welcome_email(template=email_template, subject=email_subject, sender=email_sender) if htk_setting('HTK_SLACK_NOTIFICATIONS_ENABLED'): try: from htk.utils.notifications import slack_notify slack_notify('*%s* has activated their account on %s' % ( user.email, htk_setting('HTK_SITE_NAME'), )) except: rollbar.report_exc_info() return was_activated
def get_members(self): sort_order = htk_setting('HTK_ORGANIZATION_MEMBERS_SORT_ORDER') members = self.members.filter( active=True, user__is_active=True ).order_by( *sort_order ) return members
class BaseAbstractOrganizationMember(HtkBaseModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='organizations') organization = models.ForeignKey(htk_setting('HTK_ORGANIZATION_MODEL'), related_name='members') role = models.PositiveIntegerField(default=OrganizationMemberRoles.MEMBER.value, choices=get_organization_member_role_choices()) active = models.BooleanField(default=True) class Meta: abstract = True verbose_name = 'Organization Member'
def get_members(self): sort_order = htk_setting('HTK_ORGANIZATION_TEAM_MEMBERS_SORT_ORDER') members = self.members.filter( #active=True, # TODO: exclude users that are not active at the organization level user__is_active=True ).order_by( *sort_order ) return members
def prelaunch_email(prelaunch_signup): template = htk_setting('HTK_PRELAUNCH_EMAIL_TEMPLATE', HTK_PRELAUNCH_EMAIL_TEMPLATE) subject = htk_setting('HTK_PRELAUNCH_EMAIL_SUBJECT', HTK_PRELAUNCH_EMAIL_SUBJECT) bcc = htk_setting('HTK_PRELAUNCH_EMAIL_BCC', HTK_PRELAUNCH_EMAIL_BCC) context = { 'prelaunch_signup': prelaunch_signup, 'site_name': htk_setting('HTK_SITE_NAME') } send_email(template=template, subject=subject, to=[ prelaunch_signup.email, ], bcc=bcc, context=context)
def should_display_dismissible_alert(alert_name, alert_template, user, context, *args, **kwargs): result = False display_predicates = htk_setting('HTK_NOTIFICATIONS_DISMISSIBLE_ALERT_DISPLAY_PREDICATES') display_predicate_method = display_predicates.get(alert_name, None) if display_predicate_method: display_predicate = resolve_method_dynamically(display_predicate_method) if display_predicate: result = display_predicate(alert_name, alert_template, user, context, *args, **kwargs) return result
def get_alert_key(alert_name): alert_key = None alert_key_generators = htk_setting('HTK_NOTIFICATIONS_DISMISSIBLE_ALERT_KEY_GENERATORS') generator_method = alert_key_generators.get(alert_name, None) if generator_method: generator = resolve_method_dynamically(generator_method) if generator: alert_key = generator(alert_name) return alert_key
def is_prelaunch_exception_url(path): is_excepted = False prelaunch_exception_urls = htk_setting('HTK_PRELAUNCH_EXCEPTION_URLS', HTK_PRELAUNCH_EXCEPTION_URLS) for url in prelaunch_exception_urls: if re.match(url, path): is_excepted = True break return is_excepted
def simple_email(subject='', message='', sender=None, to=None, fail_silently=False): """Sends a simple email """ sender = sender or htk_setting('HTK_DEFAULT_EMAIL_SENDER', HTK_DEFAULT_EMAIL_SENDER) to = to or htk_setting('HTK_DEFAULT_EMAIL_RECIPIENTS', HTK_DEFAULT_EMAIL_RECIPIENTS) if settings.ENV_DEV: fail_silently = True subject = '[%s-dev] %s' % ( htk_setting('HTK_SYMBOLIC_SITE_NAME'), subject, ) send_mail(subject, message, sender, to, fail_silently=fail_silently)
def __init__(self, client_id=None, client_secret=None): if client_id is None: client_id = htk_setting('HTK_ZUORA_CLIENT_ID') if client_secret is None: client_secret = htk_setting('HTK_ZUORA_CLIENT_SECRET') self.client_id = client_id self.client_secret = client_secret self.access_token = None self.access_token_expires_at = None zuora_country = htk_setting('HTK_ZUORA_COUNTRY') zuora_api_mode = 'prod' if htk_setting('HTK_ZUORA_PROD') else 'sandbox' self.api_base_url = HTK_ZUORA_API_BASE_URLS[zuora_country][ zuora_api_mode] self.authenticate()
def _process_registration(self, domain, email_template, email_subject, email_sender, commit): domain = domain or htk_setting('HTK_DEFAULT_EMAIL_SENDING_DOMAIN') user = super(UserRegistrationForm, self).save(commit=False) # temporarily assign a unique username so that we can create the record and the user can log in if htk_setting('HTK_ACCOUNTS_REGISTER_SET_PRETTY_USERNAME_FROM_EMAIL', False): user.username = email_to_username_pretty_unique(email) else: user.username = email_to_username_hash(email) # we'll store the primary email in the User object user.email = email if not htk_setting('HTK_ACCOUNT_ACTIVATE_UPON_REGISTRATION', False): # require user to confirm email account before activating it user.is_active = False if commit: user.save() from htk.apps.accounts.utils import associate_user_email user_email = associate_user_email(user, email, domain=domain, email_template=email_template, email_subject=email_subject, email_sender=email_sender) return user
def process_user_email_association(sender, instance, created, **kwargs): """signal handler for UserEmail post-save """ user_email = instance if user_email.is_confirmed: if htk_setting('HTK_INVITATIONS_LIFECYCLE_SIGNALS_ENABLED'): from htk.apps.invitations.services import InvitationsService invitations_service = InvitationsService() invitations_service.process_user_email_confirmation(user_email)
def send_activation_reminder_email(self, template=None, subject=None, sender=None): """Sends an account activation reminder email Piggybacks off of `self.send_activation_email` """ if template is None: template = htk_setting( 'HTK_ACCOUNT_ACTIVATION_REMINDER_EMAIL_TEMPLATE') if subject is None: subject = 'Reminder to activate your account on %s' % htk_setting( 'HTK_SITE_NAME') self.send_activation_email(resend=True, template=template, subject=subject, sender=sender)
def get_view_context(request): view_context_generator = htk_setting( 'HTK_PRELAUNCH_VIEW_CONTEXT_GENERATOR', '') method = resolve_method_dynamically(view_context_generator) if method: context = method(request) else: context = {} return context
def is_prelaunch_mode(): is_prelaunch = htk_setting('HTK_PRELAUNCH_MODE', HTK_PRELAUNCH_MODE) if settings.TEST: from htk.test_scaffold.models import TestScaffold scaffold = TestScaffold() fake_prelaunch_mode = scaffold.get_fake_prelaunch_mode() if fake_prelaunch_mode is not None: is_prelaunch = fake_prelaunch_mode return is_prelaunch
def get_full_url(self, base_uri=None): if base_uri is None: domain = htk_setting('HTK_DEFAULT_DOMAIN') base_uri = 'http://%s' % domain cpq_url = self.get_url() full_url = '%s%s' % ( base_uri, cpq_url, ) return full_url
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 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 create_invoice_for_payment(self, stripe_customer, line_items): """Creates an invoice for this Quote with successful payment by `stripe_customer` for `line_items` """ InvoiceModel = resolve_model_dynamically( htk_setting('HTK_CPQ_INVOICE_MODEL')) invoice = InvoiceModel.objects.create(date=utcnow(), customer=self.customer, paid=True, quote=self) invoice.record_payment(stripe_customer, line_items)
def get_site_name(request=None): """Returns the current site name """ site = get_current_site(request=request) site_name = site.name if site else None if not site_name: site_name = htk_setting('HTK_SITE_NAME') return site_name
def has_company_email_domain(self): """Determines whether this User has email with company domain """ company_email_domains = htk_setting('HTK_COMPANY_EMAIL_DOMAINS') company_email_domains_re = '|'.join( [domain.replace(r'\.', r'\.') for domain in company_email_domains]) value = bool( re.match(r'^[A-Za-z0-9\.\+_-]+@(%s)' % company_email_domains_re, self.user.email)) return value
def organizations(self): from htk.utils.general import resolve_model_dynamically Organization = resolve_model_dynamically( htk_setting('HTK_ORGANIZATION_MODEL')) organizations = Organization.objects.filter( members__user=self.user, members__active=True).order_by( 'name', 'handle', ) return organizations
def members_changelist_url(self): app_label = htk_setting('HTK_DEFAULT_APP_LABEL') members_changelist_url = '%s?organization__id__exact=%s' % ( reverse('admin:%s_%s_changelist' % ( app_label, 'customer', )), self.id, ) return members_changelist_url
def get_event_type(event): """Get event type from Alexa skill webhook `event` """ event_type_resolver_module_str = htk_setting( 'HTK_ALEXA_SKILL_EVENT_TYPE_RESOLVER') from htk.utils.general import resolve_method_dynamically event_type_resolver = resolve_method_dynamically( event_type_resolver_module_str) event_type = event_type_resolver(event) return event_type
def reset_password(request, data=None, redirect_url_name='account_password_reset_success', template='account/reset_password.html', renderer=_r): """ View that checks the hash in a password reset link and presents a form for entering a new password. Based off of django.contrib.auth.views.password_reset_confirm Need to customize error display """ if data is None: data = wrap_data(request) uidb36 = request.GET.get('u', None) token = request.GET.get('t', None) token_generator = default_token_generator success = False response = None if uidb36 and token: UserModel = get_user_model() try: uid_int = base36_to_int(uidb36) user = UserModel.objects.get(id=uid_int) except (ValueError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True if request.method == 'POST': form = UpdatePasswordForm(user, request.POST) if form.is_valid(): user = form.save() if htk_setting( 'HTK_ACCOUNTS_CHANGE_PASSWORD_UPDATE_SESSION_AUTH_HASH' ): from django.contrib.auth import update_session_auth_hash update_session_auth_hash(request, user) success = True else: form = UpdatePasswordForm(None) if 'input_attrs' in data: set_input_attrs(form, attrs=data['input_attrs']) else: validlink = False form = None data['form'] = form data['validlink'] = validlink else: data['validlink'] = False if success: response = redirect(reverse(redirect_url_name)) else: response = renderer(request, template, data=data) return response
def webhook_call(webhook_url=None, channel=None, username=None, text='', attachments=None, icon_emoji=None, unfurl_links=True, unfurl_media=True, error_response_handlers=None): """Performs a webhook call to Slack https://api.slack.com/incoming-webhooks https://api.slack.com/docs/message-formatting `channel` override must be a public channel """ if webhook_url is None: webhook_url = htk_setting('HTK_SLACK_WEBHOOK_URL') payload = { 'text': text, 'unfurl_links': unfurl_links, 'unfurl_media': unfurl_media, } if channel: payload['channel'] = channel if username: payload['username'] = username if icon_emoji: payload['icon_emoji'] = icon_emoji if attachments: payload['attachments'] = attachments response = requests.post(webhook_url, json=payload) if response.status_code == 200: # success case, do nothing pass elif response.status_code <= 399: # 200-300, do nothing pass else: if handle_webhook_error_response(response, error_response_handlers): # successfully handled the webhook error pass else: extra_data = { 'webhook_url': webhook_url, 'payload': payload, } rollbar.report_message('Slack webhook call error: [%s] %s' % ( response.status_code, response.content, ), extra_data=extra_data) return response
def check_email(strategy, details, user=None, *args, **kwargs): """Ask the user to enter the email if we don't have one yet The pipeline process was cut prior to this custom pipeline function, and will resume to this same function after completing """ response = None if user is None: strategy.request.session['backend'] = kwargs.get( 'current_partial').backend social_email = details.get('email') collected_email = strategy.request.session.get( SOCIAL_REGISTRATION_SETTING_EMAIL) if social_email: # email available from social auth user = get_user_by_email(social_email) if user and user.is_active: # a user is already associated with this email # TODO: there is an error with linking accounts... strategy.request.session[ SOCIAL_REGISTRATION_SETTING_EMAIL] = social_email if user.has_usable_password(): # user should log into the existing account with a password url_name = htk_setting( 'HTK_ACCOUNTS_REGISTER_SOCIAL_LOGIN_URL_NAME') else: # no password was set, so user must log in with another social auth account url_name = htk_setting( 'HTK_ACCOUNTS_REGISTER_SOCIAL_ALREADY_LINKED_URL_NAME') response = redirect(url_name) elif collected_email: # email provided by user details['email'] = collected_email response = {'details': details} else: # no email provided from social auth strategy.request.session[ SOCIAL_REGISTRATION_SETTING_MISSING_EMAIL] = True url_name = htk_setting( 'HTK_ACCOUNTS_REGISTER_SOCIAL_EMAIL_URL_NAME') response = redirect(url_name) return response
def get_zestimate(zpid, zwsid=None): """Get the Zestimate for `zpid` `zpid` Zillow property id http://www.zillow.com/howto/api/GetZestimate.htm """ if zwsid is None: zwsid = htk_setting('HTK_ZILLOW_ZWSID') zestimate = Zestimate(zpid, zwsid) return zestimate
def get_num_server_api_keys(): """Returns the number of Google server API keys configured """ key = htk_setting('HTK_GOOGLE_SERVER_API_KEY') if type(key) == str: num = 1 elif hasattr(key, '__iter__'): num = len(key) else: num = 0 return num