我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用django.utils.http.int_to_base36()。
def _make_token_with_timestamp(self, user, timestamp): # timestamp is number of days since 2001-1-1. Converted to # base 36, this gives us a 3 digit string until about 2121 ts_b36 = int_to_base36(timestamp) # By hashing on the internal state of the user and using state # that is sure to change (the password salt will change as soon as # the password is set, at least for current Django auth, and # last_login will also change), we produce a hash that will be # invalid as soon as it is used. # We limit the hash to 20 chars to keep URL short hash = salted_hmac( self.key_salt, self._make_hash_value(user, timestamp), ).hexdigest()[::2] return "%s-%s" % (ts_b36, hash)
def send_email(self, email): protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") current_site = get_current_site(self.request) for user in User.objects.filter(email__iexact=email): uid = int_to_base36(user.id) token = self.make_token(user) password_reset_url = u"%s://%s%s" % ( protocol, unicode(current_site.domain), reverse("account_password_reset_token", kwargs=dict(uidb36=uid, token=token)) ) ctx = { "user": user, "current_site": current_site, "password_reset_url": password_reset_url, } subject = render_to_string("account/email/password_reset_subject.txt", ctx) subject = "".join(subject.splitlines()) message = render_to_string("account/email/password_reset.txt", ctx) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email])
def send_email(self, email): User = get_user_model() protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") current_site = get_current_site(self.request) email_qs = EmailAddress.objects.filter(email__iexact=email) for user in User.objects.filter(pk__in=email_qs.values("user")): uid = int_to_base36(user.id) token = self.make_token(user) password_reset_url = "{0}://{1}{2}".format( protocol, current_site.domain, reverse("account_password_reset_token", kwargs=dict(uidb36=uid, token=token)) ) ctx = { "user": user, "current_site": current_site, "password_reset_url": password_reset_url, } hookset.send_password_reset_email([user.email], ctx)
def get_confirmation_url(email, request, user=None, name='email_registration_confirm'): """ Returns the confirmation URL """ code = [email, '', ''] if user: code[1] = str(user.id) code[2] = int_to_base36(get_last_login_timestamp(user)) return request.build_absolute_uri( reverse( name, kwargs={ 'code': get_signer().sign(u':'.join(code)), }))
def _make_token_with_timestamp(self, user, timestamp): # timestamp is number of days since 2001-1-1. Converted to # base 36, this gives us a 3 digit string until about 2121 ts_b36 = int_to_base36(timestamp) # By hashing on the internal state of the user and using state # that is sure to change (the password salt will change as soon as # the password is set, at least for current Django auth, and # last_login will also change), we produce a hash that will be # invalid as soon as it is used. # We limit the hash to 20 chars to keep URL short key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" # Ensure results are consistent across DB backends login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None) value = (six.text_type(user.pk) + user.password + six.text_type(login_timestamp) + six.text_type(timestamp)) hash = salted_hmac(key_salt, value).hexdigest()[::2] return "%s-%s" % (ts_b36, hash)
def _make_token_with_timestamp(self, user, timestamp): """ Generate a token that cannot be used twice and that last some time. """ # IMPORTANT: user is the API param name, but in our context it is a Client model client = user # timestamp is number of days since 2001-1-1. Converted to # base 36, this gives us a 3 digit string until about 2121 ts_b36 = int_to_base36(timestamp) # By hashing on the internal state of the client and using state # that is sure to change (the cert_public_download_on will change as soon as # the certificate is downloaded), we produce a hash that will be # invalid as soon as it is used. # We limit the hash to 20 chars to keep URL short hash = salted_hmac( self.key_salt, self._make_hash_value(client, timestamp)).hexdigest()[::2] return "%s-%s" % (ts_b36, hash)
def _make_token_with_timestamp(self, user, timestamp): # timestamp is number of days since 2001-1-1. Converted to # base 36, this gives us a 3 digit string until about 2121 ts_b36 = int_to_base36(timestamp) # By hashing on the internal state of the user and using state # that is sure to change (the password salt will change as soon as # the password is set, at least for current Django auth, and # last_login will also change), we produce a hash that will be # invalid as soon as it is used. # We limit the hash to 20 chars to keep URL short key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" # Ensure results are consistent across DB backends login_timestamp = user.last_login.replace(microsecond=0, tzinfo=None) value = (six.text_type(user.pk) + user.password + six.text_type(login_timestamp) + six.text_type(timestamp)) hash = salted_hmac(key_salt, value).hexdigest()[::2] return "%s-%s" % (ts_b36, hash)
def _make_token_with_timestamp(self, user, timestamp): # timestamp is number of days since 2001-1-1. Converted to # base 36, this gives us a 3 digit string until about 2121 ts_b36 = int_to_base36(timestamp) # By hashing on the internal state of the user and using state # that is sure to change (the password salt will change as soon as # the password is set, at least for current Django auth, and # last_login will also change), we produce a hash that will be # invalid as soon as it is used. # We limit the hash to 20 chars to keep URL short key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" # Ensure results are consistent across DB backends if user.date_updated: login_timestamp = user.date_updated.replace(microsecond=0, tzinfo=None) elif user.last_login: login_timestamp = user.last_login.replace(microsecond=0, tzinfo=None) else: login_timestamp = user.date_joined.replace(microsecond=0, tzinfo=None) value = (six.text_type(user.pk) + user.password + six.text_type(login_timestamp) + six.text_type(timestamp)) hash = salted_hmac(key_salt, value).hexdigest()[::2] return "%s-%s" % (ts_b36, hash)
def send_email(self, email): protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") current_site = get_current_site(self.request) for user in User.objects.filter(email__iexact=email): uid = int_to_base36(user.id) token = self.make_token(user) password_reset_url = "{0}://{1}{2}".format( protocol, current_site.domain, reverse("account_password_reset_token", kwargs=dict(uidb36=uid, token=token)) ) ctx = { "user": user, "current_site": current_site, "password_reset_url": password_reset_url, } subject = render_to_string("account/email/password_reset_subject.txt", ctx) subject = "".join(subject.splitlines()) message = render_to_string("account/email/password_reset.txt", ctx) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email])
def test_make_token(self): token = token_generator.make_token(self.project) id_b36 = int_to_base36(self.project.pk) expected = salted_hmac( token_generator.key_salt, token_generator._make_hash_value(self.project), secret=token_generator.secret, ).hexdigest() self.assertEqual(token, '-'.join([id_b36, expected]))
def make_token(self, project): """ Return a token that can be used to upload archives throug the API. After hash is calculated, we concat the project id in order to simplify the token check, otherwise we would have to go through all the objects in the database. """ project_b36 = int_to_base36(project.pk) digest = salted_hmac( self.key_salt, self._make_hash_value(project), secret=self.secret, ).hexdigest() return "{project}-{digest}".format( project=project_b36, digest=digest)
def int_to_base(user_id, base): if base == 36: from django.utils.http import int_to_base36 return int_to_base36(user_id) elif base == 64: # Logic extracted from django.contrib.auth.forms.PasswordResetForm in Django 1.6+ from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode return urlsafe_base64_encode(force_bytes(user_id))
def user_pk_to_url_str(user): """ This should return a string. """ User = get_user_model() if (hasattr(models, 'UUIDField') and issubclass( type(User._meta.pk), models.UUIDField)): if isinstance(user.pk, six.string_types): return user.pk return user.pk.hex ret = user.pk if isinstance(ret, six.integer_types): ret = int_to_base36(user.pk) return str(ret)
def build_cache_key(pk, timestamp): return int_to_base36(pk)+'_'+int_to_base36(timestamp)
def last_update_cache_key(self): last_update = self.created if self.last_update_id is None else self.last_update.datetime return int_to_base36(self.last_update_id or 0)+'_'+int_to_base36(int(make_naive(last_update).timestamp()))
def last_change_cache_key(self): last_change = self.created if self.last_change_id is None else self.last_change.datetime return int_to_base36(self.last_change_id or 0)+'_'+int_to_base36(int(make_naive(last_change).timestamp()))
def test_confirm_valid_base36(self): # Remove in Django 1.7 url, path = self._test_confirm_start() path_parts = path.strip("/").split("/") # construct an old style (base36) URL by converting the base64 ID path_parts[1] = int_to_base36(int(urlsafe_base64_decode(path_parts[1]))) response = self.client.get("/%s/%s-%s/" % tuple(path_parts)) # redirect to a 'complete' page: self.assertContains(response, "Please enter your new password")
def save(self, **kwargs): email = self.cleaned_data["email"] token_generator = kwargs.get("token_generator", default_token_generator) for user in User.objects.filter(email__iexact=email): temp_key = token_generator.make_token(user) # save it to the password reset model password_reset = PasswordReset(user=user, temp_key=temp_key) password_reset.save() current_site = Site.objects.get_current() domain = unicode(current_site.domain) # send the password reset email subject = _("Password reset email sent") message = render_to_string("account/password_reset_key_message.txt", { "user": user, "uid": int_to_base36(user.id), "temp_key": temp_key, "domain": domain, }) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email]) return self.cleaned_data["email"]
def user_pk_to_url_str(user): """ This should return a string. """ User = get_user_model() if (hasattr(models, 'UUIDField') and issubclass(type(User._meta.pk), models.UUIDField)): if isinstance(user.pk, six.string_types): return user.pk return user.pk.hex ret = user.pk if isinstance(ret, six.integer_types): ret = int_to_base36(user.pk) return str(ret)
def decode(code, *, max_age): """ Decodes the code from the registration link and returns a tuple consisting of the verified email address and the associated user instance or ``None`` if no user was passed to ``send_registration_mail`` Pass the maximum age in seconds of the link as ``max_age``. This method raises ``ValidationError`` exceptions containing an translated message what went wrong suitable for presenting directly to the user. """ try: data = get_signer().unsign(code, max_age=max_age) except signing.SignatureExpired: raise ValidationError(_( 'The link is expired. Please request another registration link.' ), code='email_registration_expired') except signing.BadSignature: raise ValidationError(_( 'Unable to verify the signature. Please request a new' ' registration link.' ), code='email_registration_signature') parts = data.split(':') if len(parts) != 3: raise ValidationError(_( 'Something went wrong while decoding the' ' registration request. Please try again.' ), code='email_registration_broken') email, uid, timestamp = parts if uid and timestamp: try: user = User.objects.get(pk=uid) except (User.DoesNotExist, TypeError, ValueError): raise ValidationError(_( 'Something went wrong while decoding the' ' registration request. Please try again.' ), code='email_registration_invalid_uid') if timestamp != int_to_base36(get_last_login_timestamp(user)): raise ValidationError(_( 'The link has already been used.' ), code='email_registration_used') else: user = None return email, user