Пример #1
0
def account():
    if current_user.is_authenticated:
        try:
            if (request.json['publicName']):
                current_user.public_name = request.json['publicName']
                db.session.commit()
                return jsonify('public name changed')
        except Exception:
            pass
        try:

            if (request.json['email']) and current_user.check_password(
                    request.json['password']):
                current_user.email = request.json['email']
                db.session.commit()
                return jsonify('email changed')
        except Exception:
            pass
        try:
            if (request.json['newPassword']) and current_user.check_password(
                    request.json['password']):
                current_user.set_password(request.json['newPassword'])
                db.session.commit()
                return jsonify('password changed')
        except Exception:
            pass
    else:
        return jsonify({'error': 'Not logged in'})
Пример #2
0
def user_settings():
    form = UserSettingsForm()
    del_form = UserDeleteForm()
    if form.submit.data and form.validate_on_submit():
        if not current_user.check_password(form.password.data):
            flash('Incorrect password.')
            return render_template('user_settings.html',
                                   form=form,
                                   del_form=del_form)
        if form.new_password.data:
            current_user.set_password(form.new_password.data)
            flash('Password updated.')
        if form.new_email.data:
            current_user.email = form.new_email.data.lower()
            flash('Email updated.')
        if form.new_username.data:
            current_user.username = form.new_username.data.strip()
            flash('Username updated.')
        db.session.commit()
        return redirect(url_for('user_settings'))
    if del_form.delete.data and del_form.validate_on_submit():
        if not current_user.check_password(del_form.delete_password.data):
            flash('Incorrect password.')
            return render_template('user_settings.html',
                                   form=form,
                                   del_form=del_form)
        current_user.clear_all_towers()
        db.session.delete(current_user)
        db.session.commit()
        logout_user()
        return redirect(url_for('index'))
    return render_template('user_settings.html',
                           form=form,
                           del_form=del_form,
                           user_settings_flag=True)
Пример #3
0
    def validate(self):
        initial_validation = super(EditPasswordForm, self).validate()
        if not initial_validation:
            return False

        if not current_user.check_password(self.old_password.data):
            self.old_password.errors.append(u'密码无效')
            return False

        if current_user.check_password(self.new_password.data):
            self.new_password.errors.append(u'密码不一致')
            return False

        return True
Пример #4
0
    def validate(self):
        initial_validation = super(EditPasswordForm, self).validate()
        if not initial_validation:
            return False

        if not current_user.check_password(self.old_password.data):
            self.old_password.errors.append('password error')
            return False

        if current_user.check_password(self.new_password.data):
            self.new_password.errors.append(
                'new password can not equal old one')
            return False

        return True
Пример #5
0
def testingaccount():
    username = current_user.username
    if request.method == "GET":
        return render_template('testingaccount.html', username_str=username)

    current_password = request.form["current_password"]
    if not current_user.check_password(current_password):
        return render_template('testingaccount.html',
                               username_str=username,
                               password_update_str="Incorrect Password")
    new_password = request.form["new_password"]
    confirm_new_password = request.form["confirm_new_password"]
    if new_password != confirm_new_password:
        return render_template(
            'testingaccount.html',
            username_str=username,
            password_update_str="The passwords do not match")

    user = UserDB.query.filter_by(username=username)[0]
    password_hash = generate_password_hash(new_password)
    user.password_hash = password_hash
    db.session.commit()
    return render_template(
        'testingaccount.html',
        username_str=username,
        password_update_str="Your password has been updated")
Пример #6
0
def edit_profile():
    if request.method == 'POST':
        realname = request.form.get('realname', '')
        username = request.form.get('username', '')
        old_password = request.form.get('old_password', '')
        new_password = request.form.get('new_password', '')

        if not filter_edit_form(realname, username, new_password):
            return redirect(url_for('home.edit_profile'))

        current_user.real_name = realname
        current_user.user_name = username

        if old_password != '' and new_password != '':
            if current_user.check_password(old_password) == True:
                current_user.secure_password(new_password)
            else:
                flash('error', 'Old password is incorrect.')
                return redirect(url_for('home.edit_profile'))

        db.session.add(current_user)
        db.session.commit()

        flash('success', 'Successfully update profile.')
        return redirect(url_for('home.edit_profile'))
    else:
        roles = Role.query.all()
        return render_template('home/edit_profile.html',
                               user=current_user,
                               roles=roles)
