Python django.utils.http.urlsafe_base64_decode() Examples

The following are 30 code examples of django.utils.http.urlsafe_base64_decode(). 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: schema.py    From django-graph-auth with MIT License 7 votes vote down vote up
def mutate_and_get_payload(cls, input, context, info):
        Model = UserModel

        try:
            uid = force_text(uid_decoder(input.get('id')))
            user = Model.objects.get(pk=uid)
        except (TypeError, ValueError, OverflowError, Model.DoesNotExist):
            raise Exception('uid has an invalid value')

        data = {
            'uid': input.get('id'),
            'token': input.get('token'),
            'new_password1': input.get('password'),
            'new_password2': input.get('password')
        }

        reset_form = SetPasswordForm(user=user, data=data)

        if not reset_form.is_valid():
            raise Exception("The token is not valid")

        reset_form.save()

        return ResetPassword(ok=True, user=user) 
Example #2
Source File: views.py    From django-user-management with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def initial(self, request, *args, **kwargs):
        uidb64 = kwargs['uidb64']
        uid = urlsafe_base64_decode(force_text(uidb64))

        try:
            self.user = User.objects.get(pk=uid)
        except User.DoesNotExist:
            raise exceptions.InvalidExpiredToken()

        token = kwargs['token']
        if not default_token_generator.check_token(self.user, token):
            raise exceptions.InvalidExpiredToken()

        return super(OneTimeUseAPIMixin, self).initial(
            request,
            *args,
            **kwargs
        ) 
Example #3
Source File: views.py    From iguana with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        uidb64 = kwargs['uidb64']
        token = kwargs['token']
        try:
            uid = urlsafe_base64_decode(uidb64).decode()
            user = self.model.objects.get(id=uid)
        except(TypeError, ValueError, OverflowError, self.model.DoesNotExist):
            user = None
        if user is not None and account_activation_token.check_token(user, token):
            messages.info(request, _("Thanks for registering. You are now logged in."))
            user.is_active = True
            user.save()
            login(request, user)
            return HttpResponseRedirect(reverse("landing_page:home"))
        else:
            return render(request, 'registration/invalid_activation_link.html')


# TODO reactivate as soon as the bug is fixed
# TODO BUG does it work as intended again?
# TODO BUG sends wrong url for local (development) settings example.com != localhost:port 
Example #4
Source File: views.py    From registration with MIT License 6 votes vote down vote up
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}) 
Example #5
Source File: views.py    From registration with MIT License 6 votes vote down vote up
def activate(request, uid, token):
    try:
        uid = force_text(urlsafe_base64_decode(uid))
        user = User.objects.get(pk=uid)
        if request.user.is_authenticated and request.user != user:
            messages.warning(request, "Trying to verify wrong user. Log out please!")
            return redirect('root')
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        messages.warning(request, "This user no longer exists. Please sign up again!")
        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, "Email verification url has expired. Log in so we can send it again!")
    return redirect('root') 
Example #6
Source File: serializers.py    From django-rest-auth with MIT License 6 votes vote down vote up
def validate(self, attrs):
        self._errors = {}

        # Decode the uidb64 to uid to get User object
        try:
            uid = force_text(uid_decoder(attrs['uid']))
            self.user = UserModel._default_manager.get(pk=uid)
        except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
            raise ValidationError({'uid': ['Invalid value']})

        self.custom_validation(attrs)
        # Construct SetPasswordForm instance
        self.set_password_form = self.set_password_form_class(
            user=self.user, data=attrs
        )
        if not self.set_password_form.is_valid():
            raise serializers.ValidationError(self.set_password_form.errors)
        if not default_token_generator.check_token(self.user, attrs['token']):
            raise ValidationError({'token': ['Invalid value']})

        return attrs 
Example #7
Source File: views.py    From Ouroboros with GNU General Public License v3.0 6 votes vote down vote up
def get(self, request, *_args, **kwargs):
        user = None
        try:
            uid = force_text(urlsafe_base64_decode(kwargs["uidb64"]))
            user = get_user_model().objects.get(id=int(uid))
        except (
            TypeError,
            ValueError,
            OverflowError,
            get_user_model().DoesNotExist,
        ) as e:
            print(e)
        if user is not None and email_confirmation_generator.check_token(
            user, kwargs["token"]
        ):
            user.is_active = True
            user.save()
            login(request, user)
            return redirect(reverse_lazy("status"))
        else:
            return HttpResponse("Activation link is invalid.") 
