Getting user in django-socketio

As soon as a message is sent via a Socket.IO connection from the client (JS) to the server (django / python) using django-socketio, can I find out which user was authenticated when the page was displayed?

In this case, the view is processed by django and requires authentication - usually on the server I could execute user = request.user , but in the events.py file request.user just returns an AnonymousUser object. This makes sense because the websocket server is a completely separate process than the django web server, and thus the user did not authenticate this socket connection.

I think I will have to come up with some kind of smart code to insert the user ID into the message sent to the server, in which case I will need to add some kind of handshake to make sure that the end user cannot fool him.

Has anyone come up with a smart solution to this problem?

+4
source share
2 answers

I found my solution to this problem. The trick is to add session_key from the django request object to the django-socketio message before sending it to the server; then back to the server side, you can allow session_key to return to the User object. Here is the code:

Template file: (served by django server)

 <input type="hidden" id="session_key" value="{{ request.session.session_key }}"> ... <script type="text/javascript" charset="utf-8"> function someHandler(action, post_id, some_val){ var data = { 'action': action, 'post_id': post_id, 'value': some_val, 'session_key': $("#session_key").val() }; socket.send(data); } </script> 

events.py: (processed by django-socketio server)

 from django.contrib.sessions.models import Session from django.contrib.auth.models import User def message(request, socket, context, message): session = Session.objects.get(session_key=message['session_key']) uid = session.get_decoded().get('_auth_user_id') user = User.objects.get(pk=uid) 

Profit!

+4
source

To avoid unnecessary hits in the database in response, you can use Django cached sessions . This includes setting memcached and changing the SESSION_ENGINE parameter to use the caching backend of your choice.

0
source

All Articles