Пример #7
0
def register():
    election = maintenance.get_election()
    if election is None:
        flash(f'Wybory nie są aktywne.')
        return redirect(url_for('base.index'))
    elif not election.check_flag(ELECTION_REGISTER):
        flash(f'Rejestracja nie jest aktywna')
        return redirect(url_for('base.index'))

    form = RegisterForm()
    if form.validate_on_submit():
        if current_user.check_password(form.password.data):
            kmsid = form.kmsid.data
            log.debug(f'Trying to register candidate by kms id: {kmsid}')
            fellow = Fellow.query.filter_by(id=kmsid).first()
            log.info(f'Trying to register candidate: {fellow}')

            if not fellow.check_board(FELLOW_ACTIVE):
                log.warning(f'Candidate is not an active fellow: {fellow}.')
                flash(f'Kandydat nie jest aktywnym członkiem.')
                return redirect(url_for('base.index'))

            for position in election.positions.all():
                if position.is_registered(fellow):
                    log.warning(f'Candidate is already registered: {fellow}')
                    flash('Kandydat został już zarejestrowany.')
                    return redirect(url_for('base.index'))

            register_candidate(form, election)
            log.info(f'New candidate registered: {fellow}')
            flash('Kandydat zarejestrowany poprawnie.')
            return redirect(url_for('base.index'))
        else:
            flash('Podane hasło jest niepoprawne.')
    return render_template('dike/register.html', form=form)
Пример #8
0
    def validate(self):
        base_validation = super().validate()
        is_valid_current_password = current_user.check_password(
            self.current_password.data)
        is_valid_new_password = current_user.is_new_password(
            self.new_password.data)
        specials = set(string.punctuation)
        has_num = any(c.isdigit() for c in self.new_password.data)
        has_upper = any(c.isupper() for c in self.new_password.data)
        has_lower = any(c.islower() for c in self.new_password.data)
        has_special = any(c in specials for c in self.new_password.data)

        if not has_num:
            self.new_password.errors.append(
                "Your new password must contain at least 1 number.")
        if not has_upper:
            self.new_password.errors.append(
                "Your new password must contain at least 1 capital letter.")
        if not has_lower:
            self.new_password.errors.append(
                "Your new password must contain at least 1 lower case letter.")
        if not has_special:
            self.new_password.errors.append(
                "Your new password must contain at least 1 special character.")

        if not is_valid_new_password:
            self.new_password.errors.append(
                "Your new password cannot be the same as your current password or your last 3 passwords."
            )
        if not is_valid_current_password:
            self.current_password.errors.append("Incorrect password.")

        return (base_validation and is_valid_current_password
                and is_valid_new_password and has_num and has_upper
                and has_lower and has_special)
def my_account_change_password():
    form = ChangePasswordForm()

    if form.validate_on_submit():
        old_password = form.old_password.data.strip()
        new_password = form.new_password.data.strip()

        if current_user.check_password(old_password):
            if new_password:
                current_user.set_password(new_password)
                db.session.add(current_user)
                db.session.commit()
                flash("Please login with your new password")
                logout_user()

            else:
                flash("Invalid new password")

        else:
            flash("Old password is incorrect")

    else:
        flash("Error in password change form")

    return redirect(url_for('my_account'))
Пример #10
0
def mypage():
    form = MypageForm(request.form)
    msg = None
    if request.method == "POST":
        if current_user.check_password(form.cpassword.data):
            msg = ""
            if form.password.data:
                if len(form.password.data) < 4:
                    msg = "password - Field must be at least 4 characters long."
                    return render_template("mypage.html", msg = msg, form = form, entrance_type = config.entrance_type)
                elif form.password.data == form.confirm.data:
                    msg += "password "
                    current_user.set_password(form.password.data)
                else:
                    msg = "Passwords must match"
                    return render_template("mypage.html", msg = msg, form = form, entrance_type = config.entrance_type)
            if form.name.data and form.name.data != current_user.name:
                msg += "name "
            if msg:
                msg += "changed successfully"
            db_session.commit()
        else:
            msg = "wrong current password"

    return render_template("mypage.html", msg = msg, form = form, entrance_type = config.entrance_type)
