Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Channels middleware use ORM

I have troubles checking the user token inside of middleware. I'm getting token from cookies and then I need to query database to check if this token exists and belongs to user that made a request.

routing.py

from channels.routing import ProtocolTypeRouter, URLRouter
import game.routing
from authentication.utils import TokenAuthMiddlewareStack

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

middleware.py

from rest_framework.authentication import TokenAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_auth.models import TokenModel

from channels.auth import AuthMiddlewareStack
from django.contrib.auth.models import AnonymousUser
from django.db import close_old_connections
...
class TokenAuthMiddleware:
    """
    Token authorization middleware for Django Channels 2
    """

    def __init__(self, inner):
        self.inner = inner


    def __call__(self, scope):
        close_old_connections()

        headers = dict(scope['headers'])
        if b'Authorization' in headers[b'cookie']:
            try:
                cookie_str = headers[b'cookie'].decode('utf-8')

                try:  # no cookie Authorization=Token in the request
                    token_str = [x for x in cookie_str.split(';') if re.search(' Authorization=Token', x)][0].strip()
                except IndexError:
                    scope['user'] = AnonymousUser()
                    return self.inner(scope)

                token_name, token_key = token_str.replace('Authorization=', '').split()
                if token_name == 'Token':
                    token = TokenModel.objects.get(key=token_key)
                    scope['user'] = token.user

            except TokenModel.DoesNotExist:
                scope['user'] = AnonymousUser()
        return self.inner(scope)


TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))

And this gives me

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

I also tried the following approaches

async def __call__(self, scope):
    ...
    if token_name == 'Token':
        token = await self.get_token(token_key)
        scope['user'] = token.user
    ...

# approach 1
@sync_to_async
def get_token(self, token_key):
    return TokenModel.objects.get(key=token_key)

# approach 2
@database_sync_to_async
def get_token(self, token_key):
    return TokenModel.objects.get(key=token_key)

Those approaches give the following error

[Failure instance: Traceback: <class 'TypeError'>: 'coroutine' object is not callable
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/autobahn/websocket/protocol.py:2847:processHandshake
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/txaio/tx.py:366:as_future
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/twisted/internet/defer.py:151:maybeDeferred
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/daphne/ws_protocol.py:72:onConnect
--- <exception caught here> ---
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/twisted/internet/defer.py:151:maybeDeferred
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/daphne/server.py:206:create_application
]```
like image 803
Nikita Tonkoskur Avatar asked Jul 10 '26 02:07

Nikita Tonkoskur


1 Answers

I am not sure if it will work or not,but you can try

First write the get_token function outside the class.

   # approach 1
   @sync_to_async
   def get_token(self, token_key):
     return TokenModel.objects.get(key=token_key)

then in your async function write get_token() instead of self.get_token()

  async def __call__(self, scope):
     ...
     if token_name == 'Token':
        token = await get_token(token_key)
        scope['user'] = token.user
     ...
like image 94
Gilbish Kosma Avatar answered Jul 13 '26 17:07

Gilbish Kosma