1

I have django (1.9) application which is implemented with websocket. To implement websocket I use Django channel (1.1.8). My models are under ACL which are managed by Django-guardian (1.4.4).

I send message through websocket every time a model named "My_model" is created, changed or deleted. But my challenge is that the model is under ACL that means that user can receive message through websocket if and only if this user can_view the model instance. This means that I must have the user instance in my signal handler in order to verify if websocket user has perm before sending a message.

You can see below my implementation. It works on development environment but not in production. The difference is that on production, websocket handler is running under a Django worker and Daphne server.

in a file my_app/consumers/my_model_consumer.py:

class MyModelConsumer(WebsocketConsumer):
    http_user_and_session = True

    # the connect method is triggered when an user is connecting through the websocket
    # It register signals handlers which receive the connected user as argument
    def connect(self, message, **kwargs):
       user = message.user
       group = "my_model_Notifications-{}".format(user.id)

       Group(group).add(message.reply_channel)

       post_save.connect(partial(notify_my_model_change, user=user, group=group), My_model, weak=False, dispatch_uid= uuid.uuid4())
       post_delete.connect(partial(notify_request_delete, user=user, group=group), My_model, weak=False, dispatch_uid= uuid.uuid4())

       self.message.reply_channel.send({"accept": True})

def notify_my_model_change(sender, **kwargs):
    user = kwargs['user']
    instance = kwargs['instance'] 
    if user.has_perm('view_my_model', instance):
        Group(group).send({"text": "My_model changed"})

Does someone know what's wrong causing it to not work in production environment?

0 Answers0