Пример #11
0
def member_setting():
    """
    represents member setting page
    """

    real_name = request.form.get("real_name")
    user_name = request.form.get("user_name")
    email = request.form.get("email")
    phone = request.form.get("phone")
    old_password = request.form.get("old_password", "")
    new_password = request.form.get("new_password", "")

    try:
        current_user.set_real_name(real_name)
        current_user.set_user_name(user_name)
        current_user.set_phone_number(phone)
        current_user.set_email_address(email)

        if old_password != "" and new_password != "":
            if current_user.check_password(old_password):
                current_user.set_pass_word(new_password)
            else:
                raise Exception("password lama tidak benar")

        current_user.save()
    except Exception as Error:
        flash("error", Error.__str__())
    else:
        flash("success", "berhasil update profile")

    return redirect(url_for("index.index"))
Пример #12
0
def settings():
    avatars = {}
    for filename in os.listdir('static/avatars'):
        fullpath = 'avatars/' + filename
        avatars[fullpath] = True if fullpath == current_user.avatar else False
    if request.method == 'POST' and 'avatarForm' in request.form:
        user = db.session.query(User).filter_by(id=current_user.id).one()
        avatar = request.form['avatar']
        user.avatar = avatar
        db.session.commit()
        flash('Avatar image changed!', "success")
        return redirect(url_for('auth.settings'))
    form = SettingsForm(username=current_user.name,
                        email=current_user.email,
                        bio=current_user.bio)
    if form.validate_on_submit():
        if current_user.check_password(form.password.data):
            user = db.session.query(User).filter_by(id=current_user.id).one()
            user.name = form.username.data
            user.email = form.email.data
            user.bio = form.bio.data
            if form.new_password.data:
                user.set_password(form.new_password.data)
            db.session.commit()
            flash('Account settings updated!', "success")
            return redirect(
                url_for('home.profile',
                        user_id=current_user.id,
                        username=current_user.name))
        else:
            flash('Incorrect password!', "error")
    return render_template('settings.html',
                           current_user=current_user,
                           form=form,
                           avatars=avatars)
Пример #13
0
def changemail():
    """
	Change the email only when the user know his password.
	"""
    form = ChangeMailForm()
    if form.validate_on_submit():
        if current_user.check_password(form.password.data):
            user = current_user._get_current_object()
            user.email = form.new_email.data
            user.confirmed = False
            db.session.add(user)
            db.session.commit()

            token = user.generate_confirmed_token()
            send_mail(
                user.email,
                "Confirmed your email.",
                "/auth/mail/confirmed",
                user=user,
                token=token,
            )

            flash(
                "Please check the email that we sent to your new mailbox to update your account."
            )
            return redirect(url_for("main.index"))

        else:
            flash("Password error.")
            return redirect(url_for("auth.changemail"))

    return render_template("auth/changemail.html", form=form)
Пример #14
0
def cambiar_contrasena():
    form = ChangePasswordForm()
    if form.validate_on_submit():

        # Check the old password
        if current_user.check_password(form.old_password.data):

            # Check that new password is not the same as the old one
            if form.old_password.data == form.password.data:
                flash(Msg.Flash.SAME_AS_OLD_PASSWORD)
                # print("[DEBUG] User {} tried to change to same password.".format(
                #     current_user.email))
                return redirect(url_for("auth.cambiar_contrasena"))

        else:
            flash(Msg.Flash.INVALID_OLD_PASSWORD)
            # print("[DEBUG] Password change request, incorrect old password. User: {}".format(
            #     current_user.email))
            return redirect(url_for("auth.cambiar_contrasena"))

        # Check that the user curently signed in is still on the database
        user = User.get_user(email=current_user.email)
        if user is None:
            # print("[DEBUG] Password change request, user not found: {}".format(
            #     current_user.email))
            return redirect(url_for("error.not_found"))

        # No errors, proceed to commit changes to database
        user.password_hash = generate_password_hash(form.password.data)
        user.save()
        # print("[DEBUG] Password change from user {}.".format(user.email))
        flash(Msg.Flash.PASSWORD_CHANGE_SUCCESFUL)
        return redirect(url_for("main.index"))
    return render_template("auth/cambiar_contrasena.html", form=form)
