Server/Site

- 42 connection is working
This commit is contained in:
Kum1ta
2024-08-10 16:09:12 +02:00
parent 69205167c7
commit 4c6e8f2b1a
9 changed files with 122 additions and 52 deletions

View File

@ -11,4 +11,5 @@
- 9007 : Invalid username or password - 9007 : Invalid username or password
- 9008 : User not found - 9008 : User not found
- 9009 : Invalid message sent - 9009 : Invalid message sent
- 9010 : Invalid token 42 - 9010 : Invalid token 42
- 9011 : Not user registered with this 42 account

View File

@ -6,10 +6,11 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/09 09:15:24 by edbernar #+# #+# */ /* Created: 2024/08/09 09:15:24 by edbernar #+# #+# */
/* Updated: 2024/08/09 23:23:46 by edbernar ### ########.fr */ /* Updated: 2024/08/10 15:02:33 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
import { typeLogin } from "../typeResponse/typeLogin.js";
import { sendRequest } from "../websocket.js"; import { sendRequest } from "../websocket.js";
function connectedWith42Func() function connectedWith42Func()
@ -17,7 +18,10 @@ function connectedWith42Func()
const token42 = window.location.search.split('code=')[1]; const token42 = window.location.search.split('code=')[1];
if (!token42) if (!token42)
{
typeLogin(null);
return ; return ;
}
sendRequest("login", {type: "by42", token: token42}); sendRequest("login", {type: "by42", token: token42});
} }

View File

@ -3,10 +3,10 @@
/* ::: :::::::: */ /* ::: :::::::: */
/* main.js :+: :+: :+: */ /* main.js :+: :+: :+: */
/* +:+ +:+ +:+ */ /* +:+ +:+ +:+ */
/* By: edbernar <edbernar@student.42.fr> +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/07 17:40:15 by edbernar #+# #+# */ /* Created: 2024/08/07 17:40:15 by edbernar #+# #+# */
/* Updated: 2024/08/09 09:20:03 by edbernar ### ########.fr */ /* Updated: 2024/08/10 15:08:44 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -14,7 +14,6 @@ import { createNotification as CN } from "../notification/main.js";
import { userMeInfo, waitForLogin } from "../typeResponse/typeLogin.js"; import { userMeInfo, waitForLogin } from "../typeResponse/typeLogin.js";
import { createConnectDiv } from "./createConnectDiv.js"; import { createConnectDiv } from "./createConnectDiv.js";
import { createThreeDiv } from "./createThreeDiv.js"; import { createThreeDiv } from "./createThreeDiv.js";
import { connectedWith42Func } from "./connectedWith42.js";
function login() function login()
{ {
@ -22,9 +21,13 @@ function login()
const pLoginButton = loginButton.getElementsByTagName('p')[0]; const pLoginButton = loginButton.getElementsByTagName('p')[0];
let nodeText = null; let nodeText = null;
waitForLogin().then(() => { waitForLogin().then((token) => {
nodeText = document.createTextNode(userMeInfo.username); nodeText = document.createTextNode(userMeInfo.username);
if (token !== undefined)
{
document.cookie = "token={" + token + "}; path=/; Secure; SameSite=Strict; max-age=3600";
}
if (userMeInfo.id !== -1) if (userMeInfo.id !== -1)
loginButton.replaceChild(nodeText, pLoginButton); loginButton.replaceChild(nodeText, pLoginButton);
else else

View File

@ -0,0 +1,23 @@
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* typeErrorInvalidToken42.js :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/10 14:29:34 by edbernar #+# #+# */
/* Updated: 2024/08/10 14:40:10 by edbernar ### ########.fr */
/* */
/* ************************************************************************** */
import { createNotification as NC } from "../notification/main.js";
function typeErrorInvalidToken42()
{
// |Eddy| Changer le path pour mettre le bon path quand il y aura un vrai serveur
window.history.replaceState({}, document.title, "/site/");
NC.new("Error 42", "Invalid token", NC.defaultIcon.error);
}
export { typeErrorInvalidToken42 };

