Esempio n. 1
0
    def test_edit(self):
        u = User(username='******', email='*****@*****.**', password='******',
                 about_me='test')
        self.create_user(u)
        assert u in db.session

        # going to the edit page when no one is logged in
        assert current_user.is_anonymous
        rv = self.edit(u, 'james', '*****@*****.**', 'foobar', 'test')
        assert "Please log in to access this page" in rv.data.decode("utf-8")

        # loggin in test user
        self.login(u, '*****@*****.**', 'foobar')
        assert current_user == u

        # checking empty edit
        rv = self.edit(u, '', '', '', '')
        assert current_user.username.lower() == 'jim'
        assert current_user.email == '*****@*****.**'
        assert current_user.check_password('foobar')
        assert current_user.about_me == 'test'

        # checking successful edit
        rv = self.edit(u, 'james', '*****@*****.**', 'pharos1', 'something')
        assert current_user.username.lower() == 'james'
        assert current_user.email == '*****@*****.**'
        assert current_user.check_password('pharos1')
        assert current_user.about_me == 'something'
Esempio n. 2
0
 def validate(self):
     initial_validation = super(ChangePasswordForm, self).validate()
     if not initial_validation:
         return False
     if not current_user.check_password(self.old_password.data):
         self.old_password.errors.append('The old password you entered is incorrect.')
         return False
     if current_user.check_password(self.new_password.data):
         self.new_password.errors.append('You cannot use the same password as your new password.')
         return False
     return True
Esempio n. 3
0
 def validate(self):
     initial_validation = super(ChangePasswordForm, self).validate()
     if not initial_validation:
         return False
     if not current_user.check_password(self.old_password.data):
         self.old_password.errors.append(
             'The old password you entered is incorrect.')
         return False
     if current_user.check_password(self.new_password.data):
         self.new_password.errors.append(
             'You cannot use the same password as your new password.')
         return False
     return True
def edit_password():
	form = EditPasswordForm(request.form)
	if request.method == 'POST' and form.validate():
		if current_user.check_password(form.data['old_password']):
			print(current_user.check_password(form.data['old_password']))
			current_user.password = form.data['new_password'];
			current_user.save()
			notification = Notify(notification_type = 'success', message = 'Successfully Changed Password')
			return redirect(url_for('user', notify = True, notify_type = notification.type, notify_message = notification.message))
		else:
			notification = Notify(notification_type = 'error', message = 'Old Password Incorrect') 
			return render_template('edit_password.html', form=form, notify = notification)
	return render_template('edit_password.html', form=form)
Esempio n. 5
0
def username(username):
    Account = AccountFactory.get_model()
    acc = Account.pull(username)
    if acc is None:
        try:
            acc = Account.pull_by_email(username)
        except exceptions.NonUniqueAccountException:
            flash("Permanent Error: these user credentials are invalid - please contact an administrator", "error")
            return redirect(url_for(("logut")))

    if acc is None:
        abort(404)

    # actions on this page are only availble to the actual user, or a user with the edit-users role
    if current_user.id != acc.id or not current_user.has_role(app.config.get("ACCOUNT_EDIT_USERS_ROLE")):
        abort(401)

    # if this is a request for the user page, just render it
    if request.method == "GET":
        fc = AccountFactory.get_user_formcontext(acc)
        return fc.render_template()


    is_delete = request.method == "DELETE" or (request.method == "POST" and request.values.get("submit", False) == "Delete")
    if is_delete:
        # validate the delete
        if not current_user.check_password(request.values.get("password")):
            flash("Incorrect password", "error")
            fc = AccountFactory.get_user_formcontext(acc=acc)
            return fc.render_template()

        # if the password validates, go ahead and do it
        acc.remove()    # Note we don't use the DAO's delete method - this allows the model to decide the delete behaviour
        _do_logout()
        flash('Account {x} deleted'.format(x=username), "success")
        return redirect(url_for(app.config.get("ACCOUNT_LOGOUT_REDIRECT_ROUTE", "index")))

    if request.method == "POST":
        fc = AccountFactory.get_user_formcontext(acc=acc, form_data=request.form)

        # attempt to validate the form
        if not fc.validate():
            flash("There was a problem when submitting the form", "error")
            return fc.render_template()

        # if the form validates, then check the legality of the submission
        try:
            fc.legal()
        except exceptions.AccountException as e:
            flash(e.message, "error")
            return fc.render_template()

        # if we get to here, then update the user record
        fc.finalise()

        # tell the user that everything is good
        flash("Account updated", "success")

        # end with a redirect because some details have changed
        return redirect(url_for("account.username", username=fc.target.email))
Esempio n. 6
0
def user():
  dbuser = db.session.query(User).filter_by(username=current_user.id).first()
  if dbuser is None:
    abort(401)

  if request.method == "POST":
    # update user info
    new_user = UserDecoder().decode(request.json)
    if new_user is None:
      print "Failed to decode request.json"
      abort(400)
    dbuser.update_with_user(new_user)

    # change password
    if len(request.json.get("oldpassword", "")) > 0 \
        and len(request.json.get("newpassword", "")) > 0:
      # check old password
      if current_user.check_password(request.json["oldpassword"]):
        current_user.set_password(request.json["newpassword"])
        dbuser.password_hash = current_user.pw_hash

    db.session.commit()
    return jsonify({})

  return render_template("user.html", current_dbuser=dbuser)
Esempio n. 7
0
def user():
  dbuser = db.session.query(User).filter_by(username=current_user.id).first()
  if dbuser is None:
    abort(401)

  if request.method == "POST":
    # update user info
    new_user = UserDecoder().decode(request.json)
    if new_user is None:
      print "Failed to decode request.json"
      abort(400)
    dbuser.update_with_user(new_user)

    # change password
    if len(request.json.get("oldpassword", "")) > 0 \
        and len(request.json.get("newpassword", "")) > 0:
      # check old password
      if current_user.check_password(request.json["oldpassword"]):
        current_user.set_password(request.json["newpassword"])
        dbuser.password_hash = current_user.pw_hash

    db.session.commit()
    return jsonify({})

  return render_template("user.html", current_dbuser=dbuser)
Esempio n. 8
0
def settings():
    form = SettingsForm(request.form,
                        username=current_user.username,
                        email=current_user.mail,
                        show_def_name=current_user.get_setting(code='show_def_name'),
                        show_def_desc=current_user.get_setting(code='show_def_desc'),
                        show_def_tags=current_user.get_setting(code='show_def_tags'),
                        show_def_logo=current_user.get_setting(code='show_def_logo'),
                        use_icy=current_user.get_setting(code='use_icy'))

    if request.method == "POST" and form.validate():
        if current_user.check_password(password=form.old_password.data):
            if form.new_password.data:
                current_user.password = User.make_password(form.new_password.data)
            current_user.mail = form.email.data
            current_user.set_setting(code='show_def_name', value=form.show_def_name.data)
            current_user.set_setting(code='show_def_desc', value=form.show_def_desc.data)
            current_user.set_setting(code='show_def_tags', value=form.show_def_tags.data)
            current_user.set_setting(code='show_def_logo', value=form.show_def_logo.data)
            current_user.set_setting(code='use_icy', value=form.use_icy.data)
            rfk.database.session.commit()
            flash(gettext('Settings successfully updated.'), 'success')
            return redirect(url_for('settings'))
        else:
            form.old_password.errors.append(gettext('Wrong password.'))

    return render_template('settings.html', form=form, TITLE='Settings',
                           imgur={'client': rfk.CONFIG.get('site', 'imgur-client')})
Esempio n. 9
0
 def profile(self):
     account_form = AccountUpdateForm(obj=current_user)
     account_form.main_character.choices = [(character.id, character.name) for character in current_user.characters if character.get_status() != CharacterStatus.ineligible]
     if account_form.validate_on_submit():
         if account_form.new_password.data and not account_form.password.data:
             flash('Your password is required to make these changes.', 'danger')
             return redirect(url_for('AccountView:profile'))
         if current_user.check_password(account_form.password.data):
             # Password checks out, let's update it
             current_user.update_password(account_form.new_password.data)
             db.session.add(current_user)
             db.session.commit()
             User.password_updated.send(current_user, account_form.new_password.data)
             session.clear()
             flash('Your password has been updated, please login again.')
             return redirect(url_for('AccountView:login'))
         current_user.email = account_form.email.data
         new_main_character = current_user.characters.filter_by(id=account_form.main_character.data).first()
         if not character:
             flash("We could not found this character in your characters.", 'danger')
             return redirect(url_for('AccountView:profile'))
         else:
             current_user.name = new_main_character.name
             current_user.main_character_id = new_main_character.id
         db.session.add(current_user)
         db.session.commit()
         flash('Account updated.', 'success')
         return redirect(url_for('AccountView:profile'))
     api_forms = [APIKeyForm(obj=api_key) for api_key in current_user.api_keys]
     new_api_form = APIKeyForm()
     return render_template('account/profile.html', account_form=account_form, api_forms=api_forms, new_api_form=new_api_form)
Esempio n. 10
0
def me_edit_login():
	form = UserEditLoginForm(obj=current_user)
	if form.validate_on_submit():
		if not current_user.check_password(form.old_password.data):
			form.old_password.errors.append('Incorrect Password')
		else:
			current_user.username = form.username.data
			current_user.set_password(form.password.data)
			db.session.commit()
			return redirect('.me')
	return render_template('users/me_edit_login.html', user=current_user, form=form)
Esempio n. 11
0
def change_password():
    """
    Change logged in user's password.
    """
    form = ChangePasswordForm(request.json_multidict)
    if not form.validate_on_submit():
        return api_error(form.errors)
    if not current_user.check_password(form.current.data):
        return api_error(dict(form=['Current password is incorrect.']))
    current_user.set_password(form.new_password.data)
    current_user.save()
    return '', 200
Esempio n. 12
0
def refresh_login():
    form = PasswordForm()

    if form.validate_on_submit():
        if current_user.check_password(form.password.data):
            confirm_login()
            return redirect(request.args.get("next") or url_for("index"))
        else:
            flash("Incorrect password.")
            return redirect(url_for('refresh_login'))

    return render_template('accounts/refresh.html', form=form)
Esempio n. 13
0
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.check_password(form.current_password.data):
            current_user.password = form.new_password.data
            db.session.add(current_user)
            db.session.commit()
            flash(u'新密码已设置。', 'success')
            return redirect(url_for('.index'))
        else:
            flash(u'原密码有误,请重新输入。', 'warning')
    return render_template('settings/change-password.html', form=form)
Esempio n. 14
0
def change_password():
    """Password changing."""
    form = PasswordForm()

    if form.validate_on_submit():
        if not current_user.check_password(form.old_password.data):
            form.add_error('old_password', 'Old password is invalid.')
        else:
            with db.transaction:
                current_user.password = form.new_password.data
            return redirect(request.args.get('next') or url_for('settings'))

    return render_template('change_password.html', form=form)
Esempio n. 15
0
def change_password():
    """Password changing."""
    form = PasswordForm()

    if form.validate_on_submit():
        if not current_user.check_password(form.old_password.data):
            form.add_error('old_password', 'Old password is invalid.')
        else:
            with db.transaction:
                current_user.password = form.new_password.data
            return redirect(request.args.get('next') or url_for('settings'))

    return render_template('change_password.html', form=form)
Esempio n. 16
0
def changepassword():
    form = ChangePasswordForm(request.form)
    if request.method == "POST" and form.validate():
        if not current_user.check_password(form.old_password.data):
            form.old_password.errors.append(u"密码错误!")
            return render_template("changepassword.html", form=form)

        current_user.password = User.create_password(form.new_password.data)
        db.session.add(current_user)
        db.session.commit()
        flash(u"密码修改成功!")
        return render_template("changepassword.html", form=ChangePasswordForm())

    return render_template("changepassword.html", form=form)
Esempio n. 17
0
def change_password():
    '''
    Change a user's password
    '''
    form = ChangePasswordForm(request.form)
    if request.method == 'POST' and form.validate():
        if current_user.check_password(form.old_password.data):
            current_user.update_password(form.new_password.data)
            current_user.save()
            flash("Your password has been updated.", category='index_page')
            return redirect(url_for('.list_projects'))
        else:
            flash("Your password does not match.", category='error')
            return render_template('change_password.html', form=form)    
    return render_template('change_password.html', form=form)
Esempio n. 18
0
def change_password():
    """
    Change user's password view
    """
    form = ChangePass(request.form)
    if request.method == 'POST' and form.validate():
        old_password = request.form.get('old_pass')
        new_password = request.form.get('new_pass')
        if current_user.check_password(old_password):
            current_user.change_password(new_password)
            db.session.add(current_user)
            db.session.commit()
            flash('Your password successfully changed', 'success')
            return redirect(url_for('index'))
    return render_template('change_pass.html', form=form)
Esempio n. 19
0
def make_admin(user_id):
    form = ConfirmPasswordForm()
    user = User.query.filter_by(id=user_id).first_or_404()
    if form.validate_on_submit():
        if current_user.check_password(form.password.data):
            user.admin = not user.admin
            db.session.commit()
            return redirect(url_for('view_frontend'))
        else: 
            form.password.errors.append('Wrong password')
    return render_template('confirm.html',
        user=current_user.to_dict() if is_logged_in() else None, 
        form=form,
        title='Change Admin Status',
        target=url_for('make_admin', user_id=user_id))
Esempio n. 20
0
def sign_in():
    """Log the user into the server"""
    # Check for the correct form data to be submitted
    if "user[password]" not in request.form or "user[email]" not in request.form:
        abort(400)

    # Get the user and check the password
    user = User.get_by_email(request.form["user[email]"])
    if user and user.check_password(request.form["user[password]"]):
        # If the user and credentials are valid, log the user in
        login_user(user)
        return jsonify(success=True)

    # Something went wrong
    return jsonify(success=False, errors=["Login Failed"])
Esempio n. 21
0
def login():
    'Login view'
    form = LoginForm()
    invalid_login = False
    if form.validate_on_submit():
        user = User.get_user(form.username.data)
        if user and user.check_password(form.password.data):
            login_user(user)
            return redirect(app.config['LOGIN_REDIRECT'])
        else:
            invalid_login = True
        

    return render_template('spirits/login.jinja', form=form, 
                                                  invalid_login=invalid_login)
Esempio n. 22
0
def changepassword():
    form = ChangePasswordForm(request.form)
    if request.method == 'POST' and form.validate():
        if not current_user.check_password(form.old_password.data):
            form.old_password.errors.append(u'密码错误!')
            return render_template("changepassword.html", form=form)

        current_user.password = User.create_password(form.new_password.data)
        db.session.add(current_user)
        db.session.commit()
        flash(u"密码修改成功!")
        return render_template("changepassword.html",
                               form=ChangePasswordForm())

    return render_template("changepassword.html", form=form)
Esempio n. 23
0
def drop_all():
    form = DropAllForm()
    if form.validate_on_submit():
        if current_user.check_password(form.password.data):
            items = current_user.items
            current_user.items = []
            for item in items:
                db.session.delete(item)
            db.session.add(current_user)
            db.session.commit()
            flash(u'您已清空所有条目。', 'danger')
            return redirect(url_for('.index'))
        else:
            flash(u'您输入的密码不正确!', 'warning')
    flash(u'注意:您将会清空所有条目,此操作不可逆!', 'danger')
    return render_template('settings/drop-all.html', form=form)
Esempio n. 24
0
def sign_in():
    """Log the user into the server"""
    # Check for the correct form data to be submitted
    if 'user[password]' not in request.form \
        or 'user[email]' not in request.form:
        abort(400)

    # Get the user and check the password
    user = User.get_by_email(request.form['user[email]'])
    if user and user.check_password(request.form['user[password]']):
        # If the user and credentials are valid, log the user in
        login_user(user)
        return jsonify(success=True)

    # Something went wrong
    return jsonify(success=False, errors=['Login Failed'])
Esempio n. 25
0
def make_admin(user_id):
    form = ConfirmPasswordForm()
    user = User.query.filter_by(id=user_id).first_or_404()
    if form.validate_on_submit():
        if current_user.check_password(form.password.data):
            user.admin = not user.admin
            db.session.commit()
            return redirect(url_for('view_frontend'))
        else:
            form.password.errors.append('Wrong password')
    return render_template(
        'confirm.html',
        user=current_user.to_dict() if is_logged_in() else None,
        form=form,
        title='Change Admin Status',
        target=url_for('make_admin', user_id=user_id))
Esempio n. 26
0
def change_password():
    """
    Change a user's password
    """
    # form = ChangePasswordForm(request.form)
    # if request.method == 'POST' and form.validate():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.check_password(form.old_password.data):
            current_user.update_password(form.new_password.data)
            current_user.save()
            flash("Your password has been updated.", category="index_page")
            return redirect(url_for(".list_projects"))
        else:
            flash("Your password does not match.", category="error")
            return render_template("change_password.html", form=form)
    return render_template("change_password.html", form=form)
Esempio n. 27
0
def reset_password():
    res = ajax_response()
    old_password = request.form.get('old_password')
    new_password = request.form.get('new_password')
    new_password_confirm = request.form.get('new_password_confirm')
    if new_password and new_password_confirm and new_password_confirm != new_password:
        res.update({'info': '两次输入的新密码不一致', 'type': 'error'})
        return jsonify(res)
    if not current_user.check_password(old_password):
        res.update({'info': '原始密码错误', 'type': 'error'})
        return jsonify(res)
    with session_cm() as session:
        session.query(User).get(
            current_user.user_id).set_password(new_password)
        session.commit()
    res.update(info='密码修改成功')
    return jsonify(res)
Esempio n. 28
0
def change_password(user_id=None):
    form = ChangePasswordForm()
    if user_id is not None and not is_admin():
        return 'You are not authorised', 403
    if user_id is None:
        user_id = current_user.get_id()
    user = User.query.filter_by(id=user_id).first_or_404()
    if form.validate_on_submit():
        if current_user.check_password(form.current_password.data):
            user.set_password(form.new_password.data)
            db.session.commit()
            return redirect(url_for('view_frontend'))
        else: 
            form.current_password.errors.append('Wrong password')
    return render_template('user_change_password.html',
        form=form,
        user=current_user.to_dict() if is_logged_in() else None,
        user_id=user_id)
Esempio n. 29
0
def change_password(user_id=None):
    form = ChangePasswordForm()
    if user_id is not None and not is_admin():
        return 'You are not authorised', 403
    if user_id is None:
        user_id = current_user.get_id()
    user = User.query.filter_by(id=user_id).first_or_404()
    if form.validate_on_submit():
        if current_user.check_password(form.current_password.data):
            user.set_password(form.new_password.data)
            db.session.commit()
            return redirect(url_for('view_frontend'))
        else:
            form.current_password.errors.append('Wrong password')
    return render_template(
        'user_change_password.html',
        form=form,
        user=current_user.to_dict() if is_logged_in() else None,
        user_id=user_id)