Пример #15
0
def user_settings():
    to_logout = False
    form = UserSettingsForm()
    if request.method == 'GET':
        form.load_user_settings(current_user)
    if form.validate_on_submit():
        current_user.name = form.name.data
        form.email.data = current_user.email
        flash('Alterações enviadas com sucesso', 'success')
        if form.old_password.data != '':
            if current_user.check_password(form.old_password.data):
                current_user.password = form.new_password.data
                flash('Password alterada com sucesso', 'success')
                to_logout = True
            else:
                flash('Password Antiga errada', 'danger')
        db.session.add(current_user)
        db.session.commit()
    if to_logout:
        return redirect(url_for('main.logout'))
    return render_template(
        'settings.html',
        title='Definições',
        form=form,
        cur_page='settings'
    )
Пример #16
0
def edit():
    form = EditForm()
    if request.method == "GET":
        if current_user.img:
            img = decode_image(current_user.img)
        else:
            img = None
        return render_template("edit.html", form=form, img=img)
    else:
        img = request.files["change"]
        if form.validate_on_submit():
            if form.name.data:
                current_user.name = form.name.data
            if form.new_password.data:
                if current_user.check_password(form.old_password.data):
                    current_user.set_password(form.new_password.data)
            if img:
                current_user.img = img.read()
            db.session.commit()
            return redirect(url_for("account"))
        if img:
            current_user.img = img.read()
            db.session.commit()
            return redirect(url_for("account"))
        return redirect(url_for('account'))
Пример #17
0
def edit():
    # current_user = Account.query.first()
    form = FormEdit()
    target = current_user
    if request.method == 'POST':
        if form.validate_on_submit():
            pass_flag = True
            check_coll = Account.query.filter_by(email=form.email.data).first()

            # 驗證現在密碼是否正確
            if not current_user.check_password(form.current_password.data):
                pass_flag = False
                flash('Wrong password', 'danger')

            if pass_flag:
                # print(request.form)
                if form.nickname.data != '':
                    target.nickname = form.nickname.data
                if form.email.data != '':
                    target.email = form.email.data
                if form.password.data != '':
                    target.password = generate_password_hash(form.password.data)
                db.session.commit()
                flash('Succeed', 'success')

    return render_template('edit.html', form=form, target=target)
Пример #18
0
def init_form():
    print("load", list(request.args.keys()))
    for key in request.args.keys():
        print(key, request.args.get(key))
    print(current_user.fake_account)
    if str(current_user.fake_account) == "True":
        flash(
            "Het wachtwoord van 'Duckstad health centrum' is 'DonaldDuck123'.")
    form = GegevensCheck()
    if form.validate_on_submit():
        if not current_user.check_password(form.ww_current_user.data):
            flash("Uw eigen wachtwoord is fout.")
            redirect(url_for("forms.init_form"))

        if current_user.fake_account == "True":
            if form.ww_bezoekende.data is not "DonaldDuck123":
                flash("Het wachtwoord van de bezoekende praktijk is fout.")
                redirect(url_for("forms.init_form"))
        else:
            if not current_user.check_password_bezoekende_praktijk(
                    form.ww_bezoekende.data):
                flash("Het wachtwoord van de bezoekende praktijk is fout.")
                redirect(url_for("forms.init_form"))

        if form.alles_klopt.data:
            return redirect(url_for("forms.form_vragen/praktijk/0"))
        else:
            flash("Uw moet de gegevens bevestigen of wijzigen.")

    return render_template(
        "formulieren/init_form.html",
        title="Gegevens check",
        form=form,
        user=current_user,
    )
Пример #19
0
def delete():
    """Удаление профиля"""
    if not current_user.is_authenticated:  # если пользователь не авторизован
        return redirect(url_for('unauthorized_form.unauthorized'))
    if request.method == "GET":
        return render_template("delete_profile.html")
    elif request.method == "POST":
        # просим подтвердить удаление профиля вводом пароля
        password = request.form.get('password')
        # если пароли не совпадают
        if not current_user.check_password(password, current_user.name):
            return render_template('delete_profile.html',
                                   message="Пароли не совпадают")
        # а если совпали
        session = db_session.create_session()
        # удаляем все связи этого пользователя с книгами
        session.query(Relationship).filter(
            Relationship.user_id == current_user.id).delete()
        # и его статистику
        session.query(Statics).filter(
            Statics.user_id == current_user.id).delete()
        # удаляем самого пользователя
        session.query(User).filter(User.id == current_user.id).delete()
        session.commit()
        # сообщаем пользователю, что мы удалили его профиль
        return render_template('profile_is_delete.html')
