Python django.utils.http.base36_to_int() Examples

The following are 15 code examples of django.utils.http.base36_to_int(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.http , or try the search function .
Example #1
Source File: tokens.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example #2
Source File: utils.py    From django-users2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a activation token is correct for a given user.
        """
        # Parse the token
        try:
            ts_b36, hash = token.split('-')
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.USERS_EMAIL_CONFIRMATION_TIMEOUT_DAYS:
            return False

        return True 
Example #3
Source File: tokens.py    From fomalhaut-panel with MIT License 6 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example #4
Source File: utils.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def url_str_to_user_pk(s):
    User = get_user_model()
    # TODO: Ugh, isn't there a cleaner way to determine whether or not
    # the PK is a str-like field?
    if getattr(User._meta.pk, 'rel', None):
        pk_field = User._meta.pk.rel.to._meta.pk
    else:
        pk_field = User._meta.pk
    if (hasattr(models, 'UUIDField') and issubclass(
            type(pk_field), models.UUIDField)):
        return s
    try:
        pk_field.to_python('a')
        pk = s
    except ValidationError:
        pk = base36_to_int(s)
    return pk 
Example #5
Source File: tokens.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example #6
Source File: views.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def password_reset_confirm(request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html',
                           token_generator=default_token_generator, set_password_form=SetPasswordForm,
                           post_reset_redirect=None):
    """
    View that checks the hash in a password reset link and presents a
    form for entering a new password.
    """
    assert uidb36 is not None and token is not None # checked by URLconf
    if post_reset_redirect is None:
        post_reset_redirect = reverse('drawquest.apps.drawquest_auth.views.password_reset_complete')
    try:
        uid_int = base36_to_int(uidb36)
        user = User.objects.get(id=uid_int)
    except (ValueError, User.DoesNotExist):
        user = None

    ctx = {}

    if user is not None and token_generator.check_token(user, token):
        ctx['validlink'] = True
        if request.method == 'POST':
            form = set_password_form(user, request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(post_reset_redirect)
        else:
            form = set_password_form(None)
    else:
        ctx['validlink'] = False
        form = None
    ctx['form'] = form
    return r2r_jinja(template_name, ctx, request) 
Example #7
Source File: tokens.py    From bioforum with MIT License 5 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        if not (user and token):
            return False
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example #8
Source File: tokens.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        if not (user and token):
            return False
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit. Timestamps are rounded to
        # midnight (server time) providing a resolution of only 1 day. If a
        # link is generated 5 minutes before midnight and used 6 minutes later,
        # that counts as 1 day. Therefore, PASSWORD_RESET_TIMEOUT_DAYS = 1 means
        # "at least 1 day, could be up to 2."
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example #9
Source File: classes.py    From django-htk with MIT License 5 votes vote down vote up
def from_encoded_id_luhn_base36(cls, encoded_id):
        from htk.utils.luhn import is_luhn_valid
        id_with_luhn = base36_to_int(encoded_id)
        if is_luhn_valid(id_with_luhn):
            xored = id_with_luhn // 10
            xor_key = cls._luhn_xor_key()
            obj_id =  xored ^ xor_key
            obj = cls.objects.get(id=obj_id)
        else:
            obj = None
        return obj 
Example #10
Source File: general.py    From django-htk with MIT License 5 votes vote down vote up
def decrypt_uid(encrypted_uid):
    uid_xor = htk_setting('HTK_USER_ID_XOR')
    user_id = base36_to_int(encrypted_uid) ^ uid_xor
    return user_id 
Example #11
Source File: crypto.py    From django-htk with MIT License 5 votes vote down vote up
def resolve_cpq_code(cpq_code, cpq_type=CPQType.INVOICE):
    """Returns the CPQ object (Quote or Invoice) for this `cpq_code`
    """
    check_hash = cpq_code[:CPQ_CHECK_HASH_LENGTH]
    cpq_code = cpq_code[CPQ_CHECK_HASH_LENGTH:]
    if is_valid_cpq_code_check_hash(cpq_code, check_hash):
        if cpq_type == CPQType.INVOICE:
            CPQModel = resolve_model_dynamically(settings.HTK_CPQ_INVOICE_MODEL)
        elif cpq_type == CPQType.QUOTE:
            CPQModel = resolve_model_dynamically(settings.HTK_CPQ_QUOTE_MODEL)
        elif cpq_type == CPQType.GROUP_QUOTE:
            CPQModel = resolve_model_dynamically(settings.HTK_CPQ_GROUP_QUOTE_MODEL)
        else:
            raise Exception('Bad value for cpq_type')
        try:
            padded = base36_to_int(cpq_code)
            if is_luhn_valid(padded):
                xored = padded // 10
                cpq_id = xored ^ CPQ_XOR_KEY
                cpq = CPQModel.objects.get(id=cpq_id)
            else:
                cpq = None
        except ValueError:
            cpq = None
        except CPQModel.DoesNotExist:
            cpq = None
    else:
        cpq = None
    return cpq 
Example #12
Source File: tokens.py    From python2017 with MIT License 5 votes vote down vote up
def check_token(self, user, token):
        """
        Check that a password reset token is correct for a given user.
        """
        if not (user and token):
            return False
        # Parse the token
        try:
            ts_b36, hash = token.split("-")
        except ValueError:
            return False

        try:
            ts = base36_to_int(ts_b36)
        except ValueError:
            return False

        # Check that the timestamp/uid has not been tampered with
        if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
            return False

        # Check the timestamp is within limit
        if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
            return False

        return True 
Example #13
Source File: views.py    From devops with MIT License 5 votes vote down vote up
def get_user(self):
        try:
            uid_int = base36_to_int(self.kwargs["uidb36"])
        except ValueError:
            raise Http404()
        return get_object_or_404(get_user_model(), id=uid_int) 
Example #14
Source File: hash.py    From eoj3 with MIT License 5 votes vote down vote up
def check_token(self, user, token, expire_minutes=-1):
    try:
      (timestamp, content_type_id, object_id, _) = token.split("-")
      timestamp = base36_to_int(timestamp)
      content_type_id = base36_to_int(content_type_id)
      object_id = base36_to_int(object_id)
    except ValueError:
      return None
    if not constant_time_compare(self._make_hash(user, timestamp, content_type_id, object_id), token):
      return None
    if self._num_minutes() - timestamp > expire_minutes > 0:
      return None
    return ContentType.objects.get_for_id(content_type_id).get_object_for_this_type(pk=object_id) 
Example #15
Source File: views.py    From django-htk with MIT License 4 votes vote down vote up
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