Ejemplo n.º 1
0
    def _reset_activation_key(self, resend=False):
        """Resets the activation key

        `resend` whether this key is being reset as the result of a resend confirmation email

        If `resend`, then check the `key_expires` timestamp to see if we should reuse the existing activation key, or generate a new one
        """
        should_reset = True
        if resend and self.activation_key and self.key_expires:
            now = utcnow()
            if now < self.key_expires:
                # do not reset key if remaining time has not fallen below threshold
                remaining_time = self.key_expires - now
                threshold = datetime.timedelta(hours=EMAIL_ACTIVATION_KEY_REUSE_THRESHOLD_HOURS)
                should_reset = remaining_time < threshold

        if should_reset:
            user = self.user
            salt = sha1(str(random.random())).hexdigest()[:5]
            activation_key = sha1(salt + user.username).hexdigest()
            key_expires = utcnow() + datetime.timedelta(hours=EMAIL_ACTIVATION_KEY_EXPIRATION_HOURS)

            self.activation_key = activation_key
            self.key_expires = key_expires
            self.save()
        else:
            # no need to reset activation key, use the same one
            pass
Ejemplo n.º 2
0
    def _reset_activation_key(self, resend=False):
        """Resets the activation key

        `resend` whether this key is being reset as the result of a resend confirmation email

        If `resend`, then check the `key_expires` timestamp to see if we should reuse the existing activation key, or generate a new one
        """
        should_reset = True
        if resend and self.activation_key and self.key_expires:
            now = utcnow()
            if now < self.key_expires:
                # do not reset key if remaining time has not fallen below threshold
                remaining_time = self.key_expires - now
                threshold = datetime.timedelta(
                    hours=EMAIL_ACTIVATION_KEY_REUSE_THRESHOLD_HOURS)
                should_reset = remaining_time < threshold

        if should_reset:
            user = self.user
            salt = sha1(str(random.random())).hexdigest()[:5]
            activation_key = sha1(salt + user.username).hexdigest()
            key_expires = utcnow() + datetime.timedelta(
                hours=EMAIL_ACTIVATION_KEY_EXPIRATION_HOURS)

            self.activation_key = activation_key
            self.key_expires = key_expires
            self.save()
        else:
            # no need to reset activation key, use the same one
            pass
Ejemplo n.º 3
0
def main():
    # use date as asset_version because it is unique at the time of deploy
    now = utcnow()
    asset_version = now.strftime('%Y%m%d%H%M%S')
    slog('New asset version: %s' % asset_version)
    c = StaticAssetVersionCache()
    c.cache_store(asset_version)
Ejemplo n.º 4
0
def utcnow_slack(event, **kwargs):
    """utcnow event handler for Slack webhook events
    """
    text = kwargs.get('text')
    command = kwargs.get('command')
    args = kwargs.get('args')

    if command == 'utcnow':
        from htk.utils import utcnow
        now = utcnow()
        webhook_settings = event['webhook_settings']
        user_id = webhook_settings['user']
        from htk.apps.accounts.utils import get_user_by_id
        user = get_user_by_id(user_id)
        slack_text = """*The time is now*:\n
*UTC*: %s
*%s*: %s""" % (
            now,
            user.profile.get_timezone(),
            user.profile.get_local_time(dt=now),
        )
    else:
        slack_text = 'Illegal command.'

    payload = {
        'text': slack_text,
    }
    return payload
Ejemplo n.º 5
0
def confirm_email(
    request,
    activation_key,
    data=None,
    resend_confirmation_url_name='account_resend_confirmation',
    template='account/confirm_email.html',
    renderer=_r
):
    if data is None:
        data = wrap_data(request)

    user = request.user
    user_email = get_object_or_404(UserEmail,
                                   activation_key=activation_key)
    if user and user != user_email.user:
        # for a mismatched user, force logout
        logout(request)
        user = None
        data['user'] = None

    # attempt to confirm
    if user_email.key_expires < utcnow():
        data['expired'] = True
        data['resend_confirmation_uri'] = reverse(resend_confirmation_url_name)
    else:
        was_activated = user_email.confirm_and_activate_account()
        data['was_activated'] = was_activated
        data['success'] = True

    response = renderer(template, data)
    return response
