def user_reset_password(request, token): if request.user.is_authenticated(): return redirect("/") form = ResetPasswordForm(request.POST or None, token=token, use_required_attribute=False) try: password_reset_auth = PasswordResetAuth.objects.get(token=token, is_expired=False) except PasswordResetAuth.DoesNotExist: raise Http404 if request.method == "POST": if form.is_valid(): user = User.objects.get(email=password_reset_auth.email) new_password = form.cleaned_data["new_password"] user.set_password(new_password) user.save() password_reset_auth.is_expired = True password_reset_auth.save() messages.add_message(request, messages.INFO, "Password has been reset successfully!") return redirect(reverse('login_user')) return render(request, "accounts/user_reset_password.html", { "form": form, })
def password_reset(request): if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): if form.data['email'] in (User.objects.values_list('email', flat=True)): user = User.objects.get(email=form.data['email']) token = hashlib.md5(str(user.id)).hexdigest() user.userprofile.token = token user.userprofile.save() reset_password_link = 'http://127.0.0.1:8000/account/password_reset/confirm/?token=' + str( token) + '&id=' + str(user.id) email_body = 'Hi, you can click the following link to reset your password\n\n' + reset_password_link send_mail( 'Reset Password', email_body, '*****@*****.**', [ form.data['email'], ], fail_silently=False, ) return redirect('/account/reset_password/done/') return HttpResponse('This email id does not exist') return HttpResponse('Enter a valid email id') form = ResetPasswordForm() args = {'form': form} return render(request, 'accounts/password_reset.html', args)
def reset_password(request): if 'email' not in request.GET and 'email' not in request.POST: reset_missing_email = True return render(request, "accounts/reset_password.html", locals()) if 'email' in request.POST and 'verification_code' not in request.GET: email_sent = True email = request.POST.get('email') try: user = User.objects.get(email__iexact=email) user.account.generate_verification_code() user.account.save() EmailService.send_verification_email(user) except: email_not_exist = True return render(request, "accounts/reset_password.html", locals()) if 'verification_code' not in request.GET: verification_code_error = True return render(request, "accounts/reset_password.html", locals()) email = request.GET.get('email') verification_code = request.GET.get('verification_code') forgot_form = ResetPasswordForm(request.POST) if _is_bad_verification(email, verification_code): bad_verification = True return render(request, "accounts/reset_password.html", locals()) if request.method != 'POST': return render(request, "accounts/reset_password.html", locals()) if not forgot_form.is_valid(): return render(request, "accounts/reset_password.html", locals()) if forgot_form.cleaned_data['password'] != forgot_form.cleaned_data[ 'confirm_password']: confirm_password_error = True return render(request, "accounts/reset_password.html", locals()) user = User.objects.get(email=forgot_form.cleaned_data['email']) user.set_password(forgot_form.cleaned_data['password']) user.save() account = user.account account.verification_code = "%s" % timezone.now() account.expire_at = timezone.now() account.save() user = authenticate(username=user.username, password=forgot_form.cleaned_data['password']) django_login(request, user) next = request.GET.get('next', '') if next == '': next = '/accounts/profile/' return HttpResponseRedirect(next)
def forgot_reset(request, code, template=None): """Allows a user who has clicked on a validation link to reset their password. """ # This doesn't make sense if the user is logged in if not request.user.is_anonymous(): return HttpResponseRedirect('/') e = get_object_or_404(EmailVerification, verification_code=code) if not e.user.is_active: raise Http404('Inactive user') if getattr(e.user, 'social_auth', None) and e.user.social_auth.all().exists(): raise Http404('User has a social auth login') if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): password1 = form.cleaned_data['password1'] e.user.set_password(password1) e.user.save() e.delete() if not template: try: template = settings.ACCOUNTS_TEMPLATES['reset_successful'] except Exception as e: print('ERROR: NO SETTING FOR ACCOUNTS_TEMPLATES["reset_successful"]') pass if not template: template = 'accounts/forgot/reset_successful.html' return render(request, template) else: form = ResetPasswordForm() c = { 'form': form, 'code': code, } if not template: try: template = settings.ACCOUNTS_TEMPLATES['reset'] except Exception as e: print('ERROR: NO SETTING FOR ACCOUNTS_TEMPLATES["reset"]') pass if not template: template = 'accounts/forgot/reset.html' return render(request, template, c)
def post(self, request, token, *args, **kwargs): try: reset_token = ResetToken.objects.get(token=token) except (ResetToken.DoesNotExist, MultipleObjectsReturned): return render(request, 'reset/reset_password.html', {'validlink': False}, status=400) form = ResetPasswordForm(request.POST) if form.is_valid(): logger.info("Reset password form for {} was valid, saving new password".format(reset_token.user.email)) form.save(user=reset_token.user) return redirect('home') return render(request, 'reset/reset_password.html', {'form': form, 'user': reset_token.user, 'validlink': True})
def reset_password(request, key): """ Allows user to reset their password if they used a valid key. """ template = 'accounts/resetpassword.html' template_context = {'key': key, 'success': False} # Trigger 404 if reset key is not valid user_profile = get_object_or_404(UserProfile, activation_key=key) # Check if user is activated. If not, automatically activate them. user = user_profile.user if not user.is_active: user.is_active = True user.save() msg = "You account has automatically been activated!" messages.add_message(request, messages.SUCCESS, msg) if user_profile.key_expires < timezone.now(): # User's reset password key has expired msg = "Sorry, but this link has expired. You will have to have a new \ link sent to your email to reset your password." messages.add_message(request, messages.ERROR, msg) else: if request.POST: # User sent request to reset password form = ResetPasswordForm(request.POST) if form.is_valid(): # Passwords matched, change user's password new_password = form.cleaned_data['password1'] user = user_profile.user user.set_password(new_password) user.save() # Set key to expired state so user cannot use same link to # reset password user_profile.key_expires = timezone.now() user_profile.save() success_msg = "Congratulations! Your password has been reset. \ You can now sign in with your new password." messages.add_message(request, messages.SUCCESS, success_msg) return redirect('/login') template_context['form'] = form request_context = RequestContext(request, template_context) return render_to_response(template, request_context)
def get(self, request, token, *args, **kwargs): try: reset_token = ResetToken.objects.get(token=token) except (ResetToken.DoesNotExist, MultipleObjectsReturned): return render(request, 'reset/reset_password.html', {'validlink': False}, status=400) if reset_token.expired(): return render(request, 'reset/reset_password.html', {'validlink': False}, status=403) form = ResetPasswordForm() return render(request, 'reset/reset_password.html', {'form': form, 'user': reset_token.user, 'validlink': True})
def reset_psw_confirm(request, tmp_psw): tmp_user = get_object_or_404(AccountTempPassword, tmp_psw = tmp_psw) delta = time.mktime(datetime.datetime.now().timetuple()) - time.mktime(tmp_user.datetime.timetuple()) if delta > 60 * 60: tmp_user.delete() raise Http404("临时密码过期") if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): password = form.cleaned_data['password'] tmp_user.user.set_password(password) tmp_user.user.save() tmp_user.delete() return render_to_response('accounts/reset_psw_done.html', {}) else: return TemplateResponse(request, 'accounts/reset_psw_confirm.html', {'form': form}) form = ResetPasswordForm() return TemplateResponse(request, 'accounts/reset_psw_confirm.html', {'form': form})