Пример #20
0
def update_email(id):

    colleague, who, authorized = update_authorization(current_user, id)
    if not authorized:
        return unathorized("Only your own email can you change.", "error")

    form = UpdateEmailForm()

    if form.validate_on_submit():

        if not current_user.check_password(form.password.data):
            return unathorized("Invalid password. Please log in again.",
                               "warning")

        if colleague.email != form.email.data:
            # save confirmation code to the database and send email confirmation code to the new email:
            if not set_confirmation_code(colleague, form.email.data):
                redirect(url_for("login"))

            return redirect(url_for("confirm_email"))

        return redirect(url_for("profile", id=id))

    return render_template("update_email.html",
                           type="Email",
                           value=colleague.email,
                           placeholder=get_placeholder(colleague, current_user,
                                                       form),
                           form=form,
                           colleague=colleague,
                           avatar=get_avatar(colleague),
                           nav=get_nav(current_user))
Пример #21
0
def edit_profile():
    form = EditUserForm()
    if form.validate_on_submit():
        if current_user.check_password(form.password.data):
            email_not_in_use = User.query.filter_by(
                email=form.email.data).first() is None
            username_not_in_use = User.query.filter_by(
                username=form.username.data).first() is None
            email_is_correct = email_not_in_use or form.email.data == current_user.email
            username_is_correct = username_not_in_use or form.username.data == current_user.username
            if email_is_correct and username_is_correct:
                user = current_user
                user.username = form.username.data
                user.email = form.email.data
                db.session.commit()
                flash("Your profile was updated.", "success")
            else:
                flash("Error: email or username already in use!", "danger")
        else:
            flash("incorrect password", "danger")
        return redirect(url_for('main.edit_profile'))
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.email.data = current_user.email
    return render_template('main/edit_profile.html', form=form)
Пример #22
0
def settings():
    errors = {
        "old_password": None,
        "new_password": None,
        "new_password_repeat": None
    }
    if request.method == 'POST':
        old_password = request.form.get('oldPassword', '')
        new_password = request.form.get('newPassword', '')
        new_password_repeat = request.form.get('newPasswordRepeat', '')

        if current_user.check_password(old_password):
            errors["old_password"] = "******"

        print(new_password)
        if len(new_password) < 4:
            errors["new_password"] = "******"

        if new_password_repeat != new_password_repeat:
            errors["new_password_repeat"] = "adgangskoderne er ikke ens"

        if not any([type(x) == str for x in errors.values()]):
            current_user.set_password(new_password)
            db.session.commit()
            flash("Din adgangskode er blevet ændret", "primary")
            return redirect(url_for("view.settings"))

    return render_template("settings.html", errors=errors)
Пример #23
0
def edit_user() -> redirect:
    """
    Edit the user password
    :return: a redirect to the user page
    """

    if not current_user.is_admin:
        return render_template("authorisation_error.html", title="403")

    # Get the user-id from the url
    user_id = request.args.get("user-id")

    # Check if a user id is given in the url
    if not user_id:
        flash({"contend": "No user id was provided", "type": "bg-warning"})
        return redirect(url_for("admin.users"))

    if current_user.id != int(user_id) and not current_user.is_root:
        return render_template("authorisation_error.html", title="403")

    form = ChangePasswordForm()

    if form.confirmed_new_password.data == (None or "") and form.new_password.data == (None or "") \
            and form.current_password.data == (None or ""):
        flash({
            "contend": "You did not input all the required forms",
            "type": "bg-warning"
        })
        return redirect(url_for("admin.users") + f"?user-if={user_id}")

    # checks if all relevant data filed have been filled
    if current_user.check_password(form.current_password.data) or \
            (current_user.is_root and not current_user.id == int(user_id)):

        if form.new_password.data == form.confirmed_new_password.data:

            if not password_complex_enough(form.new_password.data):
                flash({
                    "contend":
                    "The password is not complex enough. (Upper + Lower + Digits)",
                    "type": "bg-warning"
                })

            user = User.query.filter(User.id == int(user_id)).first()
            user.set_password(form.confirmed_new_password.data)
            db.session.commit()
            return redirect(url_for("admin.users") + f"?user-id={user.id}")
        else:
            flash({
                "contend": "The passwords did not match",
                "type": "bg-warning"
            })
            return redirect(url_for("admin.users") + f"?user-id={user_id}")

    else:
        flash({
            "contend": "You provided the wrong password",
            "type": "bg-warning"
        })
        return redirect(url_for("admin.users") + f"?user-id={user_id}")