Ejemplo n.º 6
0
def confirm_email(request,
                  activation_key,
                  data=None,
                  resend_confirmation_url_name='account_resend_confirmation',
                  template='account/confirm_email.html',
                  email_template=None,
                  email_subject=None,
                  email_sender=None,
                  renderer=_r):
    if data is None:
        data = wrap_data(request)

    user = request.user
    user_email = get_object_or_404(UserEmail, activation_key=activation_key)
    if user and user != user_email.user:
        # for a mismatched user, force logout
        logout(request)
        user = None
        data['user'] = None

    # attempt to confirm
    if user_email.key_expires < utcnow():
        data['expired'] = True
        data['resend_confirmation_uri'] = reverse(resend_confirmation_url_name)
    else:
        was_activated = user_email.confirm_and_activate_account(
            email_template=email_template,
            email_subject=email_subject,
            email_sender=email_sender)
        data['was_activated'] = was_activated
        data['success'] = True

    response = renderer(template, data)
    return response
def main():
    # use date as asset_version because it is unique at the time of deploy
    now = utcnow()
    asset_version = now.strftime("%Y%m%d%H%M%S")
    slog("New asset version: %s" % asset_version)
    c = StaticAssetVersionCache()
    c.cache_store(asset_version)
Ejemplo n.º 8
0
    def is_valid(self):
        now = utcnow()

        is_valid = ((self.valid_after is None or now >= self.valid_after)
                    and (self.valid_until is None or now <= self.valid_until))

        return is_valid
Ejemplo n.º 9
0
def utcnow_slack(event, **kwargs):
    """utcnow event handler for Slack webhook events
    """
    text = kwargs.get('text')
    command = kwargs.get('command')
    args = kwargs.get('args')

    if command == 'utcnow':
        from htk.utils import utcnow
        now = utcnow()
        webhook_settings = event['webhook_settings']
        user_id = webhook_settings['user']
        from htk.apps.accounts.utils import get_user_by_id
        user = get_user_by_id(user_id)
        slack_text = """*The time is now*:\n
*UTC*: %s
*%s*: %s""" % (
    now,
    user.profile.get_timezone(),
    user.profile.get_local_time(dt=now),
)
    else:
        slack_text = 'Illegal command.'

    payload = {
        'text' : slack_text,
    }
    return payload
Ejemplo n.º 10
0
def users_logged_in_within_period(users, window=1):
    """Filter the queryset of users who logged in within the last `window` number of hours.
    """
    threshold = utcnow() - datetime.timedelta(hours=window)
    filtered = users.filter(
        last_login__gte=threshold
    ).order_by(
        '-last_login'
    )
    return filtered
Ejemplo n.º 11
0
 def get_local_time(self, dt=None):
     """Gets the current local time for User
     If `dt` is specified, format `dt` into User's timezone
     """
     tz = self.get_django_timezone()
     if dt is None:
         local_time = utcnow().astimezone(tz)
     else:
         local_time = dt.astimezone(tz)
     return local_time
Ejemplo n.º 12
0
 def get_local_time(self, dt=None):
     """Gets the current local time for User
     If `dt` is specified, format `dt` into User's timezone
     """
     tz = self.get_django_timezone()
     if dt is None:
         local_time = utcnow().astimezone(tz)
     else:
         local_time = dt.astimezone(tz)
     return local_time
Ejemplo n.º 13
0
def users_registered_within_period(users, window=1):
    """Filter the queryset of users who registered within the last `window` number of hours.
    """
    threshold = utcnow() - datetime.timedelta(hours=window)
    filtered = users.filter(
        date_joined__gte=threshold
    ).order_by(
        '-date_joined'
    )
    return filtered
Ejemplo n.º 14
0
 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)
Ejemplo n.º 15
0
def users_registered_within_period(users, window=1):
    """Filter the queryset of users who registered within the last `window` number of hours.
    """
    threshold = utcnow() - datetime.timedelta(hours=window)
    filtered = users.filter(
        date_joined__gte=threshold
    ).order_by(
        '-date_joined'
    )
    return filtered
Ejemplo n.º 16
0
def users_logged_in_within_period(users, window=1):
    """Filter the queryset of users who logged in within the last `window` number of hours.
    """
    threshold = utcnow() - datetime.timedelta(hours=window)
    filtered = users.filter(
        last_login__gte=threshold
    ).order_by(
        '-last_login'
    )
    return filtered
