diff --git a/api/utils.py b/api/utils.py new file mode 100644 index 0000000..bbe5dc2 --- /dev/null +++ b/api/utils.py @@ -0,0 +1,5 @@ +import re + +def is_valid_email(email): + email_regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' + return re.match(email_regex, email) is not None diff --git a/api/views.py b/api/views.py index 7092afd..ec5d64e 100644 --- a/api/views.py +++ b/api/views.py @@ -9,13 +9,14 @@ from rest_framework import status from rest_framework.generics import UpdateAPIView from rest_framework.exceptions import MethodNotAllowed from rest_framework.permissions import IsAuthenticated - -from django.contrib.auth import authenticate from rest_framework.views import APIView +from django.contrib.auth import authenticate from django.db.models import Q +from django.core.exceptions import ObjectDoesNotExist from .permissions import IsClubOwner +from .utils import is_valid_email class CustomAuthToken(APIView): permission_classes = [] @@ -24,8 +25,13 @@ class CustomAuthToken(APIView): username = request.data.get('username') password = request.data.get('password') device_id = request.data.get('device_id') + user = authenticate(username=username, password=password) + if user is None and is_valid_email(username) == True: + true_username = self.get_username_from_email(username) + user = authenticate(username=true_username, password=password) + if user is not None: if user.device_id is None or user.device_id == device_id or user.username == 'apple-test': @@ -39,6 +45,13 @@ class CustomAuthToken(APIView): else: return Response({'error': 'L\'utilisateur et le mot de passe de correspondent pas'}, status=status.HTTP_401_UNAUTHORIZED) + def get_username_from_email(self, email): + try: + user = CustomUser.objects.get(email=email) + return user.username + except ObjectDoesNotExist: + return None # or handle the case where the user doesn't exist + class Logout(APIView): permission_classes = (IsAuthenticated,)