Python django.contrib.auth.tokens.default_token_generator.check_token() Examples

The following are 7 code examples of django.contrib.auth.tokens.default_token_generator.check_token(). 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.contrib.auth.tokens.default_token_generator , or try the search function .
Example #1
Source File: forms.py    From pycon with MIT License 6 votes vote down vote up
def clean(self):
        cleaned_data = super().clean()

        token = cleaned_data["token"]
        userid = urlsafe_b64decode(cleaned_data["encoded_user_id"])

        user = User.objects.filter(id=userid).first()

        if not user:
            raise ValidationError({"encoded_user_id": _("Invalid user")})

        if not default_token_generator.check_token(user, token):
            raise ValidationError({"token": _("Invalid token")})

        cleaned_data["user"] = user
        return cleaned_data 
Example #2
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 #3
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 #4
Source File: password_reset_serializer.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def validate(self, attrs):
        user = get_user_from_uid(attrs.get('uid'))
        value = attrs['token']

        if not default_token_generator.check_token(user, value):
            raise ValidationError(_("Invalid token: %s") % value)

        return attrs 
Example #5
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 #6
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 #7
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)