1

As the title says I have been trying to reference the current_user object in a SocketIO event as seen below:

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    fs_uniquifier = db.Column(db.String(255), unique=True, nullable=False)

@socketio.on('connect')
@socketio.on('login')
def on_connect():
    print("Client connected")
    print("Current user ID:", current_user.id)
    print("SocketIO Session ID:", request.sid)

The connection is created prior to user login so I have attempted to integrate flask-session in order to keep the current_user object up to date after user login and I have added a post login hook in order to verify the user is in fact logged in:

app.config['SESSION_TYPE'] = 'filesystem'
socketio = SocketIO(app, manage_session=False)
sess = Session(app)

@user_logged_in.connect_via(app)
def _after_login_hook(sender, user, **extra):
    print("ID of the user that just logged in:", user.id)

This is the current output I am getting when first connecting to the app:

Client connected
Current user ID: None
SocketIO Session ID: WyOkORnDbLjSrXUDAAAD

The None value for the current user is expected because up to this point the user has not logged in and therefore we are getting the AnonymousUser object. The issue is that after user login I am still receiving a None value:

ID of the user that just logged in: 2
Client connected
Current user ID: None
SocketIO Session ID: WyOkORnDbLjSrXUDAAAD

Any thoughts as to why I might be getting the AnonymousUser object after successful login would be greatly appreciated.

Flask==1.1.2
Flask-Login==0.5.0
Flask-Security-Too==3.4.5
Flask-SocketIO==5.0.1
Flask-Session==0.3.2
1ntel0pe
  • 33
  • 4
  • I don't understand how your login works. If the Socket.IO connection is done before login, then how does the user log in without breaking the connection? Are you using asynchronous requests? Because if not, when the client submits the login form the page will go away and your Socket.IO will go away with it. Socket.IO cannot survive a page page. – Miguel Grinberg Feb 01 '21 at 12:12
  • @Miguel yes we are using asynchronous requests and the frontend is built as a single page application. Therefore the browser is not having to navigate after login and the connection isn't broken. The odd part though is that even after login and intentionally breaking the session by refreshing you still don't get the proper current user. – 1ntel0pe Feb 02 '21 at 05:37
  • The only thing I can offer is that you test this with the session example in the Flask-SocketIO repository. That is a test application that allows you to change the session and connect / disconnect socketio to learn how the session data is shared between HTTP and Socket.IO. – Miguel Grinberg Feb 02 '21 at 09:50

0 Answers0