View File

@ -0,0 +1,21 @@
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* typeErrorUnknown42Account.js :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/10 16:01:51 by edbernar #+# #+# */
/* Updated: 2024/08/10 16:07:06 by edbernar ### ########.fr */
/* */
/* ************************************************************************** */
import { createNotification as CN } from "../notification/main.js";
function typeErrorUnknown42Account()
{
window.history.replaceState({}, document.title, "/site/");
CN.new("Unknown 42 account", "Your 42 account is not linked to any account.");
}
export { typeErrorUnknown42Account };

View File

@ -3,14 +3,16 @@
/* ::: :::::::: */ /* ::: :::::::: */
/* websocket.js :+: :+: :+: */ /* websocket.js :+: :+: :+: */
/* +:+ +:+ +:+ */ /* +:+ +:+ +:+ */
/* By: edbernar <edbernar@student.42.fr> +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/07/31 22:17:24 by edbernar #+# #+# */ /* Created: 2024/07/31 22:17:24 by edbernar #+# #+# */
/* Updated: 2024/08/09 09:21:28 by edbernar ### ########.fr */ /* Updated: 2024/08/10 16:05:26 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
import { typeErrorUnknown42Account } from "./typeErrorResponse/typeErrorUnknown42Account.js";
import { typeErrorInvalidPassword } from "./typeErrorResponse/typeErrorInvalidPassword.js"; import { typeErrorInvalidPassword } from "./typeErrorResponse/typeErrorInvalidPassword.js";
import { typeErrorInvalidToken42 } from "./typeErrorResponse/typeErrorInvalidToken42.js";
import { typePrivateListMessage } from "./typeResponse/typePrivateListMessage.js"; import { typePrivateListMessage } from "./typeResponse/typePrivateListMessage.js";
import { typeNewPrivateMessage } from "./typeResponse/typeNewPrivateMessage.js"; import { typeNewPrivateMessage } from "./typeResponse/typeNewPrivateMessage.js";
import { typePrivateListUser } from "./typeResponse/typePrivateListUser.js"; import { typePrivateListUser } from "./typeResponse/typePrivateListUser.js";
@ -29,8 +31,8 @@ const socket = new WebSocket('ws://localhost:8000/');
const typeResponse = ["login", "private_list_user", "private_list_message", "new_private_message"]; const typeResponse = ["login", "private_list_user", "private_list_message", "new_private_message"];
const functionResponse = [typeLogin, typePrivateListUser, typePrivateListMessage, typeNewPrivateMessage]; const functionResponse = [typeLogin, typePrivateListUser, typePrivateListMessage, typeNewPrivateMessage];
const errorCode = [9007] const errorCode = [9007, 9010, 9011];
const errorFunction = [typeErrorInvalidPassword]; const errorFunction = [typeErrorInvalidPassword, typeErrorInvalidToken42, typeErrorUnknown42Account];
let status = 0; let status = 0;
@ -49,7 +51,7 @@ function getCookie(name)
} }
socket.onopen = () => { socket.onopen = () => {
let token = getCookie("token"); let token = getCookie("token");
status = 1; status = 1;
console.log('Connected'); console.log('Connected');
@ -61,7 +63,6 @@ socket.onopen = () => {
else else
{ {
connectedWith42Func(); connectedWith42Func();
typeLogin(null);
} }
}; };

View File

@ -3,10 +3,10 @@
# ::: :::::::: # # ::: :::::::: #
# createAccount.py :+: :+: :+: # # createAccount.py :+: :+: :+: #
# +:+ +:+ +:+ # # +:+ +:+ +:+ #
# By: edbernar <edbernar@student.42.fr> +#+ +:+ +#+ # # By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ # # +#+#+#+#+#+ +#+ #
# Created: 2024/08/09 08:08:00 by edbernar #+# #+# # # Created: 2024/08/09 08:08:00 by edbernar #+# #+# #
# Updated: 2024/08/09 08:52:38 by edbernar ### ########.fr # # Updated: 2024/08/10 12:37:49 by edbernar ### ########.fr #
# # # #
# **************************************************************************** # # **************************************************************************** #
@ -49,6 +49,7 @@ async def createAccount(userClass, content):
if (content["password"].find(content["username"]) != -1): if (content["password"].find(content["username"]) != -1):
await userClass.sendError("Password must not contain the username", 9015) await userClass.sendError("Password must not contain the username", 9015)
return return
# |Tom| Au lieu d'utiliser userList, faire une requête à la base de donnée pour savoir si on a un utilisateur avec cet email ou cet username
if (content["mail"] in userList): if (content["mail"] in userList):
await userClass.sendError("Mail already used", 9016) await userClass.sendError("Mail already used", 9016)
return return

View File

@ -3,10 +3,10 @@
# ::: :::::::: # # ::: :::::::: #
# login.py :+: :+: :+: # # login.py :+: :+: :+: #
# +:+ +:+ +:+ # # +:+ +:+ +:+ #
# By: edbernar <edbernar@student.42.fr> +#+ +:+ +#+ # # By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ # # +#+#+#+#+#+ +#+ #
# Created: 2024/08/03 08:10:38 by edbernar #+# #+# # # Created: 2024/08/03 08:10:38 by edbernar #+# #+# #
# Updated: 2024/08/09 09:41:55 by edbernar ### ########.fr # # Updated: 2024/08/10 15:59:54 by edbernar ### ########.fr #
# # # #
# **************************************************************************** # # **************************************************************************** #
@ -22,41 +22,37 @@ import os
# --> {"type" : "login", "content" : {"username": "". "token": "", "id": 0}} # --> {"type" : "login", "content" : {"username": "". "token": "", "id": 0}}
userList = [ userList = [
{
"username": "Nexalith",
"token": "IDSNCSDAd465sd13215421",
"mail": "eddy@ediwor.fr",
"password": "ABC123",
"id": 9999999,
'id42': 123456
},
{ {
"username": "Eddy", "username": "Eddy",
"token": "54dsadw8f4a6w5f4a62s4f984fa62f4as65", "token": "54dsadw8f4a6w5f4a62s4f984fa62f4as65",
"mail": "aaaaa", "mail": "aaaaa",
"password": "ed968e840d10d2d313a870bc131a4e2c311d7ad09bdf32b3418147221f51a6e2", # not hashed : aaaaa "password": "ed968e840d10d2d313a870bc131a4e2c311d7ad09bdf32b3418147221f51a6e2", # not hashed : aaaaa
"id": 2135421 "id": 2135421,
"id42": -1
}, },
{ {
"username": "Hugo", "username": "Hugo",
"token": "dsa4d6sa4sa1hfd1jhgk6g4k21bn65m4nb4", "token": "dsa4d6sa4sa1hfd1jhgk6g4k21bn65m4nb4",
"mail": "bbbbb", "mail": "bbbbb",
"password": "bbbbb", "password": "bbbbb",
"id": 9892154 "id": 9892154,
"id42": -1
}, },
{ {
"username": "Mathis", "username": "Mathis",
"token": "8cb1qjlfndc12mn2l1mn654xzkkhad54cxz", "token": "8cb1qjlfndc12mn2l1mn654xzkkhad54cxz",
"mail": "ccccc", "mail": "ccccc",
"password": "6304fbfe2b22557c34c42a70056616786a733b3d09fb326308c813d6ab712ec0", # not hashed : ccccc "password": "6304fbfe2b22557c34c42a70056616786a733b3d09fb326308c813d6ab712ec0", # not hashed : ccccc
"id": 2371234 "id": 2371234,
"id42": -1
}, },
{ {
"username": "Tom", "username": "Tom",
"token": "poiuygfvbdsv5c21vcxvcxhgbjqnkmds546", "token": "poiuygfvbdsv5c21vcxvcxhgbjqnkmds546",
"mail": "ddddd", "mail": "ddddd",
"password": "ddddd", "password": "ddddd",
"id": 6423457 "id": 6423457,
"id42": -1
} }
] ]
@ -92,9 +88,9 @@ async def loginBy42(userClass, content):
# |TOM| Requete pour récuperer les informations de l'utilisateur selon l'intra de la personne # |TOM| Requete pour récuperer les informations de l'utilisateur selon l'intra de la personne
# et créer un token si celui-ci n'existe pas # et créer un token si celui-ci n'existe pas
try: try:
main42login(content) await main42login(userClass, content, userList)
except Exception as e: except Exception as e:
await userClass.sendError("Invalid 42 token", 9008, e) await userClass.sendError("Invalid 42 token", 9010, e)
async def login(userClass, content): async def login(userClass, content):
# |TOM| Faire 3 types de requêtes: # |TOM| Faire 3 types de requêtes:

View File

@ -6,7 +6,7 @@
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ # # By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ # # +#+#+#+#+#+ +#+ #
# Created: 2024/08/09 09:32:17 by edbernar #+# #+# # # Created: 2024/08/09 09:32:17 by edbernar #+# #+# #
# Updated: 2024/08/10 00:42:38 by edbernar ### ########.fr # # Updated: 2024/08/10 16:06:09 by edbernar ### ########.fr #
# # # #
# **************************************************************************** # # **************************************************************************** #
@ -17,8 +17,9 @@ import os
UID42 = os.environ.get("uid") UID42 = os.environ.get("uid")
SECRET42 = os.environ.get("secret") SECRET42 = os.environ.get("secret")
TOKENURL = 'https://api.intra.42.fr/oauth/token' TOKENURL = 'https://api.intra.42.fr/oauth/token'
INFOURL = 'https://api.intra.42.fr/v2/me' INFOURL = 'https://api.intra.42.fr/v2/me'
REDIRECT = 'http://127.0.0.1:5500/site/'
# |Eddy| Changer le redirect quand il y aura un vrai serveur
access_token = "" access_token = ""
@ -26,27 +27,46 @@ if (UID42 == None or SECRET42 == None):
print("Please set the environment variables uid and secret") print("Please set the environment variables uid and secret")
exit() exit()
def main42login(content): async def main42login(userClass, content, userList):
global access_token global access_token
print(content['token'])
data = {
'grant_type': 'authorization_code',
'client_id': UID42,
'client_secret': SECRET42,
'code': content['token'],
'redirect_uri': REDIRECT
}
response = requests.post(TOKENURL, data=data)
if (response.status_code != 200):
raise Exception(f"Problem with the request (access_token {response.status_code})")
response = response.json()
headers = {
'Authorization': f'Bearer {response["access_token"]}',
}
response = requests.get(INFOURL, headers=headers)
if (response.status_code != 200):
raise Exception(f"Problem with the request (user info {response.status_code})")
response = response.json()
# |Tom| Au lieu d'utiliser userList, faire une requête à la base de donnée pour savoir si on a un utilisateur avec cet id42
i = 0
while (i < len(userList)):
if (userList[i]['id42'] == response['id']):
break
i += 1
if (i == len(userList)):
await userClass.sendError("Not user registered with this 42 account", 9011)
return
else:
await userClass.send({
"type": "login",
"content": {
"username": userList[i]['username'],
"token": userList[i]['token'],
"id": userList[i]['id']
}
})
try:
data = {
'grant_type': 'client_credentials',
'client_id': UID42,
'client_secret': SECRET42,
}
response = requests.post(TOKENURL, data=data)
access_token = response.json()["access_token"]
print("Access Token: ", access_token)
headers = {
'Authorization': 'Bearer ' + access_token,
}
response = requests.get(INFOURL, headers=headers)
print("Code: ", response.status_code)
response = response.json()
print(response)
except Exception as e:
print("Error in main42login")
print(e)