S
S
Safronov_Alexei2020-06-30 18:18:02
Django
Safronov_Alexei, 2020-06-30 18:18:02

How to connect Django channels to SimpleJWT?

Hello!
Please tell me, I can't.
I am making an application on the phone, and I need to make a correspondence function, I thought that Django Channels would do, but there was a problem, I can’t connect Django Channels and JWT Authorization. Although I did a lot according to the documentation.

sync def find_user(id):
    #try:
    await NewUser.objects.get(id=id)
    return NewUser.objects.get(id=id)
    # except NewUser.DoesNotExist:
    #     return AnonymousUser()

class TokenAuthMiddleware:
    """
    Custom token auth middleware
    """
    id = 0

    def __init__(self, inner):
        # Store the ASGI application we were passed
        print('FUCK1')
        self.inner = inner

    def __call__(self, scope):

        # Close old database connections to prevent usage of timed out connections
        close_connections()
        print('FUCK2')

        # Get the token
        print('FUCK3')
        token = parse_qs(scope["query_string"].decode("utf8"))["token"][0]

        # Try to authenticate the user
        try:
            # This will automatically validate the token and raise an error if token is invalid
            UntypedToken(token)
        except (InvalidToken, TokenError) as e:
            # Token is invalid
            print(e)
            print('FUCK4')
            return None

        #  Then token is valid, decode it
        decoded_data = jwt_decode(token, settings.SECRET_KEY, algorithms=["HS256"])
        print(decoded_data)
        # Will return a dictionary like -
        # {
        #     "token_type": "access",
        #     "exp": 1568770772,
        #     "jti": "5c15e80d65b04c20ad34d77b6703251b",
        #     "user_id": 6
        # }

        # Get the user using ID
        print('fuck 5')
        id2 = decoded_data["user_id"]
        user = find_user(id2)
        print(user)

        print('fuck 5+1')
        # Return the inner application directly and let it run everything else
        print('fuck 6')
        return self.inner(dict(scope, user=user))


When I try to get a user from the database, I get a carotene and I can’t use it in any way. Help me please!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question