python - 为什么 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-class)UserMixin
中解释的所有必需属性和方法。在函数中,调用 后,我检查以验证是否登录了正确的用户。我还检查并返回,如预期的那样。login()
login_user()
current_user.id
current_user.is_anonymous
False
用户.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 中的声明性基础。任何帮助表示赞赏。
解决方案
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
将有助于确定。
推荐阅读
- laravel - 注册数据时多个数据库如何进入主数据库打开数据库连接?
- python - 如何在 MySQL 中连接值
- swift - 有没有办法在 SwiftUI 视图和与之间接相关的类之间有一个全局变量?
- operating-system - QEMU aarch64 Guest 尚未初始化显示(尚未)
- java - 检查循环结果的详细信息
- javascript - 如何在 Turbolinks 中使用 HTML 初始化 Flickity
- python - 如何在 Windows 中运行使用 pip 安装的程序?
- python - 如何将 R conda env 连接到 jupyter notebook
- r - 循环遍历列以删除 NA
- ios - 将 Xcode 中的搜索限制为自上次提交以来更改的行