Flask-Middleware / flask-security

Quick and simple security for Flask applications
MIT License
624 stars 155 forks source link

Error / Confirmation message not showing #890

Closed mominur-helios closed 7 months ago

mominur-helios commented 7 months ago

I have override the registration view. Registration is working but the problem is if there is any error the error is not showing in the template. Error is showing when I use the default register view but after override it's not showing. This is my view

@app.route('/register', methods=['GET', 'POST'])
def register():
    roles = Config.USERS_ROLES
    form = RegisterForm()
    if request.method == 'POST':
        selected_role_value = request.form['roles']
        selected_role = next((role for role in roles if role['value'] == selected_role_value), None)

        app.security.datastore.find_or_create_role(
            name=selected_role['value'], permissions=selected_role['permissions']
        )
        db.session.commit()
        if not app.security.datastore.find_user(email=form.email.data):
            if form.password.data == form.password_confirm.data:
                user = app.security.datastore.create_user(
                    email=form.email.data,
                    password=hash_password(form.password.data), roles=[selected_role['value']]
                )
                if Config.SECURITY_SEND_REGISTER_EMAIL:
                    confirmation_link, token = generate_confirmation_link(user)

                    send_mail(
                        Config.EMAIL_SUBJECT_REGISTER,
                        user.email,
                        "welcome",
                        user=user,
                        confirmation_link=confirmation_link,
                        confirmation_token=token,
                    )
                db.session.commit()
                return redirect(url_for('login'))

            else:
                print("Password doesn't match")
        else:
            print("User already exits")

    return render_template('security/register_user.html', register_user_form=form, roles=roles, segment='register')
jwag956 commented 7 months ago

couple things: 1) I don't see in your code that you are validating the form 2) You are taking input directly from a user and creating a role? Seems pretty dangerous 3) if you want to add roles as part of registration - rather than override the view - set up a user_registered signal handler and do it there. That way you get all the validation benefits and code - the user will already be created - you can add roles there.

For general questions - please use 'discussions' or https://stackoverflow.com/questions/tagged/flask-security