Пример #24
0
def change_old_password():
    db_sess = db_session.create_session()

    form = ChangePasswordOldPasswordForm()
    if form.validate_on_submit():
        if not current_user.check_password(form.password.data):
            return render_template(
                'changepasswordnotforgot.html',
                title='Change Password',
                form=form,
                user=current_user,
                userlist=get_userlist(),
                message="Incorrect password",
                params='Account settings',
                css_file=url_for('static', filename='css/style.css'),
            )
        return redirect('/new_password')

    return render_template('changepasswordnotforgot.html',
                           title='Change Password',
                           user=current_user,
                           url_for=url_for,
                           userlist=get_userlist(),
                           css_file=url_for('static',
                                            filename='css/style.css'),
                           params='Account settings',
                           form=form)
Пример #25
0
def delete_account(user_id):
    """route for editing username, email
    or password"""
    user = User.objects(pk=user_id).first()
    if user != current_user and current_user.username != 'admin':
        flash("You cannot delete someone else's profile!", "exclamation")
        return redirect(url_for('main.gallery', view='hot'))
    form = DeleteAccountForm()
    if form.validate_on_submit():
        # Complete password check before deletion (admin can enter admin
        # password)
        if not current_user.check_password(form.password.data):
            flash('Invalid Password', 'exclamation')
            return redirect(url_for('users.profile', username=user.username))
        else:
            if current_user.username != 'admin':
                # Logout user to home screen
                logout_user()
            # Delete stored cloudinary image for each of user's dogs
            dogs = Dog.objects(owner=user)
            for dog in dogs:
                dog.delete_dog_image(user.username, dog.pk)
            # Delete user (which will cascade delete dogs, comments, etc)
            user.delete()
            flash('Account deleted! Hope to see you again', 'check-circle')
            return redirect(url_for('main.index'))

    return render_template('user/delete_account.html',
                           user=user,
                           title='Delete Account',
                           form=form)
Пример #26
0
def user_profile():
    form = EditUserForm()
    db_sess = create_session()
    if request.method == 'POST' and form.validate_on_submit():
        if current_user.check_password(form.old_password.data):
            user = db_sess.query(User).get(current_user.id)
            if form.user_picture.data is not None:
                im = Image.open(form.user_picture.data)
                width, height = im.size
                if width > height:
                    corr = (width - height) // 2
                    im = im.crop((corr, 0, corr + height, height))
                elif width < height:
                    corr = (height - width) // 2
                    im = im.crop((0, corr, width, corr + width))
                im.save(f'./static/img/avatars/{user.id}.png')
                user.picture_path = f'img/avatars/{user.id}.png'
            user.name = form.name.data
            user.email = form.email.data
            db_sess.commit()
        else:
            return render_template(
                'user_profile.html',
                form=form,
                message='Введённый пароль не совпадает со старым паролем')
    elif request.method == 'POST' and not form.validate_on_submit():
        return render_template('user_profile.html',
                               form=form,
                               message='Введите правильный email')
    return render_template('user_profile.html', form=form)
Пример #27
0
def mypage():
    form = MypageForm(request.form)
    msg = None
    if request.method == "POST":
        if current_user.check_password(form.cpassword.data):
            msg = ""
            if form.password.data:
                if len(form.password.data) < 4:
                    msg = "password - Field must be at least 4 characters long."
                    return render_template("mypage.html",
                                           msg=msg,
                                           form=form,
                                           entrance_type=config.entrance_type)
                elif form.password.data == form.confirm.data:
                    msg += "password "
                    current_user.set_password(form.password.data)
                else:
                    msg = "Passwords must match"
                    return render_template("mypage.html",
                                           msg=msg,
                                           form=form,
                                           entrance_type=config.entrance_type)
            if form.name.data and form.name.data != current_user.name:
                msg += "name "
            if msg:
                msg += "changed successfully"
            db_session.commit()
        else:
            msg = "wrong current password"

    return render_template("mypage.html",
                           msg=msg,
                           form=form,
                           entrance_type=config.entrance_type)
