From 16172283405c3a6de7bd2d69f9e9f053f36b015f Mon Sep 17 00:00:00 2001 From: rexcom28 Date: Mon, 29 May 2023 10:22:45 -0600 Subject: [PATCH] LoginIMMEX api --- IMMEX/views.py | 41 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/IMMEX/views.py b/IMMEX/views.py index 9eac01b..e2d9fa9 100644 --- a/IMMEX/views.py +++ b/IMMEX/views.py @@ -1,7 +1,7 @@ from django.shortcuts import render from allauth.account.models import EmailConfirmation, EmailAddress - +from django.contrib.auth.models import User from django.http import JsonResponse from django.urls import reverse_lazy, reverse from django.core.mail import send_mail @@ -15,7 +15,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .forms import ClienteForm_IMMEX from .serializers import ClientesA24Serailizer,SerialiazerA24 - +from rest_framework.authentication import TokenAuthentication from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status @@ -77,8 +77,41 @@ class ClientesIMMEX_CreateView(CreateView): return response """---------API VIEWS---------""" -class LoginIMMEX(APIView): - pass +from rest_framework.authtoken.models import Token +from rest_framework import authentication, permissions, views + +class LoginIMMEX(views.APIView): + authentication_classes = [authentication.TokenAuthentication] + permission_classes = [permissions.IsAuthenticated, permissions.HasAuthorizationHeader] + + def post(self, request): + try: + username = request.data.get('username') + password = request.data.get('password') + + user = authentication.authenticate(request, username=username, password=password) + + if user is not None: + email_address = user.emailaddress_set.first() + + if email_address: + if email_address.verified: + # User is authenticated and email is verified + # Proceed with session creation or any other logic + token, created = Token.objects.get_or_create(user=user) + return Response({'access': True, 'token': token.key}) + else: + return Response({'access': False, 'message': 'El correo asociado con este usuario no está verificado.'}) + else: + return Response({'access': False, 'message': 'No se encuentra una dirección de correo asociada con este usuario.'}) + else: + return Response({'access': False, 'message': 'Credenciales de inicio de sesión inválidas.'}) + except authentication.exceptions.AuthenticationFailed as ex: + return Response({'access': False, 'message': 'Error de autenticación: ' + str(ex)}) + except Exception as ex: + return Response({'access': False, 'message': 'Error durante el inicio de sesión: ' + str(ex)}) + + class RegistroUsuarios(APIView): permission_classes = [ItsAdminToken]