def resetpassword(): form = ResetPasswordForm() if request.method == 'GET': return render_template('modify.html', form=form) else: if form.validate_on_submit(): with g.db as cur: sql2 = 'select * from usertable where user_id="{0}" and user_password="******"'.format( form.user_id.data, form.user_password.data) cur.execute(sql2) infos = [dict(id=row[0]) for row in cur.fetchall()] if infos == []: flash('Invalid!') else: with g.db as cur: sql = """update usertable set user_password= '******' where user_id='{1}' """.format(form.user_newpassword.data, form.user_id.data) cur.execute(sql) flash('You have resetpassword!') else: flash(form.errors) return redirect(url_for('show_todo_list'))
def reset_password(): form = ResetPasswordForm(request.form) if request.method == "POST" and form.validate(): token = form.token.data s = Signer(app.config['SECRET_KEY']) try: email = s.unsign(token) except BadSignature: return render_template("reset_invalid_token.html") user = User.query.filter_by(email=email).first() if user: user.set_password(form.password.data) print user.password login_user(user) return redirect("/") else: return render_template("reset_invalid_token.html") token = request.args.get('token', None) if not token: return render_template("reset_invalid_token.html") return render_template("reset_password.html", form=form, token=token)
def reset_token(token): if current_user.is_authenticated: return redirect(url_for('admin')) user = User.varify_reset_token(token) if user is None: flash('that is invalid or expired token ', 'warning') return redirect(url_for('reset_request')) form = ResetPasswordForm() if form.validate_on_submit(): register = Register(name=form.name.data, username=form.username.data, email=form.email.data, password=form.password.data, country=form.country.data, city=form.city.data, contact=form.contact.data, address=form.address.data, zipcode=form.zipcode.data) db.session.add(register) flash(f'Welcome {form.name.data} Thank you for registering', 'success') db.session.commit() return redirect(url_for('customerLogin')) return render_template('customer/reset_token.html', title='Reset Password', form=form)
def reset_password(serialized_token): expired, invalid, user = unserialize_token(serialized_token, 'reset') if expired: flash(msgs['LINK_EXPIRED'], 'error') return redirect(url_for('.index')) if invalid: flash(msgs['LINK_INVALID'], 'error') return redirect(url_for('.index')) form = ResetPasswordForm() form.login.data = user.login if form.validate_on_submit(): encrypted_password = encrypt_password(form.password.data) user.passhash = encrypted_password db.session.add(user) db.session.commit() form.dispose_password() flash(msgs['RESET_PASSWORD_SUCCESS']) return redirect(url_for('.login')) for field in form.errors: flash('<strong>' + field.capitalize() + '</strong>' + ': ' + form.errors[field][0], 'error') return render_template('reset_password.html', form=form, serialized_token=serialized_token)
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(): form = ResetPasswordForm() if request.method == 'GET': forgot_password_token = request.args.get('token') user = User.query.filter(User.forgotPasswordToken == forgot_password_token).first() if not user: abort(404) return render_template('reset_password.html', form=form, token=user.forgotPasswordToken) if request.method == 'POST': if form.validate_on_submit(): if form.password.data != form.retype_password.data: flash("Entered passwords did not match") user = User.query.filter(User.forgotPasswordToken == request.form.get('token').strip()).first() if user: user.set_password(form.retype_password.data) user.forgotPasswordToken = "" db.session.commit() return redirect(url_for("api.home")) else: abort(404) abort(405)
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 reset_password(): form = ResetPasswordForm() if form.validate_on_submit(): # Query "users" database for hash using lookup user = db.execute("SELECT * FROM user WHERE user_id = :user_id", user_id=session.get("user_id")) # Ensure current password is entered correctly if not check_password_hash(user[0]["hashed_pw"], form.current_password.data): flash('Current Password is invalid. Please re-enter', 'danger') return redirect("/account_settings") else: # Hash new password hashed_pw = generate_password_hash(form.new_password.data) # Update password in "user" table update_hash = db.execute( "UPDATE user SET hashed_pw = :hashed_pw WHERE user_id = :user_id", user_id=int(session.get("user_id")), hashed_pw=hashed_pw) # flash message flash('Password has been updated successfully!', 'success') else: flash("Sorry, we're unable to reset your password.", 'danger') return redirect("/account_settings")
def reset_password_link_page(urlsafe_string): try: temp_url = TemporaryUrl.get_by_id(int(urlsafe_string)) except Exception as e: logging.info(e) return render_template('not_found_page.html'), 404 if not temp_url.isActive(): logging.info('password reset link expired') return render_template('not_found_page.html'), 404 if not temp_url.user_key: logging.info('Reset link with no user key') return render_template('not_found_page.html'), 404 form = ResetPasswordForm() if form.validate_on_submit(): user = temp_url.user_key.get() user.password = generate_password_hash(form.password.data) user.put() temp_url.isValid = False temp_url.put() return redirect(url_for('web_app.home_page')) return render_template('reset_password_link_page.html', form=form, urlsafe_string=urlsafe_string)
def password_reset(token): email = confirm_token(token) user = User.query.filter_by(email=email).first() if user and user.reset: form = ResetPasswordForm(request.form) kwargs = { 'page_title': 'Reset Password', 'form_title': 'Reset Your Password', 'action': url_for('password_reset', token=token), 'primary_button': 'Submit', 'links': [('Need help?', '#')] } if form.validate_on_submit(): user.password = bcrypt.generate_password_hash(form.password.data) user.reset = False db.session.commit() flash( 'Your password has been successfully reset. You can log in now.', 'success') return redirect(url_for('homepage')) return render_template('formbuilder.html', form=form, **kwargs) else: flash('The reset password link is invalid or has expired.', 'danger') return redirect(url_for('homepage'))
def reset_token(token): '''This function will update the new password for the user.''' username = session['username'] valid = verify_reset_token(token) con = mysql.connect() cursor = con.cursor() if valid is False: flash('This URL has expired', 'warning') return redirect(url_for('forgot_password')) form = ResetPasswordForm() userDetails = request.form if form.validate_on_submit(): password = bcrypt.generate_password_hash(str( userDetails['password'])).decode('utf-8') res = cursor.execute("SELECT * from USERS WHERE Email = %s;", (username)) if int(res) > 0: cursor.execute("UPDATE USERS SET Password = %s WHERE Email = %s", (password, username)) con.commit() flash('Your password has been updated!', 'success') return redirect(url_for('login')) else: print("Record Not found") flash("Email id does not exist", "error") con.close() return render_template('reset_token.html', title='Reset Password', form=form)
def reset(): token = request.args.get('token') if not token: log_message(f'no token attempted reset') abort(404) try: user = User.deserialize(token) except SignatureExpired: flash('Expired Token', 'danger') log_message('expired token reset attempt') return redirect(url_for('main.index')) except BadSignature: flash('Invalid token', 'danger') log_message('bad signature reset attempt') return redirect(url_for('main.index')) form = ResetPasswordForm() if form.validate_on_submit(): log_message(f'user_id: {user.id} changed password') user.change_password(form.password.data) db.session.add(user) db.session.commit() flash('Password reset', 'success') login_user(user) return redirect(url_for('dash.index')) return render_template('auth/reset.html.j2', form=form)
def post(self,token): headers = {'Content-Type': 'text/html'} form = ResetPasswordForm() if form.validate_on_submit(): #user.set_password(form.password.data) #db.session.commit() updatePassword(token,form.password.data) return make_response(render_template('reset_password.html',form=form),200,headers)
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 reset_password(username): form = ResetPasswordForm() if form.validate_on_submit(): password = form.password.data user = User.update_password(username, password) return redirect('/login')
def admin_reset_password(): form = ResetPasswordForm() if form.validate_on_submit(): admin_id = current_user.id admin = Admin.query.get(int(admin_id)) admin.password = generate_password_hash(form.password.data) admin.is_pw_changed = True db.session.commit() return redirect(url_for('admin_dashboard')) return render_template('admin/reset_password.html', form=form)
def forgotten_password(): form = ResetPasswordForm() if form.validate_on_submit(): registered_user = retrieve_user_by_name(username=form.username.data) if registered_user != 'unknown user' and registered_user.email == form.email.data: send_mail(form.email.data, 'reset_password') return '<h1>A link has been sent to your registered email to reset your password</h1>' else: return '<h1>username or email is not registered</h1>' return render_template('Forgotten_Password.html', form=form)
def password_reset(): if current_user.is_authenticated: return redirect(url_for('index')) form = ResetPasswordForm() if form.validate_on_submit(): user = UserData.query.filter_by(email=form.email.data).first() if user: token = user.generate_password_reset() send_email(user.email, 'Forex Access Reset Your Password', 'email_password_reset', user=user, token=token) flash('Check Your email for the instructions to reset your password') return render_template('password_reset.html', form=form)
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 reset_password(token): if current_user.is_authenticated: return redirect(url_for('index')) user = Student.verify_reset_password_token(token) if not user: return redirect(url_for('index')) form = ResetPasswordForm() if form.validate_on_submit(): user.set_password(form.password.data) db.session.commit() flash('Your password has been reset.') return redirect(url_for('login')) return render_template('reset_password.html', form=form)
def reset_password(): # This function will reset the user password, send an email to the user at the entered email address. from datetime import datetime form = ResetPasswordForm() if form.validate_on_submit(): # Checks is the entered email address is in the database and assigns to user user = User.query.filter_by(email=form.email.data).first() if user: # if user email is verified, reset_key is created and the current time is stored reset_key_request = create_random_pwd() reset_time_request = datetime.now() # set user reset_key and reset_timer user.reset_key = reset_key_request user.reset_timer = reset_time_request.day + 100 # save day as integer + 100 reset_url = 'http://safety.americanpeptide.com/password_reset?email=%s&password_reset_key=%s' % (user.email, reset_key_request) flash("A password reset key has been created. Please check your email for the reset key to\ change your password.") msg = Message('Your Password Reset Key.', sender=('Safety Training Website', '*****@*****.**'), recipients=[user.email]) msg.html = """ <h2>User Password Reset</h2> <p>Hello %s %s.</p> <p>You have requested to change your password for the email %s. If you did not request to change your password, please ignore this message.</p> <p>To change your password, click on the following link. Enter the password reset key then enter your new password.</p> <p>Your Password Reset Key is: <strong> %s </strong></p> <p><a href="%s">Click here to reset your password.</a></p> """ % (user.firstname, user.lastname, user.email, reset_key_request, reset_url) mail.send(msg) # db.session.add(user) # print "session add user" db.session.commit() print "session commit user" return redirect(url_for('login')) else: flash("The email address that was entered is not valid. Please check the email and try again.") return render_template('reset_password.html', form=form)
def profile(): password_reset_form = ResetPasswordForm() username_reset_form = ResetUsernameForm() existing_user = user.query.filter_by(email=current_user.email).first() security_question = security_question_dict[existing_user.security_question] existing_answer = existing_user.security_answer existing_password = existing_user.password if password_reset_form.validate_on_submit(): security_answer = password_reset_form.security_answer.data new_password = password_reset_form.new_password.data if not check_password_hash(existing_answer, security_answer): flash("wrong security answer") return redirect(url_for('auth.profile')) print(new_password) existing_user.password = generate_password_hash(new_password, method='sha256') try: db.session.commit() return redirect(url_for('index')) except: return "Update error" if username_reset_form.validate_on_submit(): old_password = username_reset_form.old_password.data new_username = username_reset_form.new_username.data if not check_password_hash(existing_password, old_password): flash("wrong password or security answer") return redirect(url_for('auth.profile')) user_already_exists = user.query.filter_by( username=new_username).first() if user_already_exists: flash("username is taken") return redirect(url_for('auth.profile')) existing_user.username = new_username try: db.session.commit() return redirect(url_for('index')) except: return "Update error" return render_template('profile.html', current_user=current_user, password_reset_form=password_reset_form, username_reset_form=username_reset_form, security_question=security_question)
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 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 reset_password(token): if not current_user.is_anonymous: return redirect(url_for('main.index')) form = ResetPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is None: return redirect(url_for('main.index')) if user.reset_password(token,form.password.data): flash('You password have been update') return redirect(url_for('auth.login')) else: return redirect(url_for('main.index')) return render_template('auth/reset_password.html',form = form)
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_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 reset_password(token): if current_user.is_authenticated: return redirect(url_for('profile.list_bookmarks')) user = User.verify_reset_password_token(token) if not user: return redirect(url_for('home.homepage')) form = ResetPasswordForm() if form.validate_on_submit(): user.password(form.password.data) db.session.commit() flash('Your password has been reset.') return redirect(url_for('auth.login')) return render_template('email/reset_password.html', form=form)
def reset_token(token): if current_user.is_authenticated: return redirect(url_for('signup')) user = User.verify_reset_token(token) if user is None: flash('That is invalid or expired token', 'warning') return redirect(url_for('reset_request')) form = ResetPasswordForm() if form.validate_on_submit(): password = generate_password_hash(form.password.data) user.password = password db.session.commit() flash('Yor password has been updated!', 'success') return redirect(url_for('login')) return render_template('reset_token.html', form=form)
def reset_token(token): if session.get('email'): return redirect(url_for('index')) user_x = user.verify_reset_token(token) if user_x is None: flash('Token is invalid or expired', 'warning') return redirect(url_for('request_reset')) form = ResetPasswordForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.confirm_password.data).decode('utf-8') user_x.password = hashed_password db.session.commit() flash('Your password has been changed', 'success') return redirect(url_for('login')) return render_template('reset_token.html', form=form)
def reset_token(token): student = Student.get_verify_token(token) if student is None: flash('Invalid or expired tokens', 'danger') return redirect(url_for('reset_request')) form = ResetPasswordForm() if form.validate_on_submit(): hashed_pass = bcrypt.generate_password_hash( form.password.data).decode('utf-8') student.password = hashed_pass db.session.commit() flash('Your password has been updated', 'success') return redirect(url_for('login')) return render_template('reset_token.html', title='Reset password', form=form)
def resetPassword(token): if current_user.is_authenticated: return redirect(url_for('index')) user = User.verify_reset_token(token) if user is None: flash('Invalid or expired password reset link', 'warning') return redirect(url_for('forgotPassword')) form = ResetPasswordForm() if form.validate_on_submit(): user.password = form.new_password.data db.session.commit() flash('Your Password has been Updated! You can login now.', 'info') return redirect(url_for('login')) return render_template('resetpassword.html', form=form, title="ORM - Reset Password")
def reset_user_password(userid): form = ResetPasswordForm() user = User.query.filter_by(id=userid).first() if form.validate_on_submit(): print("Resetting Password:{}".format(form.new_password.data)) user.set_password(form.new_password.data) db.session.commit() print("done") flash('Password has been reset for user {}'.format(user.username)) return redirect(url_for('user_details')) return render_template('reset-password.html', title='Reset Password', form=form, user=user)
def reset_password(token): serializer = URLSafeTimedSerializer('asdfghjkl') try: email = serializer.loads(token, 86400) except SignatureExpired: return 'Token Expired' user = User.query.filter_by(email=email).first() if user: form = ResetPasswordForm() if form.validate_on_submit(): user.password_hash = user.hash_password(form.new_password.data) db.session.commit() flash('Password Changed!') return redirect(url_for('register')) return render_template('reset_password.html', form=form) return 'Password Reset Link Expired'
def confirm_forgot_password(): reset_password_form = ResetPasswordForm() if reset_password_form.submit4.data and reset_password_form.validate_on_submit(): result = request.form event = { 'username': result['username'], 'password': result['password'], 'code': result['ver_code'] } resp = reset_password(event) if resp['success']: return redirect(url_for('home', msg="Password has been changed successfully.")) else: return redirect(url_for('confirm_forgot_password', msg=resp['message'])) return render_template('confirm-forgot-password.html', resetpasswordform=reset_password_form, msg=request.args.get('msg'), user=logged_in_user)
def reset_password(token): if not current_user.is_anonymous(): return redirect(url_for('main.index')) form = ResetPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if not user: return redirect(url_for('main.index')) if not user.reset(token): flash('Invalidate token') return redirect(url_for('main.index')) user.password = form.new_password.data db.session.add(user) db.session.commit() flash('password reset successful. You can login.') return redirect(url_for('auth.login')) return render_template('auth/reset_password.html', form=form)
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(): if request.method == "POST": form = ResetPasswordForm( request.form) if( form.validate()): user = User.objects.get( email=form.email.data) password_reset_token = user.generate_password_reset_token() host = request.headers["HOST"] link = "http://%s/accounts/password/reset/%s" % (host, password_reset_token) mesg = "Hi %s,\n\nSomeone (probably you) requested for a password reset at %s. Please visit the following link if you wish to reset your password:\n\n%s\n\nHave a good day!" % (user.name, host, link) send_mail( "[%s] Reset Password" % host, mesg, current_app.config["SERVER_EMAIL"], [user.email], fail_silently=False) flash( "Sent you a mail to reset the password. Do remember to check your spam folder as well.", "success") form = ResetPasswordForm() return render_template( "auth/reset_password.html", **locals())
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(token): if not current_user.is_anonymous:#如果用户已经登录,跳转到首页 return redirect(url_for('main.index')) form = ResetPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email = form.email.data).first() if user is None: flash(u'邮箱地址错误') else: if user.confirm(token): user.password = form.password.data db.session.add(user) db.session.commit() flash(u'你刚刚重置了密码') return redirect(url_for('auth.login')) else: flash(u'错误的验证链接或链接已失效') #return redirect(url_for('main.index')) return render_template('auth/resetquest.html', form = form)
def reset_user_password(id): if not g.user.is_admin(): logger.error("%s tried to access /reset-user-password/%d", g.user.email, id) abort(403) user = User.query.get_or_404(id) form = ResetPasswordForm() if form.validate_on_submit(): if request.form['button'] == 'Cancel': return form.redirect(url_for('user_list')) user.reset_password(form.pass2.data) flash("User password modified successfully") logger.info("Password for %s was modified", user.email) return redirect(url_for('user_list')) return render_template('admin_reset_password.html', title = "Modify password", user = user, form = form)
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 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 reset(): form = ResetPasswordForm(request.form) if request.method == 'POST' and form.validate(): user = db.retrieve_user_by_email(form.email.data) if not user: form.email.errors.append('Email address not found') # generate 6 chars random password generated_password = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(6)]) # change password db.change_password(user.username, user.generate_hash(generated_password)) # generate email message email_msg = render_template('email/reset_password.html', username=user.username, new_password=generated_password) # send email send_email(recipient=user.email, subject='Reset Password', template=email_msg) flash('New password was sent to your email account, please check your inbox') return redirect(url_for('home')) return render_template('reset.html', form=form, title='Forgot Password')
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)