Ejemplo n.º 17
0
 def get_recipients(self):
     from htk.apps.accounts.utils.lookup import get_inactive_users
     inactive_users = get_inactive_users()
     # send reminders after 1 day and up to 3 weeks
     account_creation_threshold_upper = utcnow() - datetime.timedelta(days=1)
     account_creation_threshold_lower = account_creation_threshold_upper - datetime.timedelta(days=21)
     users = inactive_users.filter(
         date_joined__gte=account_creation_threshold_lower,
         date_joined__lte=account_creation_threshold_upper
     )
     return users
Ejemplo n.º 18
0
 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)
Ejemplo n.º 19
0
def validate_user_token_auth_token(token):
    """Validates a user token-auth token

    Returns a 2-tuple of `(user, is_valid,)`

    Defaults to `(None, False,)`
    """
    user = None
    is_valid = False

    try:
        data = json.loads(base64.b64decode(token))
    except ValueError:
        data = None

    if data is not None:
        # verify expiration of token

        expires_timestamp = data.get('expires', 0)
        expires = unix_time_to_datetime(expires_timestamp)

        if expires > utcnow():
            # token has not expired

            encrypted_uid = data.get('user', -1)
            user = resolve_encrypted_uid(encrypted_uid)

            if user:
                # found a matching user
                # verify hash

                received_hash = data.get('hash', None)
                expected_hash = get_user_token_auth_hash(
                    user, expires_timestamp)

                if received_hash == expected_hash:
                    # hash matches
                    is_valid = True
                else:
                    # hash does not match
                    user = None
            else:
                # no user found
                pass

        else:
            # token has expired
            pass

    return (
        user,
        is_valid,
    )
Ejemplo n.º 20
0
 def get_recipients(self):
     from htk.apps.accounts.utils.lookup import get_inactive_users
     inactive_users = get_inactive_users()
     # send reminders after 1 day and up to 3 weeks
     account_creation_threshold_upper = utcnow() - datetime.timedelta(
         days=1)
     account_creation_threshold_lower = account_creation_threshold_upper - datetime.timedelta(
         days=21)
     users = inactive_users.filter(
         date_joined__gte=account_creation_threshold_lower,
         date_joined__lte=account_creation_threshold_upper)
     return users
Ejemplo n.º 21
0
def get_asset_version():
    """Get asset_version from cache
    This value is updated whenever we deploy. See fab_helpers.py

    If not available from cache, default value is current date.
    """
    c = StaticAssetVersionCache()
    asset_version = c.get()
    if asset_version is None:
        now = utcnow()
        asset_version = now.strftime('%Y%m%d%H')
    return asset_version
Ejemplo n.º 22
0
def get_asset_version():
    """Get asset_version from cache
    This value is updated whenever we deploy. See fab_helpers.py

    If not available from cache, default value is current date.
    """
    c = StaticAssetVersionCache()
    asset_version = c.get()
    if asset_version is None:
        now = utcnow()
        asset_version = now.strftime('%Y%m%d%H')
    return asset_version
Ejemplo n.º 23
0
 def get_weight_logs_past_day(self):
     """Get Weight logs for the past day
     """
     resource_args = (
         utcnow().strftime('%Y-%m-%d'),
         '1d',
     )
     response = self.get('weight', resource_args=resource_args)
     if response.status_code == 200:
         weight_logs = response.json()['weight']
         weight_logs = weight_logs[::-1]
     else:
         weight_logs = None
     return weight_logs
Ejemplo n.º 24
0
 def get_body_fat_logs_past_day(self):
     """Get Body Fat logs for the past day
     """
     resource_args = (
         utcnow().strftime('%Y-%m-%d'),
         '1d',
     )
     response = self.get('fat', resource_args=resource_args)
     if response.status_code == 200:
         fat_logs = response.json()['fat']
         fat_logs = fat_logs[::-1]
     else:
         fat_logs = None
     return fat_logs
Ejemplo n.º 25
0
 def notify_account_activation(self, user):
     """Notify Iterable of a `user` activation event
     """
     # avoid circular import
     from htk.lib.iterable.utils import get_workflow_id
     account_activation_workflow_id = get_workflow_id('account_activation')
     if account_activation_workflow_id is not None:
         payload = {
             'dataFields' : {
                 'userId' : user.id,
                 'date_activated' : utcnow().strftime(ITERABLE_DATE_FORMAT),
             },
         }
         self.trigger_workflow(user.email, account_activation_workflow_id, payload=payload)
