Once a message is sent through a Socket.IO connection from client (JS) to server (django/python) using django-socketio, is it possible to figure out which user was authenticated when the page was rendered?
In this case the view is being served up by django and it requires authentication — normally on the server I would be able to do user = request.user, but in the events.py file the request.user just returns an AnonymousUser object. This makes sense because the websocket server is an entirely separate process than the django web server, and thus the user has not authenticated on that socket connection.
I’m thinking I’ll have to come up with some clever code to embed the user ID into the message that is being sent to the server, and in that case I would need to add some handshaking to ensure that the end user cannot spoof it.
Has anyone come up with a clever solution to this problem?
Found my own solution to this issue. The trick is to add the
session_keyfrom the djangorequestobject into the django-socketio message before you send it up to the server; then back on the server-side you can resolve thesession_keyback to a User object. Here is the code:Template file: (served up by django server)
events.py: (processed by django-socketio server)
Profit!