修改websocket传输token的方式

pull/90/head
cheney 2023-03-10 15:38:39 +08:00
parent 9d0ab55152
commit b518ddab66
4 changed files with 11 additions and 7 deletions

View File

@ -3,6 +3,6 @@ from django.urls import path
from application.websocketConfig import MegCenter from application.websocketConfig import MegCenter
websocket_urlpatterns = [ websocket_urlpatterns = [
path('ws/<str:service_uid>/', MegCenter.as_asgi()), #consumers.DvadminWebSocket 是该路由的消费者 path('ws/', MegCenter.as_asgi()), #consumers.DvadminWebSocket 是该路由的消费者
] ]

View File

@ -58,7 +58,7 @@ class DvadminWebSocket(AsyncJsonWebsocketConsumer):
async def connect(self): async def connect(self):
try: try:
import jwt import jwt
self.service_uid = self.scope["url_route"]["kwargs"]["service_uid"] self.service_uid = self.scope["subprotocols"][0]
decoded_result = jwt.decode(self.service_uid, settings.SECRET_KEY, algorithms=["HS256"]) decoded_result = jwt.decode(self.service_uid, settings.SECRET_KEY, algorithms=["HS256"])
if decoded_result: if decoded_result:
self.user_id = decoded_result.get('user_id') self.user_id = decoded_result.get('user_id')
@ -68,7 +68,7 @@ class DvadminWebSocket(AsyncJsonWebsocketConsumer):
self.chat_group_name, self.chat_group_name,
self.channel_name self.channel_name
) )
await self.accept() await self.accept(subprotocol=self.service_uid)
# 主动推送消息 # 主动推送消息
unread_count = await _get_message_unread(self.user_id) unread_count = await _get_message_unread(self.user_id)
if unread_count == 0: if unread_count == 0:
@ -78,7 +78,8 @@ class DvadminWebSocket(AsyncJsonWebsocketConsumer):
await self.send_json( await self.send_json(
set_message('system', 'SYSTEM', "请查看您的未读消息~", set_message('system', 'SYSTEM', "请查看您的未读消息~",
unread=unread_count)) unread=unread_count))
except InvalidSignatureError: except InvalidSignatureError as e:
print(e.__str__())
await self.disconnect(None) await self.disconnect(None)
async def disconnect(self, close_code): async def disconnect(self, close_code):
@ -122,6 +123,7 @@ class MessageCreateSerializer(CustomModelSerializer):
fields = "__all__" fields = "__all__"
read_only_fields = ["id"] read_only_fields = ["id"]
def websocket_push(user_id,message): def websocket_push(user_id,message):
username = "user_" + str(user_id) username = "user_" + str(user_id)
channel_layer = get_channel_layer() channel_layer = get_channel_layer()
@ -133,6 +135,7 @@ def websocket_push(user_id,message):
} }
) )
def create_message_push(title: str, content: str, target_type: int=0, target_user: list=[], target_dept=None, target_role=None, def create_message_push(title: str, content: str, target_type: int=0, target_user: list=[], target_dept=None, target_role=None,
message: dict = {'contentType': 'INFO', 'content': '测试~'}, request= Request): message: dict = {'contentType': 'INFO', 'content': '测试~'}, request= Request):
if message is None: if message is None:

View File

@ -100,7 +100,7 @@ def websocket_push(user_id, message):
主动推送消息 主动推送消息
""" """
username = "user_"+str(user_id) username = "user_"+str(user_id)
print(103,message) # print(103,message)
channel_layer = get_channel_layer() channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)( async_to_sync(channel_layer.group_send)(
username, username,

View File

@ -4,8 +4,9 @@ import store from '@/store'
function initWebSocket (e) { function initWebSocket (e) {
const token = util.cookies.get('token') const token = util.cookies.get('token')
if (token) { if (token) {
const wsUri = util.wsBaseURL() + 'ws/' + token + '/' const wsUri = util.wsBaseURL() + 'ws/'
this.socket = new WebSocket(wsUri)// 这里面的this都指向vue // const wsUri = util.wsBaseURL() + 'ws/' + token + '/'
this.socket = new WebSocket(wsUri, [token])// 这里面的this都指向vue
this.socket.onerror = webSocketOnError this.socket.onerror = webSocketOnError
this.socket.onmessage = webSocketOnMessage this.socket.onmessage = webSocketOnMessage
this.socket.onclose = closeWebsocket this.socket.onclose = closeWebsocket