首页 > 解决方案 > 为什么 Flask-Login current_user.is_authenticated 不一致?

问题描述

我有一个 Angular 应用程序正在对后端 Flask 应用程序进行 API 调用。Flask 应用程序在用户登录时使用 Flask-Login 对用户进行身份验证。当用户使用login()我定义的函数登录时,current_user.is_authenticated返回True. 当我调用另一个函数时get_is_logged_in()current_user.is_authenticated返回False

我的User类继承自,因此它具有文档( https://flask-login.readthedocs.io/en/latest/#your-user-classUserMixin中解释的所有必需属性和方法。在函数中,调用 后,我检查以验证是否登录了正确的用户。我还检查并返回,如预期的那样。login()login_user()current_user.idcurrent_user.is_anonymousFalse

用户.py

from sqlalchemy import Column, String, Text, Integer
from flask_login import UserMixin
from .database import Base, Session

class User(Base, UserMixin): # Inherits UserMixin
    __tablename__ = "USER"

    id = Column(Integer, primary_key=True)
    email = Column(String(450), unique=True, nullable=False)
    first_name = Column(String, nullable=False)
    last_name = Column(String, nullable=False)
    password = Column(Text, nullable=False)

    def __init__(self, email, first_name, last_name, password):
        self.email = email
        self.first_name = first_name
        self.last_name = last_name
        self.password = password

数据库.py

from sqlalchemy import create_engine, Column, String, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import pymssql

db_url = "DB_URL"
db_name = "DB_NAME"
db_user = "DB_USER"
db_password = "DB_PW"
engine = create_engine(f'mssql+pymssql://{db_user}:{db_password}@{db_url}/{db_name}')
Session = sessionmaker(bind=engine)
Base = declarative_base()

主文件

from flask import Flask, jsonify, request
from flask_login import LoginManager, login_user, login_required, 
logout_user, current_user
from .entities.database import Session, engine, Base
from .entities.user import User

import json    
# Other necessary imports

@login_manager.user_loader
def load_user(user_id):
    return Session().query(User).filter_by(id=user_id).first()

@app.route('/api/login', methods=['POST'])
def login():
    try:
        posted_email = request.json['email'].lower()
        posted_password = request.json['password']
        user_json = get_user_by_email(posted_email)

        if not bcrypt.check_password_hash(user_json.get_json() ['password'], posted_password): # The password was incorrect
            return jsonify(success=False, message='The password is incorrect')
        else: # The login was successful, so pass in all user credentials (except password)
            # Get user object from the database
            user = load_user(1) # Hard-coded id for testing

            # Login the user
            login_user(user, remember=False, force=True)

            return jsonify(
                success=True,
                user=current_user.is_authenticated # Returns True
                )
    except KeyError: # A KeyError is only thrown if the user does not exist
        return jsonify(success=False, message='A user with that email does not exist')

@app.route('/api/isLoggedIn', methods=['POST'])
def get_is_logged_in():
    return jsonify(success=current_user.is_authenticated) # Returns False when called

请注意,我使用的是 SQLAlchemy 中的声明性基础。任何帮助表示赞赏。

标签: pythonflaskflask-sqlalchemyflask-login

解决方案


return jsonify(
        success=True,
        user=current_user.is_authenticated # Returns True
        )

这将始终返回 true,因为success = True无论current_user.is_authenticated

我没有看到你get_is_logged_in在任何地方调用,但它返回 false 的最明显原因是因为current_user.is_authenticated实际上不等于True函数被调用的时间,因此你设置success为 false。

您调用的代码片段get_is_logged_in将有助于确定。


推荐阅读