Esempio n. 30
0
def change_password():
    if request.method == 'POST':
        new_password = request.form.get('newpassword1', '')
        if not current_user.check_password(
                request.form.get('currentpassword', '')):
            flash(
                'Your current password was entered incorrectly. Please check and try again.'
            )
        elif new_password != request.form.get('newpassword2', ''):
            flash(
                'Password not changed: new passwords provided did not match.')
        elif len(new_password) < 8:
            flash(
                'Password not changed: Please use a password at least 8 characters long.'
            )
        else:
            current_user.change_password(new_password)
            return redirect(url_for('standings'))

    return render_template('changepassword.html')
Esempio n. 31
0
def account_settings():
	if request.method == 'POST':
		if request.form.get('current-password'): # user is asking to change their password

			current = request.form.get('current-password')
			new = request.form.get('new-password')
			repeatnew = request.form.get('repeat-new-password')

			if not current_user.check_password(current):
				flash("Current password does not match.", 'error')
				return redirect(url_for('account_settings'))
			if new != repeatnew:
				flash("The passwords do not match.", 'error')
				return redirect(url_for('account_settings'))

			current_user.reset_password(new)
			g.UserManager.save_user(current_user)
			flash('Password changed successfully!', 'success')
			return redirect(url_for('account_settings'))

	return render_template('account/settings.html')
Esempio n. 32
0
def account_settings():
	if request.method == 'POST':
		if request.form.get('current-password'): # user is asking to change their password

			current = request.form.get('current-password')
			new = request.form.get('new-password')
			repeatnew = request.form.get('repeat-new-password')

			if not current_user.check_password(current):
				flash("Current password does not match.", 'error')
				return redirect(url_for('account_settings'))
			if new != repeatnew:
				flash("The passwords do not match.", 'error')
				return redirect(url_for('account_settings'))

			current_user.reset_password(new)
			UserManager.save_user(current_user)
			flash('Password changed successfully!', 'success')
			return redirect(url_for('account_settings'))

	return render_template('account/settings.html')
Esempio n. 33
0
def reset_password():
    res = ajax_response()
    old_password = request.form.get('old_password')
    new_password = request.form.get('new_password')
    new_password_confirm = request.form.get('new_password_confirm')
    if new_password and new_password_confirm and new_password_confirm != new_password:
        res.update({
            'info': '两次输入的新密码不一致',
            'type': 'error'
        })
        return jsonify(res)
    if not current_user.check_password(old_password):
        res.update({
            'info': '原始密码错误',
            'type': 'error'
        })
        return jsonify(res)
    with session_cm() as session:
        session.query(User).get(current_user.user_id).set_password(new_password)
        session.commit()
    res.update(info='密码修改成功')
    return jsonify(res)
Esempio n. 34
0
def settings():
    form = SettingsForm(
        request.form,
        username=current_user.username,
        email=current_user.mail,
        show_def_name=current_user.get_setting(code='show_def_name'),
        show_def_desc=current_user.get_setting(code='show_def_desc'),
        show_def_tags=current_user.get_setting(code='show_def_tags'),
        show_def_logo=current_user.get_setting(code='show_def_logo'),
        use_icy=current_user.get_setting(code='use_icy'))

    if request.method == "POST" and form.validate():
        if current_user.check_password(password=form.old_password.data):
            if form.new_password.data:
                current_user.password = User.make_password(
                    form.new_password.data)
            current_user.mail = form.email.data
            current_user.set_setting(code='show_def_name',
                                     value=form.show_def_name.data)
            current_user.set_setting(code='show_def_desc',
                                     value=form.show_def_desc.data)
            current_user.set_setting(code='show_def_tags',
                                     value=form.show_def_tags.data)
            current_user.set_setting(code='show_def_logo',
                                     value=form.show_def_logo.data)
            current_user.set_setting(code='use_icy', value=form.use_icy.data)
            rfk.database.session.commit()
            flash('Settings successfully updated.', 'success')
            return redirect(url_for('settings'))
        else:
            form.old_password.errors.append('Wrong password.')

    ball = rfk.helper.iso_country_to_countryball(current_user.country)
    return render_template(
        'settings.html',
        form=form,
        TITLE='Settings',
        ball=ball,
        imgur={'client': rfk.CONFIG.get('site', 'imgur-client')})
