[Solved]-How to get current user from a Django Channels web socket packet?

6đź‘Ť

âś…

Note: The question is specific to Channels 1.x and the Django session system, if you’re here for Channels 2.x way, please read the docs from the link below, they’re more than clear on how to do this, the Channels 1.x docs were confusing for some people (including me), this is why this question and others were made, the Channels 2.x docs are crystal clear on how to achieve this:
https://channels.readthedocs.io/en/latest/topics/authentication.html#django-authentication


Channels 1.x:

You can get access to a user and http_session attributes of your message by changing the decorators in consumers.py to match the docs:

You get access to a user’s normal Django session using the http_session decorator – that gives you a message.http_session attribute that behaves just like request.session. You can go one further and use http_session_user which will provide a message.user attribute as well as the session attribute.

so the consumers.py file in the example should become the following:

from channels.auth import http_session_user, channel_session_user, channel_session_user_from_http  

@channel_session_user_from_http  
def ws_connect(message):  
    ...  
    ...


@channel_session_user  
def ws_receive(message):  
    # You can check for the user attr like this  
    log.debug('%s', message.user)  
    ...  
    ...  


@channel_session_user  
def ws_disconnect(message):  
    ...  
    ...  

Notice the decorators change.
Also, i suggest you don’t build anything upon that example

for more details see: https://channels.readthedocs.io/en/1.x/getting-started.html#authentication

👤HassenPy

9đź‘Ť

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
👤Scott Skiles

Leave a comment