Пример #28
0
 def post(self, data):
     if current_user.check_password(data["old_password"]):
         current_user.password = data["new_password"]
         current_user.update_at = time_utcnow()
         current_user.save()
         return current_user.to_dict(get_token())
     raise APIException("invalid credential", 401)
Пример #29
0
def login():
    """Allows users to login"""

    args = parser.parse(user_args, request)

    user = User.query.filter_by(username=args["username"]).first()

    if user is None:
        user = User(username=str(args["username"]), email=str(args["email"]))
        user.set_password(args["password"])
        db.session.add(user)
        db.session.commit()

        login_user(user, remember=True)
        return jsonify({
            "msg": f"Successfully created user with username {user.username}",
            "User": user.asdict(),
        })

    login_user(user, remember=True)
    if not current_user.check_password(args["password"]):
        return jsonify("The password you entered was invalid.")

    if current_user.is_authenticated:
        return redirect("/mood")
Пример #30
0
def change_password():
    form = ChangePasswordForm()

    if form.validate_on_submit():
        if current_user.check_password(form.current.data):
            current_user.set_password(form.new_1.data)

            flash("Successfully changed password", "success")
            log = SystemLog(request.remote_addr, current_user.email,
                            "Successfully changed password")
            db.session.add(log)
            db.session.commit()
            return redirect(url_for('index'))
        else:
            flash("Current password incorrect", "danger")
            log = SystemLog(
                request.remote_addr, current_user.email,
                "Failed password change attempt (current password incorrect)")
            db.session.add(log)
            db.session.commit()
            return redirect(url_for('change_password'))

    return render_template('change_password.html',
                           title="Change Password",
                           form=form)
Пример #31
0
def settings():
    """Страница настроек пользователя."""
    form = NewPasswordForm()
    if form.validate_on_submit():
        if current_user.check_password(form.old_password.data):
            if form.old_password.data != form.new_password.data:
                res = requests.put('http://localhost:{}/api_users/{}'.format(
                    PORT, current_user.id),
                                   json={
                                       'login': current_user.login,
                                       'name': current_user.name,
                                       'surname': current_user.surname,
                                       'age': current_user.age,
                                       'about': current_user.about,
                                       'friends': current_user.friends,
                                       'password': form.new_password.data
                                   }).json()
                if 'success' in res:
                    return render_template('settings.html',
                                           title='Настройки',
                                           form=form,
                                           message='Пароль успешно изменён')
                return render_template('settings.html',
                                       title='Настройки',
                                       form=form,
                                       error=res['message'])
            return render_template('settings.html',
                                   title='Настройки',
                                   form=form,
                                   error='Старый и новый пароли совпадают!')
        return render_template('settings.html',
                               title='Настройки',
                               form=form,
                               error='Неверный пароль')
    return render_template('settings.html', title='Настройки', form=form)
Пример #32
0
 def password(form):
     password = form.password.data
     password_n = form.password_n.data
     if current_user.check_password(password):
         current_user.password = current_user.set_password(password_n)
         db.session.commit()
         logout_user()
         return True
     return False
Пример #33
0
def password_setting():
    old_pwd = request.form["old_password"]
    new_pws = request.form["new_password"]
    if current_user.check_password(old_pwd):
        current_user.password = new_pws
        current_user.save()
        flash("密码修改成功", "success")
    else:
        flash("密码修改失败", "error")
    return redirect(url_for(request.args["next"]))
Пример #34
0
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.check_password(form.old_password.data):
            current_user.password = form.password.data
            current_user.save()
            flash('Your password has been updated.')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid password.')
    return render_template("auth/change_password.html", form=form)
