У меня есть приложение Angular, которое выполняет вызовы API серверного приложения Flask. Приложение Flask использует Flask-Login для аутентификации пользователей при входе в систему. Когда пользователь входит в систему с помощью определенной мной функции login(), current_user.is_authenticated возвращает True. Когда я вызываю другую функцию с именем get_is_logged_in(), current_user.is_authenticated возвращает False.
Класс My User наследуется от UserMixin, поэтому он имеет все необходимые свойства и методы, как описано в документации (https://flask-login.readthedocs.io/en/l ... user-class). В функции login() после вызова login_user() я проверил current_user.id, чтобы убедиться, что в систему входит правильный пользователь. Я также проверил current_user.is_anonymous, и он вернул False, как и ожидалось.
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. Любая помощь приветствуется.
У меня есть приложение Angular, которое выполняет вызовы API серверного приложения Flask. Приложение Flask использует Flask-Login для аутентификации пользователей при входе в систему. Когда пользователь входит в систему с помощью определенной мной функции login(), current_user.is_authenticated возвращает True. Когда я вызываю другую функцию с именем get_is_logged_in(), current_user.is_authenticated возвращает False.
Класс My User наследуется от UserMixin, поэтому он имеет все необходимые свойства и методы, как описано в документации (https://flask-login.readthedocs.io/en/latest/#your-user-class). В функции login() после вызова login_user() я проверил current_user.id, чтобы убедиться, что в систему входит правильный пользователь. Я также проверил current_user.is_anonymous, и он вернул False, как и ожидалось.
user.py
[code]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"
[code]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
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 [/code]
Обратите внимание, что я использую декларативную базу из SQLAlchemy. Любая помощь приветствуется.