Example #8
Source File: password_reset_serializer.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #9
Source File: views.py    From openwisp-radius with GNU General Public License v3.0 5 votes vote down vote up
def validate_user(self, *args, **kwargs):
        if self.request.POST.get('uid', None):
            try:
                uid = force_text(urlsafe_base64_decode(self.request.POST['uid']))
                uid = UUID(str(uid))
                user = User.objects.get(pk=uid)
            except (User.DoesNotExist, ValueError):
                raise Http404()
            self.validate_membership(user)
            return user 
Example #10
Source File: utils.py    From django-uniauth with GNU Lesser General Public License v3.0 5 votes vote down vote up
def decode_pk(encoded_pk):
    """
    Decodes the provided base64 encoded pk into its
    original value, as a string
    """
    return force_text(urlsafe_base64_decode(encoded_pk)) 
Example #11
Source File: viste.py    From jorvik with GNU General Public License v3.0 5 votes vote down vote up
def recupera_password_conferma(request, uidb64=None, token=None,
                           template='base_recupero_password_conferma.html',
                           contesto_extra=None):
    assert uidb64 is not None and token is not None  # checked by URLconf
    try:
        # urlsafe_base64_decode() decodes to bytestring on Python 3
        uid = force_text(urlsafe_base64_decode(uidb64))
        utente = Utenza.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, Utenza.DoesNotExist):
        utente = None

    if utente is not None and default_token_generator.check_token(utente, token):
        link_valido = True
        titolo = 'Inserisci una nuova password'
        if request.method == 'POST':
            modulo = ModuloImpostaPassword(utente, request.POST)
            if modulo.is_valid():
                modulo.save()
                return HttpResponseRedirect(reverse('recupero_password_completo'))
        else:
            modulo = ModuloImpostaPassword(utente)
    else:
        link_valido = False
        modulo = None
        titolo = 'Errore nell\'impostazione della nuova password'
    contesto = {
        'modulo': modulo,
        'titolo': titolo,
        'link_valido': link_valido,
        "scadenza_token": django_settings.PASSWORD_RESET_TIMEOUT_DAYS * 24
    }
    if contesto_extra is not None:
        contesto.update(contesto_extra)

    return TemplateResponse(request, template, contesto) 
Example #12
Source File: extra_views.py    From webterminal with GNU General Public License v3.0 5 votes vote down vote up
def get_user(self):
        uidb64 = self.kwargs.get('uidb64')
        try:
            uid = urlsafe_base64_decode(uidb64)
            return self.get_queryset().get(pk=uid)
        except (TypeError, ValueError, OverflowError, User.DoesNotExist):
            return None 
Example #13
Source File: views.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_user(self, uidb64):
        """
        Given the verified uid, look up and return the
        corresponding user account if it exists, or ``None`` if it
        doesn't.
        """
        try:
            user = User.objects.get(**{
                'pk': force_str(urlsafe_base64_decode(uidb64))
            })
            return user
        except (TypeError, ValueError, OverflowError, User.DoesNotExist):
            return None 
Example #14
Source File: utils.py    From doccano with MIT License 5 votes vote down vote up
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()
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request=request, user=user,)
        return redirect('projects')
    else:
        return render(request, 'validate_mail_address_invalid.html') 
Example #15
Source File: views.py    From python2017 with MIT License 5 votes vote down vote up
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 
Example #16
Source File: views.py    From cruzz with MIT License 5 votes vote down vote up
def activate(request, uidb64, token, backend='django.contrib.auth.backends.ModelBackend'):
    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, backend='django.contrib.auth.backends.ModelBackend')
        return render(request, 'email_confirmed.html')
    else:
        return HttpResponse('Activation link is invalid!') 
