how to validate username and id in websocket

Hello everyone I know this is the third time I am asking questions about websocket, I have implemented websocket that works fine, I can send a receive message. The issue I have is that I want check the message sent if the username and id is part of the message then the message will be success. I have search many blogs and articles like this also read a lot on WebSocket but all of these didn’t solve my issue, please help.

here is an example of a valid message that works fine

{
    "username": "John",
    "message": 146054156041144154
}

however anything I pass here it will also succeed that is not a good idea I think

consumer.py

class QRCodeConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.group_name = "Welcome"
        session_name = self.scope['url_route']['kwargs']['session_name']
        self.group_name = "{}_{}".format(self.group_name, session_name)

        await self.channel_layer.group_add(self.group_name, self.channel_name)

        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(self.group_name, self.channel_name)

    # This function receive messages from WebSocket.
    async def receive(self, text_data=None, bytes_data=None):
        text_data_json = json.loads(text_data)

        await self.channel_layer.group_send(
            self.group_name,
            {
                "type": "message",
                "message": text_data_json
            },
        )

    # Receive message from room group.
    async def qr_code_message(self, event):
        # send message and username of sender to websocket
        await self.send(
            text_data=json.dumps(
                {
                    "message": event['message'],
                }
            )
        )

here is html file

const socket = new WebSocket("{{ ws_url }}");
  let timer = null;
  socket.onopen = () => {
    console.log("Connection Open")
  };
  socket.onmessage = function (evt) {
    console.log(evt["data"]);
    var data = JSON.parse(evt.data);
    var message = data['message']
      document.getElementById("success_message").innerHTML = message;

      window.location.href =
        "{{ request.scheme }}://{{ request.get_host }}/success_mobile/";
  };


  socket.onclose = socket.onerror = () => {
    console.log("WebSocket connection closed.")
  };

  socket.onerror = (error) => {
    console.error("WebSocket error:", error);
  };

Thank you for your help

I think you want to check your received data key and values to the particular model instance, if so then Database Access — Channels 4.0.0 documentation check out this doc.
Also here is some code that I’ve used, you can also take reference from here

import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from .models import Account

@database_sync_to_async
def update_user_status(user, status):
    try:
        user_obj = Account.objects.get(id=int(user))
        user_obj.is_online = status
        user_obj.save()
    except:
        pass


class UserOnlineConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.user_id = self.scope["url_route"]["kwargs"]["user_id"]
        print("User Online Socket Connected For: ", self.user_id)
        await update_user_status(self.user_id, True)
        await self.accept()

    async def disconnect(self, code):
        print("User Online Socket Disconnected For: ", self.user_id)
        await update_user_status(self.user_id, False)
1 Like

What username and id are you talking about here? Are you trying to identify the sender or the receiver of a message?

Yes, actually any time user logged in an ID is generated for the user then anytime he want to send messages he should be identified with username and that id eg:

{
    "username": "Mark",
    "message": 146054156041144154
}

Ok, you’re talking about the sending person.

The sender shouldn’t need to submit any identification data. Once they’re logged in to the site, the scope contains their identification.
(Websockets are persistent connections, there’s no need to send any kind of token with each frame.)

Also see the docs at Authentication — Channels 4.0.0 documentation.

1 Like

Thanks your I understand