简体   繁体   中英

Flask-Login logout_user does not change is_authenticated

I have a test for register/login/logout endpoints and it fails when I register a user, logout and try to login as registered user. For some reason in endpoint current_user.is_authenticated is still True after logout.

Endpoints code:

from flask import Blueprint, Response, request, current_app
from flask_security.core import current_user
from flask_security.utils import logout_user, login_user, verify_password
from flask_api import status
from core.database.user_models import User, USER_DATASTORE
from utils.responses import SUCCESS, BAD_REQUEST, NOT_FOUND

ACCOUNT_BP = Blueprint("account", __name__)

EMAIL_IS_REGISTERED = Response("Email Is Registered", status=status.HTTP_401_UNAUTHORIZED)
USER_INACTIVE = Response("User Is Inactive", status=status.HTTP_403_FORBIDDEN)
WRONG_CREDENTIALS = Response("Wrong Credentials", status=status.HTTP_401_UNAUTHORIZED)

@ACCOUNT_BP.route("/register", methods=['POST'])
def register_endpoint() -> Response:
    """
    # TODO: Fill this docstring.
    """
    if current_user.is_authenticated:
        return NOT_FOUND

    if "email" in request.form and "password" in request.form:
        if USER_DATASTORE.create_new_user(request.form["email"], request.form["password"]):
            user = User.find_by_email(request.form["email"])
            login_user(user, remember=True)
            return SUCCESS

        return EMAIL_IS_REGISTERED

    return BAD_REQUEST

@ACCOUNT_BP.route("/signin", methods=['POST'])
def signin_endpoint() -> Response:
    """
    # TODO: Fill this docstring.
    """
    if current_user.is_authenticated: # IT SHOULD BE False
        return NOT_FOUND

    if "email" in request.form and "password" in request.form:
        user = User.find_by_email(request.form["email"])
        if user and verify_password(request.form["password"], user.password):
            if user.active:
                login_user(user, remember=True)
                return SUCCESS

            return USER_INACTIVE

        return WRONG_CREDENTIALS

    return BAD_REQUEST


@ACCOUNT_BP.route("/logout")
def logout_endpoint() -> Response:
    if current_user.is_authenticated:
        logout_user()
        return SUCCESS

    return NOT_FOUND

Code for test:

import unittest
from flask import Response
from flask.testing import FlaskClient
from flask_security.core import current_user
from main import SERVER

def register(client: FlaskClient, email: str, password: str) -> Response:
    """Fast method for using ``/account/register`` endpoint"""
    form_data = 'email=' + email +'&password=' + password
    return client.post('/account/register', data=form_data, content_type='application/x-www-form-urlencoded')

def signin(client: FlaskClient, email: str, password: str) -> Response:
    """Fast method for using ``/account/signin`` endpoint"""
    form_data = 'email=' + email +'&password=' + password
    return client.post('/account/signin', data=form_data, content_type='application/x-www-form-urlencoded')

def logout(client: FlaskClient) -> Response:
    """Fast method for using ``/account/logout`` endpoint"""
    return client.get('/account/logout')

class UsersAccountTestCase(unittest.TestCase):
    """
    # TODO: Fill this docstring.
    """

    __REGISTER_SUCCESS_EMAIL = 'success@example.com'
    __RANDOM_PASSWORD = 'RandomPassword'

    def test_register_success(self):
        """
        # TODO: Fill this docstring.
        """
        with SERVER.test_client() as client:
            register_result = register(client, self.__REGISTER_SUCCESS_EMAIL, self.__RANDOM_PASSWORD)
            self.assertEqual(register_result.status_code, 200)
            self.assertEqual(register_result.get_data(as_text=True), "Success")
            self.assertTrue(current_user.is_authenticated)
            self.assertEqual(current_user.email, self.__REGISTER_SUCCESS_EMAIL)

            logout_result = logout(client)
            self.assertEqual(logout_result.status_code, 200)
            self.assertEqual(logout_result.get_data(as_text=True), "Success")
            self.assertFalse(current_user.is_authenticated) # THIS PASSES!

            check_result = signin(client, self.__REGISTER_SUCCESS_EMAIL, self.__RANDOM_PASSWORD)
            self.assertEqual(check_result.status_code, 200) # THIS RETURNS 404
            self.assertEqual(check_result.get_data(as_text=True), "Success")
            self.assertTrue(current_user.is_authenticated)
            self.assertEqual(current_user.email, self.__REGISTER_SUCCESS_EMAIL)
            logout(client)

What can possibly lead to this behavior?

UPDATE:

Just tested endpoints with Postman - everything works as intended.

This is the strangest issue I have ever seen. I changed return SUCCESS in registration endpoint to something else and it just worked.

也许只使用Flask-Login更容易使用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM