Python django.contrib.auth.forms.SetPasswordForm() Examples

The following are 7 code examples of django.contrib.auth.forms.SetPasswordForm(). 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.forms , 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: crudlfap.py    From mrs with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_form_kwargs(self):

        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.object

        kwargs['disabled'] = False

        # Case when the admin manages no caisses of the edited user
        if(len(list(set(self.request.user.caisses.all())
           & set(self.object.caisses.all()))) == 0):

            # We disable every field of the SetPasswordForm
            kwargs['disabled'] = True

        return kwargs 
Example #3
Source File: views.py    From 2buntu-blog with Apache License 2.0 6 votes vote down vote up
def reset_confirm(request, key):
    """
    Complete the password reset procedure.
    """
    key = get_object_or_404(ConfirmationKey, key=key)
    if request.method == 'POST':
        form = SetPasswordForm(user=key.user, data=request.POST)
        if form.is_valid():
            form.save()
            key.delete()
            messages.info(request, "Thank you! Your password has been reset. Please log in below.")
            return redirect('accounts:login')
    else:
        form = SetPasswordForm(user=key.user)
    return render(request, 'form.html', {
        'title': 'Set Password',
        'form': form,
        'description': "Please enter a new password for your account.",
        'action': 'Continue',
    }) 
Example #4
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 #5
Source File: views.py    From canvas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def password_reset_confirm(request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html',
                           token_generator=default_token_generator, set_password_form=SetPasswordForm,
                           post_reset_redirect=None):
    """
    View that checks the hash in a password reset link and presents a
    form for entering a new password.
    """
    assert uidb36 is not None and token is not None # checked by URLconf
    if post_reset_redirect is None:
        post_reset_redirect = reverse('drawquest.apps.drawquest_auth.views.password_reset_complete')
    try:
        uid_int = base36_to_int(uidb36)
        user = User.objects.get(id=uid_int)
    except (ValueError, User.DoesNotExist):
        user = None

    ctx = {}

    if user is not None and token_generator.check_token(user, token):
        ctx['validlink'] = True
        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(None)
    else:
        ctx['validlink'] = False
        form = None
    ctx['form'] = form
    return r2r_jinja(template_name, ctx, request) 
Example #6
Source File: test_view_password_reset.py    From django-beginners-guide with MIT License 5 votes vote down vote up
def test_contains_form(self):
        form = self.response.context.get('form')
        self.assertIsInstance(form, SetPasswordForm) 
Example #7
Source File: views.py    From Bitpoll with GNU General Public License v3.0 4 votes vote down vote up
def create_account(request, info_token):
    if request.user.is_authenticated:
        return redirect('home')
    try:
        info = signing.loads(info_token, max_age=TOKEN_MAX_AGE)
    except signing.SignatureExpired:
        return TemplateResponse(request, 'registration/token_expired.html')
    except signing.BadSignature:
        return TemplateResponse(request, 'registration/token_invalid.html')

    username = info['username']

    if BitpollUser.objects.filter(username=username).exists():
        messages.warning(request, _("This User already exists"))
        return redirect('login')

    if request.method == 'POST':
        # using None as User as we do not have the user, we can not call form.save() as a result
        form = SetPasswordForm(None, request.POST)
        if form.is_valid():
            first_name = info.get('first_name')
            last_name = info.get('last_name')
            if not (first_name and last_name):
                return TemplateResponse(request, 'registration/token_invalid.html')
            email = info['email']
            user = BitpollUser(username=username,
                               email=email,
                               first_name=first_name,
                               last_name=last_name,
                               email_invitation=info['email_invitation'],
                               #  TODO: more fields?
                               )
            user.set_password(form.cleaned_data['new_password2'])
            user.save()
            user.backend = 'django.contrib.auth.backends.ModelBackend'

            login(request, user)
            return redirect('home')
    else:
        form = SetPasswordForm(None)

    return TemplateResponse(request, 'registration/create_account.html', {
        'form': form,
        'username': username
    })