我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.http.urlsafe_base64_decode()。
def get(self, request, **kwargs): """uid?token?????????.""" token = kwargs.get('token') uidb64 = kwargs.get('uidb64') try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user and user.is_active: if default_token_generator.check_token(user, token): user.is_active = True user.save() return super().get(request, **kwargs) raise Http404
def get(self, request, *args, **kwargs): try: uid = force_text(urlsafe_base64_decode(kwargs['uid64'])) user = UserModel.objects.get(pk=uid) except Exception as e: logger.info(e) user = None if user is not None and account_activation_token.check_token(user, kwargs['token']): email_address = user.emailaddress_set.first() email_address.verified = True email_address.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) # return redirect('home') return HttpResponse('Thank you for your email confirmation. Now you can login your account.') return HttpResponse('Activation link is invalid!')
def verify_step2(request, uidb64, token): bytes_uid = urlsafe_base64_decode(uidb64) try: uid = int(bytes_uid) except ValueError: raise SuspiciousOperation('verify_step2 received invalid base64 user ID: {}'.format( bytes_uid)) if uid != request.user.id: raise PermissionDenied('UID mismatch - user is {}, request was for {}'.format( request.user.id, uid)) user = get_object_or_404(models.User, pk=uid) if not verify_token_generator.check_token(user, token): raise Http404('token invalid') if not user.email_verified: user.email_verified = True user.save() messages.success(request, _('Your email has been verified successfully. Thanks!')) else: messages.info(request, _('Your email address has already been verified.')) return redirect('index')
def activate(request, uid, token): try: uid = force_text(urlsafe_base64_decode(uid)) user = User.objects.get(pk=uid) if request.user != user: messages.warning(request, "User email can be verified") return redirect('root') except (TypeError, ValueError, OverflowError, User.DoesNotExist): messages.warning(request, "User email can be verified") return redirect('root') if account_activation_token.check_token(user, token): messages.success(request, "Email verified!") user.email_verified = True user.save() auth.login(request, user) else: messages.error(request, "This email verification url has expired") return redirect('root')
def password_reset_confirm(request, uid, token): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ try: uid = force_text(urlsafe_base64_decode(uid)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): return TemplateResponse(request, 'password_reset_confirm.html', {'validlink': False}) if password_reset_token.check_token(user, token): if request.method == 'POST': form = SetPasswordForm(request.POST) if form.is_valid(): form.save(user) return HttpResponseRedirect(reverse('password_reset_complete')) form = SetPasswordForm() else: return TemplateResponse(request, 'password_reset_confirm.html', {'validlink': False}) return TemplateResponse(request, 'password_reset_confirm.html', {'validlink': True, 'form': form})
def get(self, request, uidb64=None, token=None): if request.user.is_authenticated(): return redirect(get_redirect_url(request)) # Seo seo = Seo() seo.title = _('Password reset') seo.save(request) try: uid = urlsafe_base64_decode(uidb64) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, ObjectDoesNotExist): user = None if user is None or not default_token_generator.check_token(user, token): return redirect(resolve_url(settings.RESET_PASSWORD_REDIRECT_URL)) return password_reset_confirm(request, uidb64=uidb64, token=token, template_name='users/reset_confirm.html', set_password_form=SetPasswordForm, post_reset_redirect='users:reset_complete', )
def get(self, request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_confirmation_token.check_token(user, token): ## set the Person to being approved person = Person.objects.get(email_address=user.email) person.approved_by_user = True person.save() # user.is_active = True # user.save() # login(request, user) # return redirect('home') return HttpResponse('Thank you for confirming your source profile.') # Now you can view the live entry {}.').format(live_url) else: return HttpResponse('Confirmation link is invalid!') ## see which token the user matches return render(request, 'confirmation.html', context)
def validate_signed_token(uid, token, require_token=True): """ Validates a signed token and uid and returns the user who owns it. :param uid: The uid of the request :param token: The signed token of the request if one exists :param require_token: Whether or not there is a signed token, the token parameter is ignored if False :return: The user who's token it is, if one exists, None otherwise """ user_model = get_user_model() try: uid = force_text(urlsafe_base64_decode(uid)) user = user_model.objects.get(pk=uid) if require_token: if user is not None and default_token_generator.check_token(user, token): return user else: return user except (TypeError, ValueError, OverflowError, user_model.DoesNotExist): pass return None
def password_reset_confirm(request, initial=False, extra_context={}, **kwargs): extra_context.update({ 'password_policy': password_validators_help_text_html()}) response = auth_views.password_reset_confirm( request, extra_context=extra_context, **kwargs) if isinstance( response, HttpResponseRedirect) and response.status_code == 302: # Send password change confirmation email try: uid = force_text(urlsafe_base64_decode(kwargs['uidb64'])) user = MunchUser.objects.get(pk=uid) if initial: user.send_invitation_complete_email() else: user.send_password_reset_complete_email() except (TypeError, ValueError, OverflowError, MunchUser.DoesNotExist): pass return response
def post(self, request, format=None): UserModel = get_user_model() uidb64 = request.data['uid'] token = request.data['token'] new_password = request.data['new_password'] token_generator = MunchUserTokenGenerator() try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = MunchUser.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if token_generator.check_token(user, token): user.set_password(new_password) return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_401_UNAUTHORIZED)
def activation(request, uuid, token): user_model = get_user_model() token_manager = TokenManager() new_user_is_actived = False try: uid = urlsafe_base64_decode(uuid) user = user_model._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, user_model.DoesNotExist): user = None if user and token_manager.validate(user, token): user.is_active = True user.save() new_user_is_actived = True context = { 'new_user_is_actived': new_user_is_actived } return render(request, 'accounts/activation.html', context)
def confirm_new_email(request, uidb64): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None: user.email = user.profile.unconfirmed_email user.profile.unconfirmed_email = None user.save() user.profile.save() messages.success(request, _('Your new email was successfully confirmed!')) else: return HttpResponse('Email activation link is invalid!') return redirect('view_profile')
def check_token(uidb64, token): ''' Checks that the user token is correct. :param uidb: :param token: :return: True on success, False in all other situations ''' if uidb64 is not None and token is not None: try: uid = int(urlsafe_base64_decode(uidb64)) except ValueError as e: logger.info("Could not decode UID: {0}".format(e)) return False user = User.objects.get(pk=uid) if user is not None and default_token_generator.check_token(user, token): return True return False
def save(self): super(TungaPasswordResetConfirmSerializer, self).save() try: uid = force_text(urlsafe_base64_decode(self.initial_data.get('uid', None))) user = get_user_model().objects.get(pk=uid) email_address = EmailAddress.objects.add_email( None, user, user.email ) email_address.verified = True email_address.primary = True email_address.save() request = self.context.get("request", None) if request: user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) except: pass
def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) return redirect('post_detail') else: return render(request, 'blog/post_list.html')
def change_email_step1done(request): signer = Signer('accounts.views.change-email') email_signed = urlsafe_base64_decode(request.GET.get('e', '')) try: email = signer.unsign(email_signed) except BadSignature: raise SuspiciousOperation('change_step1done received invalid signed email {}'.format(signer)) return render(request, 'accounts/change_email/step1done.html', {'email': email})
def change_email_step2(request, uidb64, token, new_email): bytes_uid = urlsafe_base64_decode(uidb64) try: uid = int(bytes_uid) except ValueError: raise SuspiciousOperation('change_email_step2 received invalid base64 user ID: {}'.format( bytes_uid)) if uid != request.user.id: raise PermissionDenied('UID mismatch - user is {}, request was for {}'.format( request.user.id, uid)) user = get_object_or_404(models.User, pk=uid) old_email = user.email new_email = urlsafe_base64_decode(new_email).decode('utf8') user.email = new_email if not verify_token_generator.check_token(user, token): raise Http404('token invalid') if old_email == new_email: messages.info(request, _('Your email address has already been changed.')) else: was_verified = user.email_verified user.email_verified = True user.email = new_email user.save() if was_verified: _send_email_changed_email(request, user, old_email) messages.success(request, _('Your email address has been changed successfully.')) return redirect('index')
def forgot_step1done(request): if request.user.is_authenticated(): return redirect(_login_redirect_url(request)) signer = Signer('accounts.views.forgot-email') email_signed = urlsafe_base64_decode(request.GET.get('e', '')) try: email = signer.unsign(email_signed) except BadSignature: raise SuspiciousOperation('forgot_step1done received invalid signed email {}'.format(signer)) return render(request, 'accounts/forgot/step1done.html', {'email': email})
def forgot_step2(request, uidb64, token): if request.user.is_authenticated(): return redirect(_login_redirect_url(request)) bytes_uid = urlsafe_base64_decode(uidb64) try: uid = int(bytes_uid) except ValueError: raise SuspiciousOperation('forgot_step2 received invalid base64 user ID: {}'.format( bytes_uid)) user = get_object_or_404(models.User, pk=uid) if not forgot_token_generator.check_token(user, token): raise Http404('token invalid') form = forms.ForgotPasswordSetForm(user=user) if request.method == 'POST': form = forms.ForgotPasswordSetForm(request.POST, user=user) if form.is_valid(): user.set_password(form.cleaned_data['password']) user.save() messages.success( request, _('Your password has been reset, ' 'and you have been logged in.')) return _log_user_in(request, user) return render( request, 'accounts/forgot/step2.html', {'form': form, 'user': user})
def get_user(self, uidb64): try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None return user
def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!')
def dispatch(self, request, invite_idb64, token): invite_id = force_text(urlsafe_base64_decode(invite_idb64)) invite = UserInvite.objects.filter(id=invite_id, token=token, is_used=False) if invite: return super(ActivateRole, self).dispatch(request, invite[0], invite_idb64, token) return HttpResponseRedirect(reverse('login'))
def get_user_from_uid(uid): if uid is None: raise ValidationError(_("uid is required!")) try: uid = urlsafe_base64_decode(uid) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): raise ValidationError(_(u"Invalid uid %s") % uid) return user
def get_identifier(self): """ Gets the instance, if token is valid. :param klass: the class (must be model.Model instance) May throw DoesNotExist :returns: instance if signature is ok, None else. """ try: payload = signing.Signer().unsign(self.token) except signing.BadSignature: return None else: d = json.loads(force_text(urlsafe_base64_decode(payload))) return d.get('identifier')
def forgot_passwd_check(request, uidb64=None, token=None): """ Page that checks the hash in a password reset link, generates a new password which is send via SMS to the user. """ assert uidb64 is not None and token is not None try: user = User.objects.get(id=urlsafe_base64_decode(uidb64)) profile = user.userprofile except (ValueError, OverflowError, User.DoesNotExist): profile = None if profile and profile.email_token == token: # Email address is verified, we cant compare to token as register token is different to reset one. profile.email_token = '' profile.email_verified = True # This may look strange - setting the phone_verified before the user logs in. It is not :) We are sending new # password to phone number in profile, after the user logs in we would set phone_verified to True anyway. profile.phone_verified = True profile.save() return password_reset_confirm( request, uidb64=uidb64, token=token, template_name='gui/accounts/forgot_check.html', set_password_form=PasswordResetForm, post_reset_redirect=reverse('forgot_check_done'), current_app='gui')
def get_user(self, uidb64): UserModel = get_user_model() try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None return user
def post(self, request, uidb64=None, token=None, *args, **kwargs): userModel = get_user_model() form = self.form_class(request.POST) if uidb64 is None or token is None: form.add_error( field=None, error=u"O link usado para a troca de senha não é válido ou expirou, por favor tente enviar novamente.") return self.form_invalid(form) try: uid = urlsafe_base64_decode(uidb64) user = userModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, userModel.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): if form.is_valid(): new_password = form.cleaned_data['new_password'] new_password_confirm = form.cleaned_data[ 'new_password_confirm'] if new_password == new_password_confirm: user.set_password(new_password) user.save() messages.success(request, u"Senha trocada com sucesso") return self.form_valid(form) else: form.add_error(field=None, error=u"Senhas diferentes.") return self.form_invalid(form) else: form.add_error( field=None, error=u"Não foi possivel trocar a senha. Formulário inválido.") return self.form_invalid(form) else: form.add_error( field=None, error=u"O link usado para a troca de senha não é válido ou expirou, por favor tente enviar novamente.") return self.form_invalid(form)
def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if request.method == 'POST': user_form = UserCompletionForm(request.POST, instance=user) profile_form = ProfileCompletionForm(request.POST, instance=user.profile) if user_form.is_valid() and profile_form.is_valid(): user.is_active = True user_form.save() profile_form.save() login(request, user) return render(request, 'accounts/activation_completed.html') else: messages.error(request, _('Please correct the error below.')) else: user_form = UserCompletionForm() profile_form = ProfileCompletionForm() if user is not None and account_activation_token.check_token(user, token): pass else: return HttpResponse('Activation link is invalid!') return render(request, 'accounts/complete_registration.html', {'user_form': user_form, 'profile_form': profile_form})
def activate_organization(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if request.method == 'POST': form = OrganizationCompletionForm(request.POST, request.FILES, instance=user.profile) if form.is_valid(): user.is_active = True user.profile.is_organization = True user.profile.active = False # NGOs need manual approval by admin form.save() user.save() login(request, user) return render(request, 'accounts/activation_completed.html') else: messages.error(request, _('Please correct the error below.')) else: form = OrganizationCompletionForm() if user is not None and account_activation_token.check_token(user, token): pass else: return HttpResponse('Activation link is invalid!') return render(request, 'accounts/complete_organization_registration.html', {'form': form})
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 activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) return redirect('home') else: return render(request, 'account_activation_invalid.html')
def post(self, request, uidb64=None, token=None, *arg, **kwargs): form = self.get_form() assert uidb64 is not None and token is not None try: uid = urlsafe_base64_decode(uidb64) user = User._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): if form.is_valid(): new_password = form.cleaned_data['new_password'] user.set_password(new_password) user.save() messages.success(request, _('Password reset successfully.')) return self.form_valid(form) else: messages.error(request, _('We were not able to reset your password.')) return self.form_invalid(form) else: messages.error(request, _('The reset password link is no longer valid.')) return self.form_invalid(form)
def password_reset_confirm(request, uidb64=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ UserModel = get_user_model() assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True title = _('Enter new password') 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(user) else: validlink = False form = None title = _('Password reset unsuccessful') context = { 'form': form, 'title': title, 'validlink': validlink, } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context)
def password_reset_confirm(request, uidb64=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ warnings.warn("The password_reset_confirm() view is superseded by the " "class-based PasswordResetConfirmView().", RemovedInDjango21Warning, stacklevel=2) assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True title = _('Enter new password') 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(user) else: validlink = False form = None title = _('Password reset unsuccessful') context = { 'form': form, 'title': title, 'validlink': validlink, } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context)
def password_reset_confirm(request, uidb64=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, current_app=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ UserModel = get_user_model() assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True title = _('Enter new password') 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(user) else: validlink = False form = None title = _('Password reset unsuccessful') context = { 'form': form, 'title': title, 'validlink': validlink, } if extra_context is not None: context.update(extra_context) if current_app is not None: request.current_app = current_app return TemplateResponse(request, template_name, context)
def password_reset_confirm(request, uidb64=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ warnings.warn("The password_reset_confirm() view is superseded by the " "class-based PasswordResetConfirmView().", RemovedInDjango21Warning, stacklevel=2) UserModel = get_user_model() assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True title = _('Enter new password') 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(user) else: validlink = False form = None title = _('Password reset unsuccessful') context = { 'form': form, 'title': title, 'validlink': validlink, } if extra_context is not None: context.update(extra_context) return TemplateResponse(request, template_name, context)