Ejemplo n.º 26
0
 def notify_account_activation(self, user):
     """Notify Iterable of a `user` activation event
     """
     # avoid circular import
     from htk.lib.iterable.utils import get_workflow_id
     account_activation_workflow_id = get_workflow_id('account.activation')
     if account_activation_workflow_id is not None:
         payload = {
             'dataFields' : {
                 'userId' : user.id,
                 'date_activated' : utcnow().strftime(ITERABLE_DATE_FORMAT),
             },
         }
         self.trigger_workflow(user.profile.confirmed_email or user.email, account_activation_workflow_id, payload=payload)
Ejemplo n.º 27
0
 def get_body_fat_logs_past_day(self):
     """Get Body Fat logs for the past day
     """
     resource_args = (
         utcnow().strftime('%Y-%m-%d'),
         '1d',
     )
     response = self.get('fat', resource_args=resource_args)
     if response.status_code == 200:
         fat_logs = response.json()['fat']
         fat_logs = fat_logs[::-1]
     else:
         fat_logs = None
     return fat_logs
Ejemplo n.º 28
0
 def get_weight_logs_past_day(self):
     """Get Weight logs for the past day
     """
     resource_args = (
         utcnow().strftime('%Y-%m-%d'),
         '1d',
     )
     response = self.get('weight', resource_args=resource_args)
     if response.status_code == 200:
         weight_logs = response.json()['weight']
         weight_logs = weight_logs[::-1]
     else:
         weight_logs = None
     return weight_logs
Ejemplo n.º 29
0
def validate_user_token_auth_token(token):
    """Validates a user token-auth token

    Returns a 2-tuple of `(user, is_valid,)`

    Defaults to `(None, False,)`
    """
    user = None
    is_valid = False

    try:
        data = json.loads(base64.b64decode(token))
    except ValueError:
        data = None

    if data is not None:
        # verify expiration of token

        expires_timestamp = data.get('expires', 0)
        expires = unix_time_to_datetime(expires_timestamp)

        if expires > utcnow():
            # token has not expired

            encrypted_uid = data.get('user', -1)
            user = resolve_encrypted_uid(encrypted_uid)

            if user:
                # found a matching user
                # verify hash

                received_hash = data.get('hash', None)
                expected_hash = get_user_token_auth_hash(user, expires_timestamp)

                if received_hash == expected_hash:
                    # hash matches
                    is_valid = True
                else:
                    # hash does not match
                    user = None
            else:
                # no user found
                pass

        else:
            # token has expired
            pass

    return (user, is_valid,)
Ejemplo n.º 30
0
    def is_enabled(self):
        is_enabled = self.enabled

        if not is_enabled:
            if self.enabled_after is not None:
                now = utcnow()
                is_enabled = (now >= self.enabled_after
                              and (self.disabled_after is None
                                   or now <= self.disabled_after))
            else:
                pass
        else:
            pass

        return is_enabled
Ejemplo n.º 31
0
def confirm_email(
    request,
    activation_key,
    data=None,
    resend_confirmation_url_name='account_resend_confirmation',
    template='account/confirm_email.html',
    email_template=None,
    email_subject=None,
    email_sender=None,
    success_url_name=None,
    success_message=None,
    renderer=_r
):
    if data is None:
        data = wrap_data(request)

    user = request.user
    user_email = get_object_or_404(
        UserEmail,
        activation_key=activation_key
    )
    if user and user != user_email.user:
        # for a mismatched user, force logout
        logout(request)
        user = None
        data['user'] = None

    # attempt to confirm
    if user_email.key_expires < utcnow():
        data['expired'] = True
        data['resend_confirmation_uri'] = reverse(resend_confirmation_url_name)
    else:
        was_activated = user_email.confirm_and_activate_account(email_template=email_template, email_subject=email_subject, email_sender=email_sender)
        data['was_activated'] = was_activated
        data['success'] = True

    if data.get('success') and success_url_name is not None:
        clear_messages(request)
        if success_message is not None:
            messages.success(request, success_message)
        response = redirect(reverse(success_url_name))
    else:
        response = renderer(request, template, data=data)

    return response
Ejemplo n.º 32
0
    def make_request_headers(self, action='GET', username=None, secret_key=None):
        """Creates a header to pass in for GET/POST request

        `action`: 'GET' or 'POST'

        More about the authorization header can be found here: https://api.321forms.com/docs
        """
        username = username if username else self.username
        secret_key = secret_key if secret_key else self.secret_key

        sent_date = utcnow().strftime('%Y-%m-%d %H:%M:%S')
        headers = {
            'Username': username,
            'SentDate': "{ts \'%s\'}" % sent_date,
            'Action': action,
        }

        authorization_key = self._make_authorization_key(headers, secret_key)
        headers['Authorization'] = authorization_key
        return headers
