Anatol Zakrividoroga
Anatol Zakrividoroga

Reputation: 4518

How to only allow logged in users connect to websocket in Django Channels?

I have a chat app and I want only users that are logged in to be able to connect to the websocket.

How can you achieve that?

Is there something like the @login_required decorator for Django channels?

I know from the documentation that that's how you can access the user:

class ChatConsumer(WebsocketConsumer):

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

But how do you deny the connection if the user isn't logged in?

Upvotes: 2

Views: 1458

Answers (2)

Anatol Zakrividoroga
Anatol Zakrividoroga

Reputation: 4518

I figured out the answer to my question:

# mysite/routing.py

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})
class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.user = self.scope['user']

        if self.user.is_authenticated:
            # accept connection if user is logged in
            self.accept()

        else:
            # don't accept connection if user is not logged in 
            self.close()


Upvotes: 5

kkiat
kkiat

Reputation: 571

The AuthMiddlewareStack will populate the connection’s scope with a reference to the currently authenticated user, similar to how Django’s AuthenticationMiddleware populates the request object of a view function with the currently authenticated user.

Example to add AuthMiddlewareStack as below:

# mysite/routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})

Reference: https://channels.readthedocs.io/en/latest/tutorial/part_2.html#write-your-first-consumer

Upvotes: 1

Related Questions