Bearle / django-private-chat

(Deprecated - Please check out https://github.com/Bearle/django_private_chat2) Django one-to-one Websocket-based Asyncio-handled chat, developed by Bearle team
ISC License
424 stars 132 forks source link

using knox allauth with django private chat #70

Closed jihadelsayed closed 2 years ago

jihadelsayed commented 4 years ago

Description

hello! I am trying to use knox allauth with the django private chat library but it didn't work becouse DPP library use setion authonticate while knox use token authenticate

What I Did

so i tryed to edit the utils.py file

from django.contrib.sessions.models import Session
from django.contrib.auth import get_user_model
from .models import Dialog
from django.db.models import Q
import logging
import sys
from knox.auth import TokenAuthentication
from knox_allauth.models import CustomUser

async def get_user_from_auth_key(auth_key):
    token = TokenAuthentication.model.objectssss.get(digest=auth_key)
    session = Session.objects.get(session_key=auth_key)
    if session:
        session_data = session.get_decoded()
        uid = session_data.get('_auth_user_id')
        user = get_user_model().objects.filter(id=uid).first()  # get object or none
        return user
    elif token:
        #token_data = token.get_decoded()
        #uid = token_data.get('_auth_user_id')
        uid = token.user
        user = CustomUser.objects.filter(id=uid).first()
        #user = get_user_model().objects.filter(id=uid).first()  # get object or none
        return user
    else:
        return None

def get_dialogs_with_user(user_1, user_2):
    """
    gets the dialog between user_1 and user_2
    :param user_1: the first user in dialog (owner or opponent)
    :param user_2: the second user in dialog (owner or opponent)
    :return: queryset which include dialog between user_1 and user_2 (queryset can be empty)
    """
    return Dialog.objects.filter(
        Q(owner=user_1, opponent=user_2) | Q(opponent=user_1, owner=user_2))

logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s:%(levelname)s:%(message)s",
                    datefmt='%d.%m.%y %H:%M:%S')
logger = logging.getLogger('django-private-dialog')
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

I get this error

2020-11-02 14:04:42,567:INFO:Chat server started
02.11.20 14:04:42:INFO:Chat server started
02.11.20 14:04:45:DEBUG:server - state = CONNECTING
02.11.20 14:04:45:DEBUG:server - event = connection_made(<_ProactorSocketTransport fd=1616>)
02.11.20 14:04:45:DEBUG:server - event = data_received(<783 bytes>)
02.11.20 14:04:45:DEBUG:server < GET /fb6388fac60b55b06c9a232ebe0fb15cd1e0a8654741882e2363261427a29fc67ee1af3ab014014c30dcd09e519fefc4cf4369cf99c84ababb7ea8336495bd8a/1 HTTP/1.1
02.11.20 14:04:45:DEBUG:server < Headers([('Host', 'localhost:5002'), ('Connection', 'Upgrade'), ('Pragma', 'no-cache'), ('Cache-Control', 'no-cache'), ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'), ('Upgrade', 'websocket'), ('Origin', 'http://localhost:4200'), ('Sec-WebSocket-Version', '13'), ('Accept-Encoding', 'gzip, deflate, br'), ('Accept-Language', 'en-US,en;q=0.9,ar;q=0.8,sv-SE;q=0.7,sv;q=0.6'), ('Cookie', 'csrftoken=XClMZAfGjs8Tl1963cnOuJCWww2OIAvvPBj3qaDuE3VtkzxGXzcVU60MqypoqVCa; sessionid=cqw2tq3dss685qice8nux1ofdpatvhu5'), ('Sec-WebSocket-Key', 'X/L+YxN3VYW1iO8ZFDHXbg=='), ('Sec-WebSocket-Extensions', 'permessage-deflate; client_max_window_bits')])
02.11.20 14:04:45:DEBUG:server > HTTP/1.1 101 Switching Protocols
02.11.20 14:04:45:DEBUG:server > Headers([('Upgrade', 'websocket'), ('Connection', 'Upgrade'), ('Sec-WebSocket-Accept', 'EDe0ZkU7mlFeB1Yk7F7Ce7ujd+k='), ('Sec-WebSocket-Extensions', 'permessage-deflate'), ('Date', 'Mon, 02 Nov 2020 13:04:45 GMT'), ('Server', 'Python/3.8 websockets/8.1')])
02.11.20 14:04:45:DEBUG:server - state = OPEN
02.11.20 14:04:45:ERROR:Error in connection handler
Traceback (most recent call last):
  File "C:\Python38\lib\site-packages\websockets\server.py", line 191, in handler
    await self.ws_handler(self, path)
  File "D:\JM\Palimago2020\Backend\django_private_chat\handlers.py", line 248, in main_handler
    user_owner = await get_user_from_auth_key(auth_id)
  File "D:\JM\Palimago2020\Backend\django_private_chat\utils.py", line 17, in get_user_from_auth_key
    token = TokenAuthentication.model.objects.get(digest=auth_key)
  File "C:\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Python38\lib\site-packages\django\db\models\query.py", line 425, in get
    num = len(clone)
  File "C:\Python38\lib\site-packages\django\db\models\query.py", line 269, in __len__
    self._fetch_all()
  File "C:\Python38\lib\site-packages\django\db\models\query.py", line 1303, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Python38\lib\site-packages\django\db\models\query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1154, in execute_sql
    cursor = self.connection.cursor()
  File "C:\Python38\lib\site-packages\django\utils\asyncio.py", line 24, in inner
    raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. 
02.11.20 14:04:45:DEBUG:server ! failing OPEN WebSocket connection with code 1011
02.11.20 14:04:45:DEBUG:server - state = CLOSING
02.11.20 14:04:45:DEBUG:server > Frame(fin=True, opcode=8, data=b'\x03\xf3', rsv1=False, rsv2=False, rsv3=False)
02.11.20 14:04:45:DEBUG:server x half-closing TCP connection
02.11.20 14:04:45:DEBUG:server - event = connection_lost(None)
02.11.20 14:04:45:DEBUG:server - state = CLOSED
02.11.20 14:04:45:DEBUG:server x code = 1006, reason = [no reason]