def signup():
    """
    GET returns the template for the signup page, when the form is submitted the data is sent back
    to the endpoint using POST which creates a new user.
    """

    form = SignUpForm()
    if form.validate_on_submit():
        if not User.check_unique_username(form.username.data):
            flash("A user already exists with that username.")
        elif not User.check_unique_email(form.email.data):
            flash("A user already exists with that email address.")
        else:
            user = User()
            user.username = form.username.data
            user.email = form.email.data
            user.password = bcrypt.generate_password_hash(
                form.password.data).decode("utf-8")

            db.session.add(user)
            db.session.commit()

            login_user(user)

            return redirect(url_for("users.dashboard"))

    return render_template("signup.html", form=form)
예제 #2
0
def edit_user_account_details():
    """
    GET returns the template for the edit account page, when the form is submitted the data is
    sent back to the endpoint using POST which updates the users account data.
    """

    form = EditUserAccountForm()
    if form.validate_on_submit():
        if current_user.username != form.username.data and not User.check_unique_username(
                form.username.data):
            flash("A user already exists with that username.")
        elif current_user.email != form.email.data and not User.check_unique_email(
                form.email.data):
            flash("A user already exists with that email address.")
        elif form.new_password.data and not current_user.check_password(
                form.current_password.data):
            flash("Your current password is incorrect.")
        else:
            user = User.query.filter_by(id=current_user.id)

            data = {}
            if form.username.data:
                data["username"] = form.username.data
            if form.email.data:
                data["email"] = form.email.data
            if form.confirm_password.data:
                data["password"] = bcrypt.generate_password_hash(
                    form.confirm_password.data).decode("utf-8")

            fields = user_schema.load(data, partial=True)

            user.update(fields)
            db.session.commit()

            flash("Account details updated successfully.")
            return redirect(url_for("users.get_user_account_details"))

    # Prepopulate the form with existing data
    form.username.data = current_user.username
    form.email.data = current_user.email

    return render_template("account_edit.html", form=form)