import json from channels.db import database_sync_to_async @database_sync_to_async def get_user(data): from django.contrib.auth.models import User, AnonymousUser try: data = data.decode("utf-8") param_list = data.split('&') param_Dict = {item.split('=')[0]: item.split('=')[1] for item in param_list} return User.objects.get(id=param_Dict['user_id']) except User.DoesNotExist: return AnonymousUser() class QueryAuthMiddleware: """ Custom middleware (insecure) that takes user IDs from the query string. """ def __init__(self, app): # Store the ASGI application we were passed self.app = app async def __call__(self, scope, receive, send): # Look up user from query string (you should also do things like # checking if it is a valid user ID, or if scope["user"] is already # populated). data = scope['query_string'] scope['user'] = await get_user(data) return await self.app(scope, receive, send)