Я пытаюсь сделать чат, и когда я устанавливаю соединение с webSocket, я теряю данные сеанса, где хранится токен аутентификации пользователя, поэтому я не могу проверить аутентификацию пользователя. Когда я загружаю страницу, которая содержит форму для подключения к webSocket, появляются все данные сеанса. Я проверяю многие учебные пособия, но у них таких проблем нет.
Спасибо за вашу помощь!
Мой JS код здесь:
$(document).ready(function() {
url = window.location.href
name = url.slice(url.lastIndexOf('/')+1)
const chat = new WebSocket("ws://127.0.0.1:8080/chat/"+name);
chat.onmessage = function(event) {
data = JSON.parse(event.data)
message = $('<div>', {class:'chat_message', text:`${data.message}`}).appendTo('.chat')
};
$('#chat_form').submit(function(event){
event.preventDefault()
if ($('.chat_form').find('textarea').val() == '') {
return;
}
chat.send($('#chat_form').find('textarea').val())
});
})
Мой промежуточное ПО:
@middleware
async def Auth(request, handler):
request.session = session = await get_session(request)
print(request.session)
jwt_token = session.get('JWT', None)
if jwt_token:
user_credentials = jwt.decode(jwt_token, SECRET_KEY, algorithm='HS256')
datetime_expires = datetime.datetime.strptime(user_credentials['expires'], '%Y-%m-%d-%H-%M')
if datetime_expires < datetime.datetime.now():
await logout(request)
request.user = UserInfo()
else:
async with request.app['db'].acquire() as conn:
request.user = UserInfo(await conn.fetchrow('SELECT * FROM users WHERE name = $1', user_credentials['name']))
await conn.close()
else:
request.user = UserInfo()
resp = await handler(request)
return resp
И мой обработчик:
@routers_chat.view('/{user_name}')
class UserChat(web.View):
async def broadcast(self, message):
"""
Send message to all users of current chat
"""
username = self.request.match_info['user_name']
# Send fo all authorized peers
for ws in self.request.app['user_web_sockets'][username]:
response = dict(username=self.request.user.name, message=message)
ws.send_json(response)
# Send fo all unauthorized peers
for ws in self.request.app['anon_web_sockets'][username]:
print(ws)
response = dict(username=self.request.user.name, message=message)
ws.send_json(response)
async def get(self):
# Init WebSockets
ws = web.WebSocketResponse()
await ws.prepare(self.request)
# Get owner of page name
owner_username = self.request.match_info['user_name']
# Check peer authentication
if self.request.user.is_authenticated:
# Init user non anon webSocket
owner_wsdict = self.request.app['chat']['user_web_sockets']
# Collect webSocket
if owner_username not in owner_wsdict:
owner_wsdict[owner_username] = {self.request.user.name: ws}
else:
owner_wsdict[owner_username].update({self.request.user.name: ws})
# Send message
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
await self.broadcast(msg.data)
# Close connection
owner_wsdict[owner_username].pop(self.request.user.name)
return ws
else:
# Init user anon webSocket
owner_wsdict = self.request.app['chat']['anon_web_sockets']
# Collect websocket
if owner_username not in owner_wsdict:
owner_wsdict[owner_username] = [ws]
else:
owner_wsdict[owner_username].append(ws)
# Send error response
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
response = dict(username='SERVER', message='You must be authorize!')
await ws.send_json(response)
# Close connection
owner_wsdict[owner_username].remove(ws)
return ws