Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current user from a Django Channels web socket packet?

I was following this tutorial: Finally, Real-Time Django Is Here: Get Started with Django Channels.

I wanted to extend the app by using Django User objects instead of the handle variable. But how can I get the current user from the received WebSocket packet in my ws_recieve(message) function?

I noticed that both the csrftoken and the first ten digits of sessionid from the web socket packet match a normal HTTP request. Can I get the current user with this information?

For reference the received packet looks like this:

{'channel': <channels.channel.Channel object at 0x110ea3a20>,
 'channel_layer': <channels.asgi.ChannelLayerWrapper object at 0x110c399e8>,
 'channel_session': <django.contrib.sessions.backends.db.SessionStore object at 0x110d52cc0>,
 'content': {'client': ['127.0.0.1', 52472],
             'headers': [[b'connection', b'Upgrade'],
                         [b'origin', b'http://0.0.0.0:8000'],
                         [b'cookie',
                          b'csrftoken=EQLI0lx4SGCpyTWTJrT9UTe1mZV5cbNPpevmVu'
                          b'STjySlk9ZJvxzHj9XFsJPgWCWq; sessionid=kgi57butc3'
                          b'zckszpuqphn0egqh22wqaj'],
                         [b'cache-control', b'no-cache'],
                         [b'sec-websocket-version', b'13'],
                         [b'sec-websocket-extensions',
                          b'x-webkit-deflate-frame'],
                         [b'host', b'0.0.0.0:8000'],
                         [b'upgrade', b'websocket'],
                         [b'sec-websocket-key', b'y2Lmb+Ej+lMYN+BVrSXpXQ=='],
                         [b'user-agent',
                          b'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) '
                          b'AppleWebKit/602.1.50 (KHTML, like Gecko) Version'
                          b'/10.0 Safari/602.1.50'],
                         [b'pragma', b'no-cache']],
             'order': 0,
             'path': '/chat-message/',
             'query_string': '',
             'reply_channel': 'websocket.send!UZaOWhupBefN',
             'server': ['127.0.0.1', 8000]},
 'reply_channel': <channels.channel.Channel object at 0x110ea3a90>}
like image 469
user1577434 Avatar asked Oct 12 '16 18:10

user1577434


1 Answers

Updated answer in 2018 via the docs:

To access the user, just use self.scope["user"] in your consumer code:

class ChatConsumer(WebsocketConsumer):

    def connect(self, event):
        self.user = self.scope["user"]

    def receive(self, event):
        username_str = None
        username = self.scope["user"]
        if(username.is_authenticated()):
            username_str = username.username
            print(type(username_str))
            #pdb.set_trace() # optional debugging
like image 173
Scott Skiles Avatar answered Sep 22 '22 17:09

Scott Skiles