Flask-login causing login form to not validate

Issue

The login form of my flask app is failing to validate (form.valididate = false) when the app has automatically logged users out:

app.permanent_session_lifetime = timedelta(minutes=5)

form.errors returns an empty dictionary {}.

Any ideas what is going on?

Login route below. When the user has been automatically logged out the code beneath ‘if form.validate_on_submit…’ is completely bypassed.

@view.route('/Login', methods=['GET', 'POST'])
def login():

    if current_user.is_authenticated and current_user.is_suspended != True:
        return redirect(url_for('view.Index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('view.login'))

        if user.is_suspended and user.check_password(form.password.data):
            flash('Your login has been suspended. Please contact NZGBC.')
            return redirect(url_for('view.login'))

        user.session_token = user.generate_session_token()
        db.session.commit()

        login_user(user, remember=form.remember_me.data)

        if form.remember_me.data is not True:
            app.permanent_session_lifetime = timedelta(minutes=60)
        else:
            app.permanent_session_lifetime = timedelta(days=365)
        
        next = request.args.get('next')
        # is_safe_url should check if the url is safe for redirects.
        # See http://flask.pocoo.org/snippets/62/ for an example.
        if not is_safe_url(next):
            return abort(400)

        return redirect(next or url_for('view.Index'))

    return render_template('login.html', highlight='11', title='Sign In', form=form)

Solution

According to your comment:

Obliously after using the CSRF token for submitting a form it will fail, since CSRF tokens are 1-time use.

Try doing this as a workaround in your login route:

try:
    if form.validate_on_submit():
    # ... process your form normally ...
except:
    return redirect(url_for('view.login'))
    # ... maybe display a message for the user to reenter his creds because he was logged out ...

This should work as a viable fix for your problem.

Answered By – SLDem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published