def password_change(request): if request.method == "POST": form = PasswordChangeForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=request.user.username, password=cd['current_password']) if not user: form.errors['__all__'] = form.error_class( ['Current password incorrect']) else: user.set_password(cd['password1']) user.save() update_session_auth_hash(request, user) # Success ! message = "You have successfully changed your password" url = reverse('profile') return success(request, url, message) else: form = PasswordChangeForm() return render( request, 'password_change_form.html', { 'form': form, 'form_title': 'Change Password', 'action': reverse('password_change') })
def update_password(request): if request.method == 'POST': form = PasswordChangeForm(request.POST) if form.is_valid(): request.user.set_password(form.cleaned_data['password1']) request.user.save() return render(request, 'registration/update_password.html', {'success': True}) else: form = PasswordChangeForm() return render(request, 'registration/update_password.html', {'form': form})
def password_change(request): message = '' saved = False form = PasswordChangeForm() # is the user logged in? if not request.user.is_authenticated(): return HttpResponseRedirect('/nest/login/') if request.user.is_staff: return HttpResponseRedirect('/admin/') # change password if request.method == 'POST': pcform = PasswordChangeForm(data=request.POST) if pcform.is_valid(): # still have to check if old password matches u = request.user oldpass = request.POST.get('oldpass') newpass = request.POST.get('newpass1') if u.check_password(oldpass): # passwords match so it's safe to change the password u.set_password(newpass) u.save() # for some reason, the user gets logged out so we have to log them in again login(request, authenticate(username=u.username, password=newpass)) # create a message and redirect to the dashboard messages.add_message( request, messages.SUCCESS, "Your password has been changed successfully") return HttpResponseRedirect('/nest/') else: form = pcform message = '<span style="color:firebrick">Old password is incorrect. Please try again</span>' else: form = pcform message = '<span style="color:firebrick">Please correct the errors below</span>' context = { 'title': 'Change my password' + SITE_SUF, 'navlight': 3, 'request': request, 'message': message, 'form': form, 'saved': saved, } return render(request, 'nest/passwordchange.html', context)
def change_password(request): user = request.user if request.method == "POST": form = PasswordChangeForm(request.POST) if form.is_valid(): password = form.cleaned_data['password'] user.set_password(password) user.save() logger.info("Changed password for user %s" % user.username) messages.info(request, "Password was changed!") else: form = PasswordChangeForm() data = {'form': form} return render_to_response('people/change-password.html', data, RequestContext(request))
def changepassword(): form = PasswordChangeForm() if request.method == 'GET': return render_template('changepassword.html', form=form, name=current_user.email) else: if form.validate_on_submit(): if current_user.validate_password(form.currentpassword.data): local_object = db.session.merge(current_user) local_object.password = current_user.update_password( form.newpassword.data) db.session.add(local_object) db.session.commit() Mail_Service.send_email(current_user.email, "Password Changed", current_user, request.remote_addr) flash("Password Sucessfully Changed") else: flash("Incorrect Current Password") return render_template('changepassword.html', form=form, name=current_user.email) else: flash("Error with form") return render_template('changepassword.html', form=form, name=current_user.email) return redirect(url_for('account'))
def recover(secret_key): form = PasswordChangeForm(request.form) data = RecoveryData.query.filter_by(secret_key=secret_key).first() if data is None: flash('Secret key for password recovery was invalid', 'danger') return redirect(url_for('home')) if not data.is_valid(): flash('This recovery link has expired.') database.session.delete(data) database.session.commit() return redirect(url_for('home')) if request.method == 'POST' and form.validate(): account = Account.query.filter_by(name=data.name, email=data.email).first() if account is None: flash('Something went wrong, unknown user', 'danger') return redirect(url_for('home')) account.password = bcrypt.generate_password_hash(form.data['password']) database.session.delete(data) database.session.commit() flash('Successfully changed your password', 'success') return redirect(url_for('login')) return render_template('views/recover.html', form=form)
def put(self): data = ImmutableMultiDict(request.json) change_password_form = PasswordChangeForm(data, csrf_enabled=False) if change_password_form.validate(): obj = User.query.filter(User.username == current_identity.username).first() change_password_form.save(obj) return jsonify({"status": "success", "message": "Password Changed"}) return change_password_form.errors
def password_change(request, template_name='registration/password_change_form.html', post_change_redirect=None): if post_change_redirect is None: #post_change_redirect = reverse('django.contrib.auth.views.password_change_done') post_change_redirect = reverse('auth.views.password_change_done') if request.method == "POST": form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(post_change_redirect) else: form = PasswordChangeForm(request.user) return render_to_response(template_name, { 'form': form, }, context_instance=RequestContext(request))
def settings_view(request): if request.method == 'POST': form = PasswordChangeForm(user=request.user, data=request.POST, files=request.FILES) #imgform = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return HttpResponseRedirect(reverse('settings_view')) else: pass else: form = PasswordChangeForm(user=request.user) #imgform = UploadFileForm() context = { 'form': form, } return render(request, "profile.html", context)
def test_pw_change(self): user = create_user() pw = 'new_pass1' form = PasswordChangeForm(user=user, data={ 'old_password': PASSWORD, 'new_password1': pw, 'new_password2': pw, }) form.is_valid() form.save() self.assertTrue(form.password_changed())
def test_pw_length(self): user = create_user() for pw, success in [( 'a', False, ), ( 'a' * User.MINIMUM_PASSWORD_LENGTH, True, )]: form = PasswordChangeForm(user=user, data={ 'old_password': PASSWORD, 'new_password1': pw, 'new_password2': pw, }) self.assertEqual(form.is_valid(), success)
def change_password(secretstring): form = PasswordChangeForm() if form.validate_on_submit(): if form.password.data: s = URLSafeSerializer('serliaizer_code') uname, uemail = s.loads(secretstring) user = Users.query.filter_by(username=uname).first() db.session.add(user) user.pwdhash = bcrypt.generate_password_hash(form.password.data) db.session.commit() flash(u'succsessful password reset') return redirect(url_for('login')) else: flash('Try again!') return redirect(url_for('reset_password')) return render_template('change_password.html', form=form)
def changepasswd(): session_id = request.cookies.get(SESSION_ID) if session_id is None: return redirect(url_for('logout')) if not session_db.exists(session_id): return redirect(url_for('logout')) form = PasswordChangeForm() hidden = request.cookies.get('login') if hidden is None: return render_template('problem.html') form.hidden = hidden if form.validate_on_submit(): ssid = request.cookies.get(SESSION_ID) user = session_db.get(ssid) user_data = dbc.getUserByLogin(user) user_id = user_data[0] dbc.updatePassword(user_id, hash_password(form.newpassword.data)) return render_template('changegood.html') return render_template('changepasswd.html', form=form)
def password_change(): form = PasswordChangeForm() if form.validate_on_submit(): user_id = current_user.get_id() user = User.query.get(user_id) if user and not bcrypt.check_password_hash(user.Password, form.old_password.data): flash('Old password is incorrect.', 'danger') else: hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user.Password = hashed_password db.session.add(user) db.session.commit() flash('Your password has been changed.', 'success') return render_template('password-change.html', title='Change Password', form=form)
def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.POST) password_correct = False if form.is_valid(): current_password = form.cleaned_data['current_password'] new_pass = form.cleaned_data['new_password1'] password_correct = request.user.check_password(current_password) if password_correct: request.user.set_password(new_pass) request.user.save() json = {'location': '.'} return HttpResponse(simplejson.dumps(json), mimetype="application/json") if not password_correct: form._errors['current_password'] = ErrorList() form._errors['current_password'].append(_("Your password is incorrect")) else: raise Http404 return render(request, 'password_change_modal.html', {'form': form})
def account(): # Get basic database and forms ready to return bsdb = get_bsdb() acct = AccountSettings(session['user_num']) account_settings_change_form = AccountSettingsChangeForm() password_change_form = PasswordChangeForm() account_settings = bsdb.get_account_settings(session["user_num"]) show_account_modal = False show_password_modal = False # Check against requests to change account settings if (req.method == 'POST' and account_settings_change_form.submit_account_change.data): show_account_modal = True app.logger.info(f"request received to change user settings for " + f"user {session['user_num']}") # Check to make sure form was valid, return form if it was not if not account_settings_change_form.validate_on_submit(): app.logger.warning(f"Settings change form failed validation") flash("Your information wouldn't work. Try again?", "warning") return render_template( 'user/user-home.html', account_settings=account_settings, account_settings_change_form=account_settings_change_form, password_change_form=password_change_form, show_account_modal=show_account_modal, show_password_modal=show_password_modal ) # Check that the username isn't changing or is available if acct.is_username_valid(session['user_num'], account_settings_change_form.username.data): app.logger.info("username is valid") try: acct.set_account_information( session['user_num'], account_settings_change_form) flash("Account information updated.", "success") app.logger.info("returning new account info:") account_settings = bsdb.get_account_settings( session["user_num"]) show_account_modal = False account_settings = bsdb.get_account_settings( session["user_num"]) except Exception: flash("Error updating your information. Try again?", "warning") else: flash("Username is already taken", "warning") # Check against request to change password elif req.method == 'POST' and password_change_form.submit.data: show_password_modal = True app.logger.info(f"request received to change password for " + f"user {session['user_num']}") if not password_change_form.validate_on_submit(): app.logger.warning(f"Password change form failed verification") flash("Your infromation wouldn't work. Try again?", "warning") return render_template( 'user/user-home.html', account_settings=account_settings, account_settings_change_form=account_settings_change_form, password_change_form=password_change_form, show_account_modal=show_account_modal, show_password_modal=show_password_modal ) try: correct_password = acct.is_password_correct(session["user_num"], password_change_form) if not correct_password: flash("Original password was not correct. Please try again.", "warning") else: app.logger.info("Original password was entered correctly.") try: acct.set_password(session["user_num"], password_change_form) app.logger.info("New Password set") flash("New Password Sucessfully Set.", "success") show_password_modal = False except Exception: app.logger.error("Error setting new password") flash("Error setting new password. Try again?", "warning") except Exception: flash("Error determining if the original password is correct. Try again?", "warning") app.logger.error("Error checking original password.") # We got here either by being GET or succeeding making changes. # Refill account_setting and account_settings_change_form account_settings_change_form = acct.fill_account_settings_change_form() account_settings = bsdb.get_account_settings(session["user_num"]) return render_template( 'user/user-home.html', account_settings=account_settings, account_settings_change_form=account_settings_change_form, password_change_form=password_change_form, show_account_modal=show_account_modal, show_password_modal=show_password_modal )
def editview(request, action): if request.user.is_authenticated(): request_data = None context = {} if request.method == 'POST': request_data = request.POST if action == 'password': form = PasswordChangeForm(user=request.user, data=request_data) context = {'form': form, 'action': 'Change password', 'edition': True} elif action == 'settings': tz = 'UTC' if hasattr(request.user, 'sciriususer'): tz = request.user.sciriususer.timezone initial = {'timezone': tz} if request.user.is_superuser: form = UserSettingsForm(request_data, instance=request.user, initial=initial) else: form = NormalUserSettingsForm(request_data, instance=request.user, initial=initial) context = {'form': form, 'action': 'Edit settings for ' + request.user.username, 'edition': True} elif action == 'token': initial = {} token = Token.objects.filter(user=request.user) if len(token): initial['token'] = token[0] form = TokenForm(request_data, initial=initial) context = {'form': form, 'action': 'User token', 'edition': True} else: context = {'action': 'User settings', 'edition': False} if request.method == 'POST': orig_superuser = request.user.is_superuser orig_staff = request.user.is_staff if form.is_valid(): if action == 'token': current_tokens = Token.objects.filter(user=request.user) for token in current_tokens: token.delete() Token.objects.create(user=request.user) UserAction.create( action_type='edit_user_token', comment=form.cleaned_data['comment'], user=request.user, other_user=request.user ) return redirect('accounts_edit', action='token') context['edition'] = False context['action'] = 'User settings' ruser = form.save(commit = False) if not orig_superuser: ruser.is_superuser = False ruser.is_staff = orig_staff ruser.save() if action == 'password': update_session_auth_hash(request, ruser) UserAction.create( action_type='edit_user_password', comment=form.cleaned_data['comment'], user=request.user, other_user=request.user ) if action == 'settings': try: sciriususer = ruser.sciriususer sciriususer.timezone = form.cleaned_data['timezone'] except: sciriususer = SciriusUser.objects.create(user = ruser, timezone = form.cleaned_data['timezone']) UserAction.create( action_type='edit_user', comment=form.cleaned_data['comment'], user=request.user, other_user=request.user ) sciriususer.save() return scirius_render(request, 'accounts/edit.html', context)