def reset_pwd(request): if request.method == 'POST': form = ResetPasswordForm(request.POST.copy()) if form.is_valid(): oldpassword = form.cleaned_data["oldpassword"] user = auth.authenticate(username=request.user.username, password=oldpassword) if user == request.user: newpassword2 = form.cleaned_data["newpassword2"] user.set_password(newpassword2) user.save() return render_to_response( 'accounts/profile_reset_password.html', { 'form': form, 'sidebar_index': 'reset_pwd', 'reset_success': 'Y' }, context_instance=RequestContext(request)) error_msg = ["原密码错误"] form.errors['oldpassword'] = ErrorList(error_msg) else: form = ResetPasswordForm() return render_to_response('accounts/profile_reset_password.html', { 'form': form, 'sidebar_index': 'reset_pwd' }, context_instance=RequestContext(request))
def password_reset(request): """ A view for resetting a user's password """ if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') if email == '*****@*****.**': msg = 'The demo user cannot reset the password' messages.error(request, msg) else: user = form.get_user() # generate and set new password password = utils.user_password_reset(user) # send email utils.send_reset_password_email(request, user, password) # message msg = 'Your new password has been sent to your email address' messages.success(request, msg) else: form = ResetPasswordForm() # display information if user is already logged in if request.user.is_authenticated(): url = reverse('url_password_change') msg = '''You are currently logged in, you may instead want to <a href="%s" class="alert-link">change your password</a>.''' % url messages.info(request, msg) return render_to_response('account/password_reset.html', { 'form' : form, 'request' : request }, context_instance=RequestContext(request))
def password_reset_done(request, pk): try: user_reset_password = UserResetPassword.objects.get(user_id=pk) response = '' success_message = '' except UserResetPassword.DoesNotExist: return HttpResponse("User does not exist.") if request.method == 'POST': reset_password_form = ResetPasswordForm(data=request.POST) if reset_password_form.is_valid(): password = request.POST['new_password'] success_message = utils.reset_password(user_reset_password, password) else: # ResetPasswordForm.errors response = messages.PASSWORD_MISMATCH else: reset_password_form = ResetPasswordForm() return render( request, 'reset_password.html', { 'form': reset_password_form, 'response': response, 'success_message': success_message })
def reset_password(request): """ View for resetting a user's password """ if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): # Generate password new_password = User.objects.make_random_password( length=16, allowed_chars= 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789') user = User.objects.get( username__exact=form.cleaned_data.get('username'), email__exact=form.cleaned_data.get('email')) # Send password reset mail text = get_template('mail/reset_password.txt') html = get_template('mail/reset_password.haml') mail_context = Context({ 'username': form.cleaned_data.get('username'), 'new_password': new_password }) text_content = text.render(mail_context) html_content = html.render(mail_context) message = EmailMultiAlternatives('Element43 password reset', text_content, settings.DEFAULT_FROM_EMAIL, [form.cleaned_data.get('email')]) message.attach_alternative(html_content, "text/html") message.send() # Save new password user.set_password(new_password) user.save() # Add success message messages.info( request, 'A new password has been sent to your e-mail address.') # Redirect home return HttpResponseRedirect(reverse('home')) else: form = ResetPasswordForm() rcontext = RequestContext(request, {}) return render_to_response('reset_password.haml', {'form': form}, rcontext)
def forgot_password(request): if request.user.is_authenticated: return HttpResponse('User already logged int') if request.method == 'GET': return render(request, "forgotpassword.html", {}) elif request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): return AuthCenter.process_form(form, request) return HttpResponse('Invalid form') else: return HttpResponseServerError('Invalid method invoked %s' % request.method)
def reset_password(request, template_name, extra_context=None): if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): user = User.objects.get(username=form.cleaned_data['username']) user.set_password(form.cleaned_data['new_password']) return JSONResponse({}) else: return JSONError(utils.dump_form_errors(form)) else: form = ResetPasswordForm() return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request))
def password_reset(request): if request.method == "POST": password_reset_form = ResetPasswordForm(request.POST) if password_reset_form.is_valid(): email = password_reset_form.save() return render_to_response("account/password_reset_done.html", { "email": email, }, context_instance=RequestContext(request)) else: password_reset_form = ResetPasswordForm() return render_to_response("account/password_reset.html", { "password_reset_form": password_reset_form, }, context_instance=RequestContext(request))
def password_reset(request): if request.method == "POST": password_reset_form = ResetPasswordForm(request.POST) if password_reset_form.is_valid(): email = password_reset_form.save() return direct_to_template(request, "account/password_reset_done.html", { "email": email, }) else: password_reset_form = ResetPasswordForm() return direct_to_template(request, "account/password_reset.html", { "password_reset_form": password_reset_form, })
def reset_pwd_validate(request, key): try: if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): user = UserResetPassword.objects.get(reset_key=key).user form.save(user=user) messages.success(request, 'New password is accept, please login.') return HttpResponseRedirect("/login/") else: form = ResetPasswordForm() return {'reset_key':key, 'form': form} except (KeyError, UserResetPassword.DoesNotExist): messages.warning(request, 'The link in validation mail is wrong, please reset again.') return HttpResponseRedirect("/")
def post(self, request, *args, **kwargs): form = ResetPasswordForm(request.POST) if form.is_valid(): email_address = request.POST['email'] user = get_object_or_404(User, email=email_address) N = 8 # Logitud del password newPassword = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(N)) user.set_password(newPassword) user.save() email = 'You have asked for a new password, since you forgot your old one. Please take note of the new one, and change it, as soon as possible, for one easier for you to remember.\n\nUser: %s\nE-Mail: %s\nPassword: %s\n\n--\nThe Waving team.' % (user.name, user.email, newPassword) send_mail(settings.EMAIL_SUBJECT_PREFIX + 'Password reset', email, settings.DEFAULT_FROM_EMAIL, [email_address]) return HttpResponse() else: return HttpResponseBadRequest(json.dumps(form.errors), mimetype='application/json')
def reset_password(request, token_value): """Form that is accessible through the PasswordResetToken sent via email. It allows the user to change his forgotten password.""" if request.user.is_authenticated(): return not_logged_out_routine(request) # We need the token in every case, so get it right here token = None try: token = PasswordResetToken.objects.get(value=token_value) except PasswordResetToken.DoesNotExist: messages.error(request, 'This is not a valid URL. You may want to request a new password reset link.') return redirect('accounts:forgot_password') # Token must not be older than one hour if not token.is_usable(): messages.error(request, 'This token is more than one hour old and cannot be used anymore.') return redirect('accounts:forgot_password') # A valid and still usable token was specified in the URL. user = token.user if request.method == 'POST': form = ResetPasswordForm(user=user, data=request.POST) if form.is_valid(): # The submitted form looks perfect. user.set_password(form.cleaned_data['password1']) user.save() token.delete() messages.success(request, 'You can now log in with the new password.') return redirect('login') else: form = ResetPasswordForm(user=user) # GET-request or invalid form data, but a valid token. # Display the form, which then has been declared before. return render(request, 'accounts/reset_password.html', { 'form': form, 'token': token, })
def reset_password(request): form = ResetPasswordForm(request.POST or None) if request.method == "POST": if form.is_valid(): user = request.user user.set_password(form.cleaned_data["password"]) user.save() info = _("You have successfuly changed your password") return render_to_response('account_information.html', RequestContext(request, { "information": info, })) return render_to_response('account_reset_password.html', RequestContext(request, { 'form': form, }))
def reset_password(request): form = ResetPasswordForm(request.POST or None) if request.method == "POST": if form.is_valid(): user = request.user user.set_password(form.cleaned_data["password"]) user.save() info = _("You have successfuly changed your password") return render_to_response( 'account_information.html', RequestContext(request, { "information": info, })) return render_to_response('account_reset_password.html', RequestContext(request, { 'form': form, }))
def reset_password(request): def reset_fail(msg): messages.add_message(request, messages.ERROR, msg) return HttpResponseRedirect(reverse('main_page')) if request.method == 'GET': reset_string = request.GET.get('rid') user_id = request.GET.get('uid') if reset_string and user_id: profile = UserProfile.objects.get(pk=ObjectId(user_id)) if profile.password_reset_stub == reset_string: form = ResetPasswordForm(initial={ 'user': user_id, 'reset_string': reset_string }) return render_to_response( 'reset_password.html', locals(), context_instance=RequestContext(request)) return HttpResponseRedirect(reverse('main_page')) form = ResetPasswordForm(request.POST) if form.is_valid(): data = form.cleaned_data try: profile = UserProfile.objects.get(pk=ObjectId(data['user'])) except UserProfile.DoesNotExist: return reset_fail( "An error occurred while resetting your password.") if profile.password_reset_stub == data['reset_string']: profile.password_reset_stub = "" profile.user.set_password(data['password1']) profile.user.save() profile.save() messages.add_message(request, messages.SUCCESS, "Your password has been reset successfully.") return HttpResponseRedirect(reverse('login')) return reset_fail("An error occurred while resetting your password.") return render_to_response('reset_password.html', locals(), context_instance=RequestContext(request))
def auth_password_reset(request): """ Generic view to handle user password reset. """ if settings.REDIS_AVAILABLE: r = settings.Redis() if request.method == 'POST': form = ResetPasswordForm(request.POST) if form.is_valid(): reset_code = form.cleaned_data['reset_code'] password = form.cleaned_data['password'] if reset_code not in r: return HttpResponseRedirect(settings.HOME_URL) user_id = r[reset_code] del r[reset_code] user = GenericUser.objects.get(id=user_id) user.set_password(password) user.save() user = authenticate(email=user.email, password=password) if user: login(request, user) return HttpResponseRedirect(settings.HOME_URL) else: reset_code = request.GET.keys()[0] if reset_code not in r: return HttpResponseRedirect(settings.HOME_URL) form = ResetPasswordForm(initial={ 'reset_code': reset_code}) return {'form': form} else: raise Exception("Redis must be installed to use this feature.")
def post(self, request, *args, **kwargs): """Handles POST requests to 'account_reset_password' named route. Returns: A HttpResponse with the reset_password template. """ reset_password_form = ResetPasswordForm(request.POST, auto_id=True) if reset_password_form.is_valid(): try: # get the recovery_user from the session: recovery_user_pk = request.session['recovery_user_pk'] user = User.objects.get(pk=recovery_user_pk) # change the user's password to the new password: new_password = reset_password_form.cleaned_data.get('password') user.set_password(new_password) user.save() # inform the user through a flash message: messages.add_message( request, messages.INFO, 'Your password was changed successfully!') # redirect the user to the sign in: return redirect(reverse('signin')) except ObjectDoesNotExist: # set an error message: messages.add_message( request, messages.ERROR, 'You are not allowed to perform this action!') return HttpResponse('Action not allowed!', status_code=403) context = { 'page_title': 'Reset Password', 'reset_password_form': reset_password_form, } context.update(csrf(request)) return render(request, 'authentication/reset_password.html', context)
def reset_password( request ): def reset_fail( msg ): messages.add_message( request, messages.ERROR, msg ) return HttpResponseRedirect( reverse('main_page') ) if request.method == 'GET': reset_string = request.GET.get('rid') user_id = request.GET.get('uid') if reset_string and user_id: profile = UserProfile.objects.get(pk=ObjectId(user_id)) if profile.password_reset_stub == reset_string: form = ResetPasswordForm(initial={'user':user_id, 'reset_string':reset_string}) return render_to_response( 'reset_password.html', locals(), context_instance=RequestContext(request) ) return HttpResponseRedirect( reverse('main_page') ) form = ResetPasswordForm(request.POST) if form.is_valid(): data = form.cleaned_data try: profile = UserProfile.objects.get(pk=ObjectId(data['user'])) except UserProfile.DoesNotExist: return reset_fail("An error occurred while resetting your password.") if profile.password_reset_stub == data['reset_string']: profile.password_reset_stub = "" profile.user.set_password(data['password1']) profile.user.save() profile.save() messages.add_message( request, messages.SUCCESS, "Your password has been reset successfully." ) return HttpResponseRedirect( reverse('login') ) return reset_fail("An error occurred while resetting your password.") return render_to_response( 'reset_password.html', locals(), context_instance=RequestContext(request) )
def recover_account(request, username, key): """ Recover an account. """ # Check if the username belongs to a real user. user = get_object_or_404(User, username=username) # Check if that user has an unused, unexpired recovery key. recovery_key = get_object_or_404(AuthenticationKey, user=user, key=key, key_type='r', used=False, expires__gte=datetime.today()) # If we got this far, things are good so deal with the password change. # If there is POST data, try to process it if request.method == "POST": form = ResetPasswordForm(request.POST) # If new password is valid, change it and redirect to "changed" page. # Also record that the key has been used. if form.is_valid(): user.set_password(form.cleaned_data["new_password"]) user.save() recovery_key.used = True recovery_key.save() return render_to_response("account/password_reset.html", context_instance=RequestContext(request)) else: form = ResetPasswordForm() params = {"form": form, "username": username, "key": key} return render_to_response("account/reset_password.html", params, context_instance=RequestContext(request))
def post(self, request, *args, **kwargs): """Handles POST requests to 'account_reset_password' named route. Returns: A HttpResponse with the reset_password template. """ reset_password_form = ResetPasswordForm(request.POST, auto_id=True) if reset_password_form.is_valid(): try: # get the recovery_user from the session: recovery_user_pk = request.session['recovery_user_pk'] user = User.objects.get(pk=recovery_user_pk) # change the user's password to the new password: new_password = reset_password_form.cleaned_data.get('password') user.set_password(new_password) user.save() # inform the user through a flash message: messages.add_message( request, messages.INFO, 'Your password was changed successfully!') # redirect the user to the sign in: return redirect(reverse_lazy('login')) except ObjectDoesNotExist: # set an error message: messages.add_message( request, messages.ERROR, 'You are not allowed to perform this action!') return HttpResponse('Action not allowed!', status_code=403) context = { 'page_title': 'Reset Password', 'reset_password_form': reset_password_form, } context.update(csrf(request)) return render(request, 'reset_password.html', context)
def forgot_reset(request, code): """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() return render(request, 'accounts/forgot/reset_successful.html') else: form = ResetPasswordForm() c = { 'form': form, 'code': code, } return render(request, 'accounts/forgot/reset.html', c)
def reset_password(request, userid, token): msg = "" breadcrumb = [{"name": u"首页", "url": "/"}, {'name': u'重置密码'}] try: django_user = DjangoUser.objects.get(id=userid) if not default_token_generator.check_token(django_user, token): msg = u"参数错误!" form = ResetPasswordForm(user=django_user) return render_template("reset_password.html", request, breadcrumb=breadcrumb, msg=msg, form=form) except ObjectDoesNotExist: msg = u"该用户不存在!" form = ResetPasswordForm(user=None) return render_template("reset_password.html", request, breadcrumb=breadcrumb, msg=msg, form=form) if request.method == "POST": form = ResetPasswordForm(user=django_user, data=request.POST) if form.is_valid(): form.save() return redirect(reverse("account.views.login")) else: form = ResetPasswordForm(user=django_user) return render_template("reset_password.html", request, breadcrumb=breadcrumb, msg=msg, form=form)