Forums

Flask_logout not working as it should

Hello, i have Flask Web-App where i'm using flask_login.

My problem is that all of a sudden current_user.is_authenticated keeps regaining it's authenticated status when i use logout_user. When i logout from the mainpage, i am redirected to the login-page. On the login-page i have this code-snippet to send me to the mainpage if i'm already logged in:

# Bypass if user is logged in
if current_user.is_authenticated:
    return redirect(url_for('mainpage'))

It is all working as intended on my local machine and was working perfectly the last time i updated the code on pythonanywhere. Now when i logout, it seems as if i get logged out correctly. I tested it by putting print statements before and after the logout with:

print(f"User before: {current_user.get_id()}, {current_user.is_authenticated}")

I did the same on the login-page at the beginning:

print(f"---Login, user authenticated? {current_user.is_authenticated}, {current_user.get_id()}")

and that's what i get in the log:

2022-02-01 12:25:37 User before: 1, True
2022-02-01 12:25:37 User after: None, False
2022-02-01 12:25:37 ---Login, user authenticated? True, ID: 1

So what's happening here? I got a paid account and was thinking it might have something to do with the workers? That i'm logging off on worker 1, but for worker 2, who probably handles the login-site i'm still logged in? I don't get it.

My logout-route:

@app.route('/logout')
@login_required
def logout():
    """User log-out logic."""
    logout_user()
    return redirect(url_for('auth_bp.login'))

My login-route:

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    """
    Log-in page for registered users.

    GET requests serve Log-in page.
    POST requests validate and redirect user to dashboard.
    """
    # Bypass if user is logged in
    if current_user.is_authenticated:
        return redirect(url_for('mainpage'))

    form = LoginForm()
    # Validate login attempt
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and user.check_password(password=form.password.data):
            login_user(user)
            next_page = request.args.get('next')
            return redirect(next_page or url_for('mainpage'))
        flash('Wrong username or password')
        return redirect(url_for('auth_bp.login'))
    return render_template(
        'login.jinja2',
        form=form,
        title='Login.',
        template='login-page'
    )

I found the problem: somehow i had 2 identical cookies for the session instead of one. I guess i have to dive into flask_login and cookie management.

Glad you figured that out!