update login websocket

This commit is contained in:
edbernar
2024-08-03 09:12:45 +02:00
parent e533c452b9
commit f3698d3683
8 changed files with 97 additions and 56 deletions

View File

@ -1,53 +1,49 @@
# **************************************************************************** #
# #
# ::: :::::::: #
# main.py :+: :+: :+: #
# +:+ +:+ +:+ #
# By: edbernar <edbernar@student.42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# 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()