From f3698d36838eed6286af4caaa74b251823134849 Mon Sep 17 00:00:00 2001 From: edbernar Date: Sat, 3 Aug 2024 09:12:45 +0200 Subject: [PATCH] update login websocket --- site/module_livechat/listError.txt | 4 +- site/module_livechat/server/main.py | 89 +++++++++--------- .../getPrivateListUser.cpython-312.pyc | Bin 1319 -> 0 bytes .../__pycache__/login.cpython-310.pyc | Bin 0 -> 533 bytes .../server/typeRequets/login.py | 36 +++++++ site/module_livechat/site/main.js | 11 ++- .../site/typeResponse/typePrivateListUser.js | 5 +- site/module_livechat/site/websocket.js | 8 +- 8 files changed, 97 insertions(+), 56 deletions(-) delete mode 100644 site/module_livechat/server/typeRequets/__pycache__/getPrivateListUser.cpython-312.pyc create mode 100644 site/module_livechat/server/typeRequets/__pycache__/login.cpython-310.pyc create mode 100644 site/module_livechat/server/typeRequets/login.py diff --git a/site/module_livechat/listError.txt b/site/module_livechat/listError.txt index d450eca..c12a44b 100644 --- a/site/module_livechat/listError.txt +++ b/site/module_livechat/listError.txt @@ -4,4 +4,6 @@ - 9000 : Invalid token - 9001 : Token not found - 9002 : Invalid json -- 9003 : Invalid path \ No newline at end of file +- 9003 : Invalid path +- 9004 : Invalid type +- 9005 : Invalid request \ No newline at end of file diff --git a/site/module_livechat/server/main.py b/site/module_livechat/server/main.py index 19cb653..e40a680 100644 --- a/site/module_livechat/server/main.py +++ b/site/module_livechat/server/main.py @@ -1,53 +1,49 @@ +# **************************************************************************** # +# # +# ::: :::::::: # +# main.py :+: :+: :+: # +# +:+ +:+ +:+ # +# By: edbernar +#+ +:+ +#+ # +# +#+#+#+#+#+ +#+ # +# Created: 2024/08/03 08:10:40 by edbernar #+# #+# # +# Updated: 2024/08/03 08:46:38 by edbernar ### ########.fr # +# # +# **************************************************************************** # + from typeRequets.getPrivateListUser import getPrivateListUser -import asyncio +from typeRequets.login import login, userList import websockets +import asyncio import json connected_clients = set() -userList = [ - { - "username": "user1", - "token": "123456", - "id": 1 - }, - { - "username": "user2", - "token": "789123", - "id": 2 - }, - { - "username": "user3", - "token": "456789", - "id": 3 - } -] -typeRequest = ["get_private_list_user"] -functionRequest = [getPrivateListUser] +class userInfo(websockets.WebSocketServerProtocol): + def __init__(self, websocket): + self.websocket = websocket + self.username = "" + self.token = "" + self.id = 0 + +typeRequest = ["login", "get_private_list_user"] +functionRequest = [login, getPrivateListUser] async def sendError(websocket, message, code): jsonVar = {"type": "error", "content": message, "code": code} await websocket.send(json.dumps(jsonVar)) -async def sendInfoUser(websocket): - token = websocket.request_headers.get('Sec-WebSocket-Protocol') - user = [user for user in userList if user['token'] == token][0] - jsonVar = {"type": "login", "content": user} - await websocket.send(json.dumps(jsonVar)) - -async def isValidToken(websocket): - token = websocket.request_headers.get('Sec-WebSocket-Protocol') - # |TOM| Faire une requête à la base de données pour vérifier si le token est valide - if (token in [user['token'] for user in userList]): - await sendInfoUser(websocket) - return True - else: - return False +def verifyToken(websocket, token): + for user in userList: + if (user["token"] == token): + return True + return False async def handler(websocket, path): - if (not await isValidToken(websocket)): - await websocket.close(reason="Invalid token") + if (path != "/"): + await sendError(websocket, "Invalid path", 9003) + await websocket.close() return + connected_clients.add(userInfo(websocket)) try: async for resquet in websocket: try: @@ -56,19 +52,24 @@ async def handler(websocket, path): await sendError(websocket, "Invalid JSON", 9002) continue try: - if (jsonRequest["token"][0] != websocket.request_headers.get('Sec-WebSocket-Protocol')): - await sendError(websocket, "Invalid token", 9000) - continue + if (jsonRequest["type"] in typeRequest): + if jsonRequest["type"] == "login": + await functionRequest[typeRequest.index(jsonRequest["type"])](websocket, jsonRequest["content"]) + else: + if (verifyToken(websocket, jsonRequest["token"]) == False): + await sendError(websocket, "Invalid token", 9001) + continue + await functionRequest[typeRequest.index(jsonRequest["type"])](websocket) + else: + await sendError(websocket, "Invalid type", 9004) except: - await sendError(websocket, "Token not found", 9001) - continue - if (jsonRequest["type"] in typeRequest): - await functionRequest[typeRequest.index(jsonRequest["type"])](websocket) - + await sendError(websocket, "Invalid request", 9005) except websockets.ConnectionClosed: + connected_clients.remove(websocket) print("Client déconnecté") start_server = websockets.serve(handler, "localhost", 8000, subprotocols=['123456']) asyncio.get_event_loop().run_until_complete(start_server) +print("Server started") asyncio.get_event_loop().run_forever() \ No newline at end of file diff --git a/site/module_livechat/server/typeRequets/__pycache__/getPrivateListUser.cpython-312.pyc b/site/module_livechat/server/typeRequets/__pycache__/getPrivateListUser.cpython-312.pyc deleted file mode 100644 index dd4e654115d0704c98b15d07d00cc322c27245da..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1319 zcmaJ7%Q6rS;}f8r!<6On{+XnI08Xg#)LCoxn=rU`{oLP!Y*3#l6KjO}&SJIl^& z%(|rtw1NuE&XhYR=mBfPjSJj@!U5&P+jTZYATiRs`QFUD_kHip{4hP8 zM=<_e{JQlZ=T|aNGiLfEZ%fM$Pexn>hAU%@j*9jp;1?Kw}w}Ww{tlz+OH^ zldv}xqiI0rVsswRg$Q*rO^wamM@>Dzh1uUD!p(4UlS}D4On7}7W`tu~4j;bMRmzpm z5i+2*?NXO}(lBl66iv}51J^Kxqqw7p@7jVgNh+nvGAY%FDTHmfZPzGOiaobe&_dmz zeI90{qRN+{24~^KP2V(yqOu!iMY|mnUP}nAqH8%;zY{Z6N~L#6WsR)XNPPvsYOTJ~ zuCFbZs;zdJGP7b<%jK1Fo$|FdZ%2$_z9E$-TruF@a3@I$RF>>=W~t%-R8S?Q<#7cR z6!5qX#{0rCq)h|v885FV6q5S3viA7!YC>U^i_&2x8@GshY9PE_X_RkRrR%R;_ujZ> zi{AQjU^F(Y&E0{aYET-?IALy^Guaj9?y!)gixNSvWU59q;-9$mXZx=ZmgKQJEca$*y-{p(8Q-7En3nr@4-C&1k9@lM;{L> zz~jME4^r=8r6v9y{MBhRMt4vzivHJ7*<_=aOVH!>aeR{J9(?fIkpJ`4f%aiK4GIFZ ziat(%qYZFD+YD!1&)TDk-?A;KZuydXg;c1kz~y1~^b;1+q0XqHVH)l_D%2%+Sg7}; zaKbe6`>uqLi2-j(=rC7dHadBWdNKvVE?+)*n{-8=6V6yb)`jW!;bTj3RWMGr-h6F? zNK0|j7tFUK6?@$5Qbj<>9`{HjWShU^bBO40wKW!d1GMhIjiMWbv;W=po&w^hVah6) z-_T$C=qQKgp80nD$I1Hs!Y??pKe&Hsl)doL-S_W)#twR)_P$tnG+%g>UHTa>{e+iJ zjiHS z+~{THZ7@d~#`qAOJ47>wXcDANT^vo%jq=-nWOYqHnnF_xqv`ok{^ptgWPDEl>BIT! gXa0PAzjo$75&O@N{n}zKwXYw)h%@+E?-KC;4MFLC2mk;8 diff --git a/site/module_livechat/server/typeRequets/__pycache__/login.cpython-310.pyc b/site/module_livechat/server/typeRequets/__pycache__/login.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4a1da1fc4265567b12c6033e1b19090aa1e911f GIT binary patch literal 533 zcmY*Wy-pl45VpNPw|Cqj0dJ5rY!i!rkPxB>smLiJRNJ6sXMlw}`&j!xCs7c=V^Gqh z$W!nJDcz>J2S|g2l<}^DV5Av;^Z6U=v#oo*4x?E7{p;j0WbBV`-bPH#E~WWG1sL!F z%bJyEyzWINKtKQ?L=OSP(1N5!ZRo&^N2fs+Ko@%VEDM2uXX)&e&SHHRjSW^yE?!z* zSzTM7aw5~fC7xCJ5M5;T1u7>>Xr#+7-q_qC^;D3w;Z|HsvqVn=;tId6^n&Aut~H1Cq_ d#>S3+UGsrT(oJ~6MJTx7;fsjhui@YB{6D2Eh_(O# literal 0 HcmV?d00001 diff --git a/site/module_livechat/server/typeRequets/login.py b/site/module_livechat/server/typeRequets/login.py new file mode 100644 index 0000000..7677f25 --- /dev/null +++ b/site/module_livechat/server/typeRequets/login.py @@ -0,0 +1,36 @@ +# **************************************************************************** # +# # +# ::: :::::::: # +# login.py :+: :+: :+: # +# +:+ +:+ +:+ # +# By: edbernar +#+ +:+ +#+ # +# +#+#+#+#+#+ +#+ # +# Created: 2024/08/03 08:10:38 by edbernar #+# #+# # +# Updated: 2024/08/03 08:46:00 by edbernar ### ########.fr # +# # +# **************************************************************************** # + +import asyncio +import websockets +import json + +userList = [ + { + "username": "user1", + "token": "123456", + "id": 1 + }, + { + "username": "user2", + "token": "789123", + "id": 2 + }, + { + "username": "user3", + "token": "456789", + "id": 3 + } +] + +async def login(websocket, content): + print(content) \ No newline at end of file diff --git a/site/module_livechat/site/main.js b/site/module_livechat/site/main.js index 4ae6613..cd706c0 100644 --- a/site/module_livechat/site/main.js +++ b/site/module_livechat/site/main.js @@ -3,10 +3,10 @@ /* ::: :::::::: */ /* main.js :+: :+: :+: */ /* +:+ +:+ +:+ */ -/* By: edbernar +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/07/30 13:50:35 by edbernar #+# #+# */ -/* Updated: 2024/08/02 03:09:12 by edbernar ### ########.fr */ +/* Updated: 2024/08/03 08:31:07 by edbernar ### ########.fr */ /* */ /* ************************************************************************** */ @@ -29,7 +29,7 @@ function liveChat() { chatDiv.style.display = "flex"; gameButtonChatHome.removeAttribute("id"); privateButtonChatHome.setAttribute("id", "selected"); - await showListUserMessage(userList); + await showListUserMessage(); }); topChatHomeCross.addEventListener("click", () => { chatDiv.style.display = "none"; @@ -38,7 +38,7 @@ function liveChat() { privateButtonChatHome.addEventListener("click", async () => { gameButtonChatHome.removeAttribute("id"); privateButtonChatHome.setAttribute("id", "selected"); - await showListUserMessage(userList); + await showListUserMessage(); }); gameButtonChatHome.addEventListener("click", () => { privateButtonChatHome.removeAttribute("id"); @@ -47,13 +47,14 @@ function liveChat() { }); } -async function showListUserMessage(userList) { +async function showListUserMessage() { const divMessageListChatHome = document.getElementById("messageListChatHome"); let divUser; socket.send(JSON.stringify({ type: 'get_private_list_user', token: token, + content: {} })); await waitForUserList(); diff --git a/site/module_livechat/site/typeResponse/typePrivateListUser.js b/site/module_livechat/site/typeResponse/typePrivateListUser.js index 93bf99a..6366c21 100644 --- a/site/module_livechat/site/typeResponse/typePrivateListUser.js +++ b/site/module_livechat/site/typeResponse/typePrivateListUser.js @@ -3,10 +3,10 @@ /* ::: :::::::: */ /* typePrivateListUser.js :+: :+: :+: */ /* +:+ +:+ +:+ */ -/* By: edbernar +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/08/02 01:56:15 by edbernar #+# #+# */ -/* Updated: 2024/08/02 03:09:04 by edbernar ### ########.fr */ +/* Updated: 2024/08/02 11:42:46 by edbernar ### ########.fr */ /* */ /* ************************************************************************** */ @@ -27,6 +27,7 @@ function waitForUserList() { function typePrivateListUser(list) { userList = list; userListAvailable = true; + console.log(userListResolve) if (userListResolve) { userListResolve(); userListResolve = null; diff --git a/site/module_livechat/site/websocket.js b/site/module_livechat/site/websocket.js index c068ee6..32e9cea 100644 --- a/site/module_livechat/site/websocket.js +++ b/site/module_livechat/site/websocket.js @@ -3,18 +3,18 @@ /* ::: :::::::: */ /* websocket.js :+: :+: :+: */ /* +:+ +:+ +:+ */ -/* By: edbernar +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/07/31 22:17:24 by edbernar #+# #+# */ -/* Updated: 2024/08/02 03:00:42 by edbernar ### ########.fr */ +/* Updated: 2024/08/03 08:46:22 by edbernar ### ########.fr */ /* */ /* ************************************************************************** */ import { typeLogin } from "./typeResponse/typeLogin.js"; import { typePrivateListUser } from "./typeResponse/typePrivateListUser.js"; -const token = ['123456']; -const socket = new WebSocket('ws://localhost:8000/', token); +const socket = new WebSocket('ws://localhost:8000/'); +const token = "123456"; const typeResponse = ["login", "private_list_user"]; const functionResponse = [typeLogin, typePrivateListUser];