Esempio n. 35
0
def change_password():
    ret = _default_response()
    ret['form'] = ChangePasswordForm()
    ret['title'] =  u"Zmień hasło"
    ret['section_title'] = u"Zmień hasło"

    if ret['form'].validate_on_submit():
        from recorder.models import User
        if not current_user.check_password(ret['form'].current_password.data): 
            ret['error'] =  u"Podano błędne OBECNE hasło"
            return ret 

        if ret['form'].password.data != ret['form'].re_password.data:
            ret['error'] = u"Hasło i jego powtórzenie są różne"
            return ret 

        current_user.password = ret['form'].password.data
        if current_user.save():
            ret['success'] = u"Zmieniono hasło"
        else:
            ret['error'] = u"Coś poszło nie tak, nie można zmieńć hasła"
    
    return ret
Esempio n. 36
0
 def validate_current_password(self, field):
     if not current_user.check_password(field.data):
         raise wtforms.ValidationError('Wrong password')
Esempio n. 37
0
def username(username):
    Account = AccountFactory.get_model()
    acc = Account.pull(username)
    if acc is None:
        try:
            acc = Account.pull_by_email(username)
        except exceptions.NonUniqueAccountException:
            flash(
                "Permanent Error: these user credentials are invalid - please contact an administrator",
                "error")
            return redirect(url_for(("logut")))

    if acc is None:
        abort(404)

    # actions on this page are only availble to the actual user, or a user with the edit-users role
    if current_user.id != acc.id or not current_user.has_role(
            app.config.get("ACCOUNT_EDIT_USERS_ROLE")):
        abort(401)

    # if this is a request for the user page, just render it
    if request.method == "GET":
        fc = AccountFactory.get_user_formcontext(acc)
        return fc.render_template()

    is_delete = request.method == "DELETE" or (
        request.method == "POST"
        and request.values.get("submit", False) == "Delete")
    if is_delete:
        # validate the delete
        if not current_user.check_password(request.values.get("password")):
            flash("Incorrect password", "error")
            fc = AccountFactory.get_user_formcontext(acc=acc)
            return fc.render_template()

        # if the password validates, go ahead and do it
        acc.remove(
        )  # Note we don't use the DAO's delete method - this allows the model to decide the delete behaviour
        _do_logout()
        flash('Account {x} deleted'.format(x=username), "success")
        return redirect(
            url_for(app.config.get("ACCOUNT_LOGOUT_REDIRECT_ROUTE", "index")))

    if request.method == "POST":
        fc = AccountFactory.get_user_formcontext(acc=acc,
                                                 form_data=request.form)

        # attempt to validate the form
        if not fc.validate():
            flash("There was a problem when submitting the form", "error")
            return fc.render_template()

        # if the form validates, then check the legality of the submission
        try:
            fc.legal()
        except exceptions.AccountException as e:
            flash(e.message, "error")
            return fc.render_template()

        # if we get to here, then update the user record
        fc.finalise()

        # tell the user that everything is good
        flash("Account updated", "success")

        # end with a redirect because some details have changed
        return redirect(url_for("account.username", username=fc.target.email))