Ejemplo n.º 33
0
def get_bart_schedule_depart(orig_station, dest_station, delay_mins=None):
    api_key = htk_setting('HTK_BART_API_KEY')
    api = BartAPI(api_key)

    if delay_mins:
        now = utcnow().astimezone(pytz.timezone('America/Los_Angeles'))
        depart_time = now + datetime.timedelta(minutes=delay_mins)
        depart_time_str = depart_time.strftime('%I:%M%p').lower()
        api_result = api.get_schedule_depart(orig_station, dest_station, time=depart_time_str, trips_before=0)
    else:
        api_result = api.get_schedule_depart(orig_station, dest_station)

    data = {
        'origin' : orig_station.upper(),
        'destination' : dest_station.upper(),
        'orig_station_name' : get_station_name(orig_station),
        'dest_station_name' : get_station_name(dest_station),
    }
    data.update(api_result)
    return data
Ejemplo n.º 34
0
    def make_request_headers(self, action='GET', username=None, secret_key=None):
        """Creates a header to pass in for GET/POST request

        `action`: 'GET' or 'POST'

        More about the authorization header can be found here: https://api.321forms.com/docs
        """
        username = username if username else self.username
        secret_key = secret_key if secret_key else self.secret_key

        sent_date = utcnow().strftime('%Y-%m-%d %H:%M:%S')
        headers = {
            'Username' : username,
            'SentDate' : "{ts \'%s\'}" % sent_date,
            'Action' : action,
        }

        authorization_key = self._make_authorization_key(headers, secret_key)
        headers['Authorization'] = authorization_key
        return headers
Ejemplo n.º 35
0
def get_user_token_auth_token(user, expires_minutes=None):
    """Returns the token to auth/log in the `user`

    Typically would want to include the generated token in an email
    so that that user can directly log in to the app.
    """
    encrypted_uid = encrypt_uid(user)

    expires_minutes = expires_minutes if expires_minutes else htk_setting('HTK_USER_TOKEN_AUTH_EXPIRES_MINUTES')
    expires = utcnow() + datetime.timedelta(minutes=expires_minutes)
    expires_timestamp = datetime_to_unix_time(expires)

    hashed = get_user_token_auth_hash(user, expires_timestamp)

    data = {
        'user' : encrypted_uid,
        'expires' : expires_timestamp,
        'hash' : hashed,
    }

    token = base64.b64encode(json.dumps(data).encode('utf-8')).decode('utf-8')
    return token
Ejemplo n.º 36
0
def get_user_token_auth_token(user, expires_minutes=None):
    """Returns the token to auth/log in the `user`

    Typically would want to include the generated token in an email
    so that that user can directly log in to the app.
    """
    encrypted_uid = encrypt_uid(user)

    expires_minutes = expires_minutes if expires_minutes else htk_setting('HTK_USER_TOKEN_AUTH_EXPIRES_MINUTES')
    expires = utcnow() + datetime.timedelta(minutes=expires_minutes)
    expires_timestamp = datetime_to_unix_time(expires)

    hashed = get_user_token_auth_hash(user, expires_timestamp)

    data = {
        'user' : encrypted_uid,
        'expires' : expires_timestamp,
        'hash' : hashed,
    }

    token = base64.b64encode(json.dumps(data))
    return token
Ejemplo n.º 37
0
def confirm_email(request, activation_key):
    data = wrap_data_accounts(request)
    user = data['user']
    user_email = get_object_or_404(UserEmail,
                                   activation_key=activation_key)
    if user and user != user_email.user:
        # for a mismatched user, force logout
        logout(request)
        user = None
        data['user'] = None

    # attempt to confirm
    if user_email.key_expires < utcnow():
        data['expired'] = True
    else:
        was_activated = user_email.confirm_and_activate_account()
        data['was_activated'] = was_activated
        data['success'] = True

    response = _r('account/confirm_email.html', data)

    return response
Ejemplo n.º 38
0
 def get_local_time(self):
     """Gets the current local time for user
     """
     tz = self.get_django_timezone()
     now = utcnow().astimezone(tz)
     return now