Пример #35
0
def change_password():
    form = forms.ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.check_password(form.password.data):
            current_user.password = form.new_password.data
            current_user.session.add(current_user)
            logout_user()
            flash('密码修改成功,请重新登录。')
            return redirect(url_for('auth.login'))
        flash('原密码输入错误!')
    return render_template('auth/change_password.html', form=form)
Пример #36
0
def edit_password():
    form = EditPasswordForm()
    if form.validate_on_submit():
        if current_user.check_password(form.old_password.data):
            current_user.password = form.new_password.data
            db.session.add(current_user._get_current_object())
            db.session.commit()
            return redirect(url_for('main.user', username=current_user.username))
        else:
            flash('you input the wrong password')
            return redirect(url_for('main.edit_password'))
    return render_template('main/edit_password.html', form=form)
Пример #37
0
def reauth():
    """Reauthenticates a user."""
    if not login_fresh():
        form = ReauthForm(request.form)
        if form.validate_on_submit():
            if current_user.check_password(form.password.data):
                confirm_login()
                flash(_("Reauthenticated."), "success")
                return redirect_or_next(current_user.url)

            flash(_("Wrong password."), "danger")
        return render_template("auth/reauth.html", form=form)
    return redirect(request.args.get("next") or current_user.url)
Пример #38
0
def changepassword():
    form = ChangePasswordForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            oldpassword = form['oldpassword'].data
            password = form['password'].data
            if not current_user.check_password(oldpassword):
                flash('Current password incorrect', 'error')
            else:
                current_user.set_password(password)
                current_user.save()
                flash('Password successfully changed')
                return redirect(url_for('index'))
    return render_template('changepassword.html', form=form)
Пример #39
0
def change_email():
    form = forms.ChangeEmailForm()
    if form.validate_on_submit():
        if current_user.check_password(form.password.data):
            current_user.email = form.email.data
            current_user.confirmed = False
            current_user.session.add(current_user)
            token = options.dump_token('change_email', current_user.id)
            options.send_email(
                current_user.email, '验证邮箱', 'auth/mail/confirm',
                user=current_user,
                url=url_for('auth.new_confirm', token=token, _external=True))
            flash('邮箱修改成功,一封新验证邮件已发送到您的新邮箱。')
            return redirect(url_for('auth.unconfirmed'))
        flash('密码错误!')
    return render_template('auth/change_email.html', form=form)
Пример #40
0
    def validate(self):
        """Additional validation for `password_old` and `password` fields"""

        success = super(UserDetailsForm, self).validate()

        # If both a new password and the old password was specified
        if self.password.data and self.password_old.data:
            if not current_user.check_password(self.password_old.data):
                self.password_old.errors.append(_("Invalid current password"))
                success = False

        # If only the new password was specified
        elif self.password.data and not self.password_old.data:
            self.password_old.errors.append(_("You must specify your current password"))
            success = False

        return success
Пример #41
0
def password():
    form = PasswordForm()
    if form.validate_on_submit() and request.method == "POST":
        password = form.password.data
        password_n = form.password_n.data
        if current_user.check_password(password):
            current_user.password = current_user.set_password(password_n)
            db.session.commit()
            logout_user()
            return redirect(url_for('auth.login'))
        else:
            flash('password is error')
            return redirect(url_for('setting.password'))
    else:
        if form.errors:
            flash_errors(form)
            return redirect(url_for('setting.password'))
        else:
            return render_template('setting/password.html', form=form)
Пример #42
0
def flash_default_password():
    if current_user.check_password("root"):
        flash("You still use the default password. Please change it.", "info")
Пример #43
0
 def validate_oldpassword(self, field):
     if self.oldpassword.data:
         if not current_user.check_password(self.oldpassword.data):
             raise ValidationError("Password does not match")
Пример #44
0
def index():
    if current_user.check_password("root"):
        flash("You still use the default password. Please change it.", "info")
    return render_template("index.html")
Пример #45
0
 def validate_old_password(self, filefield):
     if not current_user.check_password(filefield.data):
         raise ValidationError('Senha incorreta')
Пример #46
0
 def validate_old_password(self, field):
     if not current_user.check_password(field.data):
         raise ValidationError(_("Old Password is wrong."))
Пример #47
0
 def validate_old_password(self, field):
     if not current_user.check_password(self.old_password.data):
         raise ValidationError("Wrong old password")