login and account creation now works using database
This commit is contained in:
@ -14,10 +14,10 @@ from django.urls import path
|
||||
from django.core.asgi import get_asgi_application
|
||||
from channels.sessions import SessionMiddlewareStack
|
||||
|
||||
from .websocket import WebsocketHandler
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')
|
||||
|
||||
from .websocket import WebsocketHandler
|
||||
|
||||
django = get_asgi_application()
|
||||
|
||||
application = ProtocolTypeRouter({
|
||||
|
@ -2,9 +2,10 @@ from django.db import models
|
||||
|
||||
class User(models.Model):
|
||||
id = models.AutoField(primary_key=True)
|
||||
nickname = models.CharField(max_length=20)
|
||||
mail = models.EmailField()
|
||||
username = models.CharField(max_length=20, unique=True)
|
||||
mail = models.EmailField(unique=True)
|
||||
password = models.CharField(max_length=100)
|
||||
id42 = models.DecimalField(decimal_places=0, unique=True, default=0)
|
||||
|
||||
class Message(models.Model):
|
||||
id = models.AutoField(primary_key=True)
|
||||
|
@ -27,7 +27,6 @@ DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = ['*']
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
@ -141,4 +140,3 @@ SESSION_COOKIE_SECURE = False
|
||||
SESSION_COOKIE_HTTPONLY = True
|
||||
SESSION_COOKIE_SAMESITE = 'Lax'
|
||||
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
|
||||
|
||||
|
@ -6,13 +6,16 @@
|
||||
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
||||
# +#+#+#+#+#+ +#+ #
|
||||
# Created: 2024/08/09 08:08:00 by edbernar #+# #+# #
|
||||
# Updated: 2024/08/24 01:11:45 by tomoron ### ########.fr #
|
||||
# Updated: 2024/08/25 14:49:14 by tomoron ### ########.fr #
|
||||
# #
|
||||
# **************************************************************************** #
|
||||
|
||||
from .login import userList
|
||||
from ..models import User
|
||||
import random
|
||||
import re
|
||||
import json
|
||||
import hashlib
|
||||
|
||||
pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).+$'
|
||||
|
||||
@ -49,30 +52,18 @@ def createAccount(socket, content):
|
||||
if (content["password"].find(content["username"]) != -1):
|
||||
socket.sendError("Password must not contain the username", 9015)
|
||||
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 (len(User.objects.filter(mail=content["mail"]))):
|
||||
socket.sendError("Mail already used", 9016)
|
||||
return
|
||||
if (content["username"] in userList):
|
||||
if (len(User.objects.filter(username=content["username"]))):
|
||||
socket.sendError("Username already used", 9017)
|
||||
return
|
||||
content["token"] = generateToken()
|
||||
while (True):
|
||||
content["id"] = random.randint(1000000, 9999999)
|
||||
if (content["id"] not in userList):
|
||||
break
|
||||
userList.append(content)
|
||||
socket.send(text_data=json.dumps({"type": "create_account", "content": "Account created"}))
|
||||
socket.scope["session"]["logged_in"] = True
|
||||
socket.scope["session"]["username"] = content["username"]
|
||||
socket.scope["session"].save()
|
||||
password = hashlib.md5((content["mail"] + content["password"]).encode()).hexdigest()
|
||||
new_user = User.objects.create(username=content["username"], mail=content["mail"], password=password)
|
||||
new_user.save()
|
||||
socket.send(text_data=json.dumps({"type": "create_account", "content": "Account created"}))
|
||||
except Exception as e:
|
||||
socket.sendError("Error create account", 9005, e)
|
||||
|
||||
def generateToken():
|
||||
list = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
token = ""
|
||||
|
||||
for i in range(0, 35):
|
||||
token += list[random.randint(0, len(list) - 1)]
|
||||
return token
|
@ -6,11 +6,13 @@
|
||||
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
|
||||
# +#+#+#+#+#+ +#+ #
|
||||
# Created: 2024/08/03 08:10:38 by edbernar #+# #+# #
|
||||
# Updated: 2024/08/24 01:11:15 by tomoron ### ########.fr #
|
||||
# Updated: 2024/08/25 15:20:21 by tomoron ### ########.fr #
|
||||
# #
|
||||
# **************************************************************************** #
|
||||
|
||||
from .login42.login42 import main42login
|
||||
from ..models import User
|
||||
import hashlib
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
@ -57,17 +59,16 @@ userList = [
|
||||
]
|
||||
|
||||
def loginByPass(socket, content):
|
||||
# |TOM| Requete pour savoir si le mail et le mot de passe sont valides
|
||||
# et créer un token si celui-ci n'existe pas
|
||||
for user in userList:
|
||||
if (user["mail"] == content["mail"] and user["password"] == content["password"]):
|
||||
jsonVar = {"type": "login", "content": {"username": user["username"]}}
|
||||
socket.scope["session"]["logged_in"] = True
|
||||
socket.scope["session"]["username"] = jsonVar["content"]["username"]
|
||||
socket.scope["session"].save()
|
||||
socket.send(text_data=json.dumps(jsonVar))
|
||||
return
|
||||
socket.send(text_data=json.dumps({"type": "error", "content": "Invalid username or password", "code": 9007}))
|
||||
password_hash = hashlib.md5((content["mail"] + content["password"]).encode()).hexdigest()
|
||||
user = User.objects.filter(mail=content["mail"], password=password_hash)
|
||||
if(len(user)):
|
||||
jsonVar = {"type": "login", "content": {"username": user[0].username}}
|
||||
socket.scope["session"]["logged_in"] = True
|
||||
socket.scope["session"]["username"] = jsonVar["content"]["username"]
|
||||
socket.scope["session"].save()
|
||||
socket.send(text_data=json.dumps(jsonVar))
|
||||
return
|
||||
socket.send(text_data=json.dumps({"type": "error", "content": "Invalid email or password", "code": 9007}))
|
||||
|
||||
|
||||
|
||||
@ -81,14 +82,11 @@ def loginBy42(socket, content):
|
||||
|
||||
def login(socket, content):
|
||||
# |TOM| Faire 3 types de requêtes:
|
||||
# - byToken: Récupérer les informations de l'utilisateur en fonction de son token
|
||||
# - nope
|
||||
# - byPass: Récupérer les informations de l'utilisateur en fonction de mail et de son mot de passe
|
||||
# - by42: Récupérer les informations de l'utilisateur en fonction de son token42 (qui sera different du token)
|
||||
# - will probably change
|
||||
print(json.dumps(content))
|
||||
try:
|
||||
# if (content["type"] == "byToken"):
|
||||
# loginByToken(socket, content)
|
||||
if (content["type"] == "byPass"):
|
||||
loginByPass(socket, content)
|
||||
elif (content["type"] == "by42"):
|
@ -1,11 +1,14 @@
|
||||
from channels.generic.websocket import WebsocketConsumer
|
||||
import json
|
||||
|
||||
from .typeRequets.getPrivateListMessage import getPrivateListMessage
|
||||
from .typeRequets.getPrivateListUser import getPrivateListUser
|
||||
from .typeRequets.sendPrivateMessage import sendPrivateMessage
|
||||
from .typeRequets.createAccount import createAccount
|
||||
from .typeRequets.login import login
|
||||
import django
|
||||
django.setup()
|
||||
|
||||
from .typeRequests.getPrivateListMessage import getPrivateListMessage
|
||||
from .typeRequests.getPrivateListUser import getPrivateListUser
|
||||
from .typeRequests.sendPrivateMessage import sendPrivateMessage
|
||||
from .typeRequests.createAccount import createAccount
|
||||
from .typeRequests.login import login
|
||||
|
||||
typeRequest = ["login", "get_private_list_user", "get_private_list_message",
|
||||
"send_private_message", "create_account"]
|
||||
@ -19,7 +22,10 @@ class WebsocketHandler(WebsocketConsumer):
|
||||
|
||||
def connect(self):
|
||||
self.accept()
|
||||
self.send(text_data=json.dumps({"type":"is_logged_in", "content":self.scope["session"].get("logged_in",False)}))
|
||||
self.send(text_data=json.dumps({"type":"logged_in", "content":{
|
||||
"status":self.scope["session"].get("logged_in",False),
|
||||
"username":self.scope["session"].get("username",None)
|
||||
}}))
|
||||
print("new client")
|
||||
|
||||
def disconnect(self, close_code):
|
||||
|
Reference in New Issue
Block a user