我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用django.utils.http.urlsafe_base64_encode()。
def test_send_set_password_email(staff_user): site = Site.objects.get_current() ctx = {'protocol': 'http', 'domain': site.domain, 'site_name': site.name, 'uid': urlsafe_base64_encode(force_bytes(staff_user.pk)), 'token': default_token_generator.make_token(staff_user)} send_templated_mail(template_name='dashboard/staff/set_password', from_email=DEFAULT_FROM_EMAIL, recipient_list=[staff_user.email], context=ctx) assert len(mail.outbox) == 1 generated_link = ('http://%s/account/password/reset/%s/%s/' % (ctx['domain'], ctx['uid'].decode('utf-8'), ctx['token'])) sended_message = mail.outbox[0].body assert generated_link in sended_message
def forgot(request): if request.user.is_authenticated(): return redirect(_login_redirect_url(request)) form = forms.ForgotPasswordForm() if request.method == 'POST': form = forms.ForgotPasswordForm(request.POST) if form.is_valid(): try: user = models.User.objects.get(email__iexact=form.cleaned_data['email']) if not user.has_usable_password(): form.add_error( 'email', _('That user does not use a password to log in, and therefore their password cannot be reset. ' 'Did you sign up with a Google account?')) user = None except models.User.DoesNotExist: form.add_error('email', _('Sorry, there is no user with that email address.')) user = None if user: _send_forgot_email(request, user) signer = Signer('accounts.views.forgot-email') email_signed = urlsafe_base64_encode(signer.sign(user.email.encode('utf8')).encode('utf8')) return redirect(reverse('accounts:forgot-sent') + '?e=' + email_signed.decode('utf8')) return render(request, 'accounts/forgot/step1.html', {'form': form})
def send_reset_password_email(request, user): from_email = settings.DEFAULT_FROM_EMAIL current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain token_generator = default_token_generator use_https = request.is_secure() context = { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', } subject = loader.render_to_string('registration/password_reset_subject.txt', context) subject = ''.join(subject.splitlines()) body = loader.render_to_string('registration/password_reset_email.html', context) email_message = EmailMultiAlternatives(subject, body, from_email, [user.email]) email_message.send()
def save(self, *args, **kwargs): """ Generates a one-use only link for resetting password and sends to the Copy of Django's implementation, changed to use our own email-sending. """ UserModel = get_user_model() email = self.cleaned_data["email"] active_users = UserModel.objects.filter(email__iexact=email, is_active=True) for user in active_users: # Make sure that no email is sent to a user that actually has # a password marked as unusable if not user.has_usable_password(): continue uid = urlsafe_base64_encode(force_bytes(user.pk)) token = default_token_generator.make_token(user) send_password_reset(user, uid, token)
def test_reset_user_password(self): # set user.last_login, ensures we get same/valid token # https://code.djangoproject.com/ticket/10265 self.user.last_login = now() self.user.save() token = default_token_generator.make_token(self.user) new_password = "bobbob1" data = {'token': token, 'new_password': new_password} # missing uid, should fail request = self.factory.post('/', data=data) response = self.view(request) self.assertEqual(response.status_code, 400) data['uid'] = urlsafe_base64_encode(force_bytes(self.user.pk)) # with uid, should be successful request = self.factory.post('/', data=data) response = self.view(request) self.assertEqual(response.status_code, 204) user = User.objects.get(email=self.user.email) self.assertTrue(user.check_password(new_password)) request = self.factory.post('/', data=data) response = self.view(request) self.assertEqual(response.status_code, 400)
def get_password_reset_email(user, reset_url, subject_template_name='registration/password_reset_subject.txt', # noqa email_template_name='api_password_reset_email.html', # noqa token_generator=default_token_generator): """Creates the subject and email body for password reset email.""" result = urlparse(reset_url) site_name = domain = result.hostname c = { 'email': user.email, 'domain': domain, 'path': result.path, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'username': user.username, 'encoded_username': urlsafe_base64_encode(user.username), 'token': token_generator.make_token(user), 'protocol': result.scheme if result.scheme != '' else 'http', } subject = loader.render_to_string(subject_template_name, c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) email = loader.render_to_string(email_template_name, c) return subject, email
def register(request): user_pk = None if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = get_user_model().objects.create_user( email=form.cleaned_data['email'], password=form.cleaned_data['password1'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], request=request ) user.save() user_pk = urlsafe_base64_encode(force_bytes(user.pk)) form = None return redirect(reverse('mhacks-thanks-registering')) elif request.method == 'GET': form = RegisterForm() else: return HttpResponseNotAllowed(permitted_methods=['POST', 'GET']) return render(request, 'register.html', {'form': form, 'user_pk': user_pk})
def send_verification_email(user, request): token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)) relative_confirmation_url = reverse( 'mhacks-validate', kwargs={'uid': uid, 'token': token} ) email_vars = { 'confirmation_url': _get_absolute_url(request, relative_confirmation_url), 'FIRST_NAME': user.first_name } send_mandrill_mail( 'confirmation_instructions', 'Confirm Your Email for MHacks', user.email, email_vars )
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, **kwargs): # Complete override, because we have to use our sendmail() for user in self.users_cache: # Update verification token profile = user.userprofile profile.email_token = token_generator.make_token(user) profile.save() sendmail(user, subject_template_name, email_template_name, extra_context={ 'user': user, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': profile.email_token, 'protocol': use_https and 'https' or 'http', })
def signup(request): if request.user.is_authenticated(): return redirect('view_profile') else: if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your account on Janani Care.' message = render_to_string('accounts/activation_email.html', { 'user':user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) toemail = form.cleaned_data.get('email') email = EmailMessage(subject, message, to=[toemail]) email.send() return render(request, 'accounts/activation_pending.html') else: form = SignupForm() return render(request, 'accounts/signup.html', {'form': form})
def organization_signup(request): if request.user.is_authenticated(): return redirect('view_profile') else: if request.method == 'POST': form = OrganizationSignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your organization account on Janani Care.' message = render_to_string('accounts/organization_activation_email.html', { 'user':user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) toemail = form.cleaned_data.get('email') email = EmailMessage(subject, message, to=[toemail]) email.send() return render(request, 'accounts/activation_pending.html') else: form = OrganizationSignupForm() return render(request, 'accounts/organization_signup.html', {'form': form})
def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: form = SignUpForm() return render(request, 'signup.html', {'form': form})
def post(self, *args, **kwargs): product_delete_pk = kwargs.get('pk', None) product_pk = kwargs.get('tpk', None) if product_pk and product_delete_pk: product_delete = ProductFinal.objects.filter(pk=product_delete_pk).first() product = ProductFinal.objects.filter(pk=product_pk).first() if product and product_delete: product.related.remove(product_delete) return redirect(reverse_lazy("status", kwargs={'status': 'accept', 'answer': urlsafe_base64_encode(json.dumps({'__pk__': None, '__str__': 'OK'}))})) # ------- sublista de accesorios productos -------
def post(self, *args, **kwargs): product_delete_pk = kwargs.get('pk', None) product_pk = kwargs.get('tpk', None) if product_pk and product_delete_pk: product_delete = ProductFinal.objects.filter(pk=product_delete_pk).first() product = ProductFinal.objects.filter(pk=product_pk).first() if product and product_delete: product.related_accesory.remove(product_delete) return redirect(reverse_lazy("status", kwargs={'status': 'accept', 'answer': urlsafe_base64_encode(json.dumps({'__pk__': None, '__str__': 'OK'}))})) # ###########################################
def form_valid(self, form): """??????????????.""" user = form.save() current_site = get_current_site(self.request) domain = current_site.domain subject_template = get_template( 'easy_regist/mailtemplate/new/subject.txt') message_template = get_template( 'easy_regist/mailtemplate/new/message.txt') context = { 'protocol': 'https' if self.request.is_secure() else 'http', 'domain': domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), 'user': user, } subject = subject_template.render(context) message = message_template.render(context) from_email = settings.EMAIL_HOST_USER to = [user.email] send_mail(subject, message, from_email, to) return super().form_valid(form)
def active_email(request, user): message = render_to_string('email/active_email.txt', { 'user': user, 'domain': request.get_host(), 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) subject = 'Activate your blog account.' to_email = user.email send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list=[to_email])
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None, extra_email_context=None): """ Generates a one-use only link for resetting password and sends to the user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override context = { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', } if extra_email_context is not None: context.update(extra_email_context) self.send_mail(subject_template_name, email_template_name, context, from_email, user.email, html_email_template_name=html_email_template_name)
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None, extra_email_context=None): """ Generates a one-use only link for resetting password and sends to the user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override context = { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', } if extra_email_context is not None: context.update(extra_email_context) self.send_mail( subject_template_name, email_template_name, context, from_email, user.email, html_email_template_name=html_email_template_name, )
def get_context_data(self): context = super(PasswordResetEmail, self).get_context_data() if not self.site_name or self.domain: current_site = Site.objects.get_current() self.site_name = current_site.name self.domain = current_site.domain protocol = 'https' if self.use_https else 'http' uid = urlsafe_base64_encode(force_bytes(self.user.pk)) token = self.token_generator.make_token(self.user) context.update({ 'full_reset_url': '{}://{}{}'.format( protocol, self.domain, reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token}) ), 'email': self.user.email, 'domain': self.domain, 'site_name': self.site_name, 'uid': uid, 'user': self.user, 'token': token, 'protocol': protocol, 'template_name': self.email_template_name, 'html_template_name': self.html_email_template_name, }) if self.extra_email_context is not None: context.update(self.extra_email_context) return context
def send_set_password_email(staff): site = Site.objects.get_current() ctx = {'protocol': 'http', 'domain': site.domain, 'site_name': site.name, 'uid': urlsafe_base64_encode(force_bytes(staff.pk)), 'token': default_token_generator.make_token(staff)} send_templated_mail( template_name='dashboard/staff/set_password', from_email=DEFAULT_FROM_EMAIL, recipient_list=[staff.email], context=ctx)
def change_email(request): if request.method == 'POST': form = forms.ChangeEmailForm(request.POST, user=request.user) else: form = forms.ChangeEmailForm(user=request.user) if request.method == 'POST' and form.is_valid(): new_email = form.cleaned_data['new_email'] _send_change_email(request, request.user, new_email) signer = Signer('accounts.views.change-email') email_signed = urlsafe_base64_encode(signer.sign(new_email.encode('utf8')).encode('utf8')) return redirect(reverse('accounts:change-email-sent') + '?e=' + email_signed.decode('utf8')) return render(request, 'accounts/change_email/step1.html', {'form': form})
def path(self, user, token, uidb64=None, new_email=None): return django.shortcuts.reverse('accounts:change-email-step2', kwargs={ 'uidb64': uidb64 or urlsafe_base64_encode(force_bytes(user.id)), 'token': token, 'new_email': new_email or urlsafe_base64_encode(force_bytes(user.email))})
def path(self, e=None): path = django.shortcuts.reverse('accounts:forgot-sent') if e: path += '?e=' + urlsafe_base64_encode(e.encode('utf8')).decode('utf8') return path
def path(self, user, token, uidb64=None): return django.shortcuts.reverse('accounts:verify-step2', kwargs={ 'uidb64': uidb64 or urlsafe_base64_encode(force_bytes(user.id)), 'token': token})
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None, extra_email_context=None): """ Generates a one-use only link for resetting password and sends to the user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override context = { 'email': email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', } if extra_email_context is not None: context.update(extra_email_context) self.send_mail( subject_template_name, email_template_name, context, from_email, email, html_email_template_name=html_email_template_name, )
def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) if form.cleaned_data['password'] != form.cleaned_data['confirm_password']: form.add_error("confirm_password", "Passwords do not match") return render(request, "account/signup.html", {"form": form}) user.set_password(form.cleaned_data["password"]) user.is_active = False user.save() current_site = get_current_site(request) message = render_to_string("account/activate_email.html", { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user) }) mail_subject = "Activate your Quora account" to_email = form.cleaned_data['email'] email = EmailMessage(mail_subject, message, to=[to_email]) email.send() profile = Profile(user=user) profile.save() return HttpResponse("Please activate your account with e-mail") else: return render(request, "account/signup.html", {"form": form})
def generate_verify_email(user): token = account_activation_token.make_token(user) uuid = urlsafe_base64_encode(force_bytes(user.pk)) activate_url = 'http://' + settings.HACKATHON_DOMAIN + \ reverse('activate', kwargs={'uid': uuid, 'token': token}) return create_verify_email(user, activate_url)
def generate_pw_reset_email(user, request): token = password_reset_token.make_token(user) uuid = urlsafe_base64_encode(force_bytes(user.pk)) reset_url = r_reverse('password_reset_confirm', kwargs={'uid': uuid, 'token': token}, request=request) return create_password_reset_email(user, reset_url)
def _get_confirmation_url(self): uidb64 = urlsafe_base64_encode( force_bytes(self.view.request.user.pk)).decode("utf-8") token = self.token_generator.make_token(self.view.request.user) return reverse( self.view.request.resolver_match.view_name, kwargs={ 'uuid': self.view.report.uuid, 'uidb64': uidb64, 'token': token, }, )
def save(self): """ Generates a one-use only link for resetting password and sends to the user. """ email = self.cleaned_data["email"] for user in self.get_users(email): # For each user, we generate a token uid = urlsafe_base64_encode(force_bytes(user.pk)) token = PasswordResetTokenGenerator().make_token(user) # We make the reset URL to be sent by mail reset_url = settings.PORTAILVA_APP['site']['url'] + reverse('member-reset-password-confirm', kwargs={ 'uidb64': uid, 'token': token }) # Then we send the mail context = { 'reset_url': reset_url } send_mail( template_html_name='mail/member/reset_password.html', template_text_name='mail/member/reset_password.text', context=context, subject="Réinitialisation du mot de passe", to=user.email )
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 save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name=None): """ Generates a one-use only link for resetting password and sends to the user. """ email = self.cleaned_data["email"] for user in self.get_users(email): if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override context = { 'email': user.email, 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', } self.send_mail(subject_template_name, email_template_name, context, from_email, user.email, html_email_template_name=html_email_template_name)
def get_absolute_url(self): return reverse('fieldsight:activate-role', kwargs={'invite_idb64': urlsafe_base64_encode(force_bytes(self.pk)), 'token':self.token,})
def test_get_password_reset_email(self): """Test base64 username is included in reset email.""" subject, email = get_password_reset_email(self.user, 'https://ona.io') self.assertIn(urlsafe_base64_encode(self.user.username), email, "Username is included in reset email.")
def confirm_login_allowed(self, user): if not user.email_verified: error = forms.ValidationError('Email not verified.', code='unverified') error.user_pk = urlsafe_base64_encode(force_bytes(user.pk)) raise error if not user.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', )
def send_password_reset_email(user, request): token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)) update_password_url = reverse( 'mhacks-update_password', kwargs={'uid': uid, 'token': token} ) send_mandrill_mail( 'change_password', 'Reset Your MHacks Password', user.email, email_vars={ 'update_password_url': _get_absolute_url(request, update_password_url) } )