Example #17
Source File: views.py    From SchoolIdolAPI with Apache License 2.0 5 votes vote down vote up
def password_reset_confirm(request, uidb64, token, template_name):
    try:
        uid = urlsafe_base64_decode(uidb64)
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    accounts_with_transfer_code = 0
    if user is not None:
        accounts_with_transfer_code = user.accounts_set.exclude(transfer_code__isnull=True).exclude(transfer_code__exact='').count()

    response = password_reset_confirm_view(request, uidb64=uidb64, token=token, extra_context={'accounts_with_transfer_code': accounts_with_transfer_code}, template_name=template_name)
    if isinstance(response, HttpResponseRedirect) and user is not None:
        accounts_with_transfer_code = user.accounts_set.all().update(transfer_code='')
    return response 
Example #18
Source File: views.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def get_user(self, uidb64):
        try:
            # urlsafe_base64_decode() decodes to bytestring
            uid = urlsafe_base64_decode(uidb64).decode()
            user = UserModel._default_manager.get(pk=uid)
        except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist, ValidationError):
            user = None
        return user 
Example #19
Source File: views.py    From AutoGrader with MIT License 5 votes vote down vote up
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.student.email_confirmed = True
        user.save()
        login(request, user)
        return redirect('home')
    else:
        return render(request, 'account/account_activation_invalid.html') 
Example #20
Source File: utils.py    From djoser with MIT License 5 votes vote down vote up
def decode_uid(pk):
    return force_text(urlsafe_base64_decode(pk)) 
Example #21
Source File: api.py    From volontulo with MIT License 5 votes vote down vote up
def password_reset_confirm(request, uidb64, token):
    """REST API reset password confirm"""
    serializer = PasswordSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    uid = force_text(urlsafe_base64_decode(uidb64))
    try:
        user = User.objects.get(pk=uid)
    except User.DoesNotExist:
        user = None
    if user is not None and default_token_generator.check_token(user, token):
        user.set_password(serializer.validated_data.get('password'))
        user.save()
    return Response({}, status=status.HTTP_201_CREATED) 
Example #22
Source File: views.py    From Collaboration-System with GNU General Public License v2.0 5 votes vote down vote up
def activate_user(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()
        auth_messages.success(request, 'Thank you for your email confirmation. You can login to your account now.')
        return redirect('login')
    else:
        return HttpResponse('Activation link is invalid!') 
Example #23
Source File: compat.py    From django-users2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def urlsafe_base64_decode(s):
        """
        Decodes a base64 encoded string, adding back any trailing equal signs that
        might have been stripped.
        """
        s = s.encode('utf-8')  # base64encode should only return ASCII.
        try:
            return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b'='))
        except (LookupError, BinasciiError) as e:
            raise ValueError(e) 
Example #24
Source File: views.py    From bioforum with MIT License 5 votes vote down vote up
def get_user(self, uidb64):
        try:
            # urlsafe_base64_decode() decodes to bytestring
            uid = urlsafe_base64_decode(uidb64).decode()
            user = UserModel._default_manager.get(pk=uid)
        except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
            user = None
        return user 
Example #25
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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')) 
Example #26
Source File: views.py    From djangoSIGE with MIT License 5 votes vote down vote up
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) 
Example #27
Source File: views.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
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) 
Example #28
Source File: auth_view.py    From eoj3 with MIT License 4 votes vote down vote up
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)  # pylint: disable=protected-access
  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()
        messages.success(request, 'Password reset complete.')
        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) 
Example #29
Source File: views.py    From bioforum with MIT License 4 votes vote down vote up
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):
    """
    Check the hash in a password reset link and present 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
        uid = urlsafe_base64_decode(uidb64).decode()
        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) 
Example #30
Source File: views.py    From esdc-ce with Apache License 2.0 4 votes vote down vote up
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
    dc1_settings = DefaultDc().settings
    sms_registration = dc1_settings.SMS_REGISTRATION_ENABLED

    if sms_registration:
        set_password_form = SMSSendPasswordResetForm
    else:
        set_password_form = PasswordResetForm

    if request.method == 'POST':
        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
            if sms_registration:
                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=set_password_form,
        post_reset_redirect=reverse('forgot_check_done'),
        current_app='gui',
        extra_context={
            'sms_registration': sms_registration,
        }
    )