Esempio n. 38
0
def update_details():
    valid = True
    flashes = []

    if (
        flask.request.form['email'] != current_user.email and
        models.User.get_by_email(flask.request.form['email']) is not None
    ):
        flashes.append(u'That email address is already in use. ')
        valid = False

    if (
        'oldpassword' in flask.request.form and
        flask.request.form['oldpassword'] != ''
    ):
        if not current_user.check_password(flask.request.form['oldpassword']):
            flashes.append(u'Current password is incorrect')
            valid = False

        if (
            'password' not in flask.request.form or
            'confirm' not in flask.request.form or
            flask.request.form['password'] == '' or
            flask.request.form['password'] != flask.request.form['confirm']
        ):
            flashes.append(u'New passwords do not match')
            valid = False

        if len(flask.request.form['password']) < 8:
            flashes.append(u'Password must be at least 8 characters long')
            valid = False

    if (
        'firstname' not in flask.request.form or
        flask.request.form['firstname'] == ''
    ):
        flashes.append(u'First Name cannot be blank')
        valid = False

    if (
        'surname' not in flask.request.form or
        flask.request.form['surname'] == ''
    ):
        flashes.append(u'Surname cannot be blank')
        valid = False

    if (
        'email' not in flask.request.form or
        flask.request.form['email'] == ''
    ):
        flashes.append(u'Email cannot be blank')
        valid = False

    if (
        'phone' not in flask.request.form or
        flask.request.form['phone'] == ''
    ):
        flashes.append(u'Phone cannot be blank')
        valid = False

    if (
        'postcode' not in flask.request.form or
        flask.request.form['postcode'] == ''
    ):
        flashes.append(u'Postcode cannot be blank')
        valid = False

    location = models.Location.get_by_postcode(flask.request.form['postcode'])

    if not location:
        flashes.append(u'Postcode not recognised')
        valid = False

    if not valid:
        flash(
            (
                u'There were errors in your provided details. Please fix '
                u'these and try again'
            ),
            'error'
        )
        for msg in flashes:
            flash(msg, 'warning')
    else:
        current_user.firstname = flask.request.form['firstname']
        current_user.surname = flask.request.form['surname']
        current_user.location_id = location.id

        if flask.request.form['email'] != current_user.email:
            current_user.email = flask.request.form['email']
            current_user.email_verified = False
            current_user.email_verification_key = str(random.randint(100000, 999999))
            current_user.send_email_verification()

        if flask.request.form['phone'] != current_user.phone:
            current_user.phone = flask.request.form['phone']
            current_user.sms_verified = False
            current_user.sms_verification_key = str(random.randint(100000, 999999))
            current_user.send_sms_verification()

        if (
            'password' in flask.request.form and
            flask.request.form['password'] != ""
        ):
            current_user.set_password(flask.request.form['password'])

        database.DB.session.commit()

        flask.flash(u'Your details have been updated', 'success')

        return flask.redirect(flask.url_for('.index'))
Esempio n. 39
0
 def validate_old_password(form, field):
     if not current_user.check_password(field.data):
         raise ValidationError('Password is wrong.')
Esempio n. 40
0
 def validate_old_password(form,field):
     if not current_user.check_password(field.data):
         raise ValidationError('Verify password failed')
Esempio n. 41
0
 def _check_password(self):
     # we check the password of the logged in user, not the account (this allows for admins to set user passwords)
     return current_user.check_password(self.form.password.data)
Esempio n. 42
0
File: forms.py Progetto: sc4599/lebi
    def validate_password(self, field):
        if not current_user.check_password(field.data):
            raise ValidationError(u'原密码不正确!')

        if field.data == self.password.data:
            raise ValidationError(u'新密码不能与原密码一致')
Esempio n. 43
0
 def validate_old_password(self, field):
     if not current_user.check_password(field.data):
         raise ValidationError(u'原密码输入错误')
Esempio n. 44
0
 def validate_old_password(self, field):
     if not current_user.check_password(field.data):
         raise ValidationError(u'原密码输入错误')
Esempio n. 45
0
 def validate_old_password(form, field):
     if not current_user.check_password(field.data):
         raise ValidationError('Verify password failed')