You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.8 KiB
Python

from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from osinacore.models import *
from .serializers import *
from django.contrib.auth import authenticate, login
from django.http import JsonResponse
@api_view(['POST'])
def register_customer(request):
if 'user' in request.data and 'customer' in request.data:
user_serializer = UserSerializer(data=request.data['user'])
if user_serializer.is_valid():
user = user_serializer.save()
customer_data = request.data['customer']
customer_serializer = CustomerProfileSerializer(data=customer_data)
if customer_serializer.is_valid():
customer_instance = customer_serializer.save(user=user)
return Response({'message': 'User and Customer registered successfully'}, status=status.HTTP_201_CREATED)
else:
return Response(customer_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
return Response({'message': 'User and Customer data are required'}, status=status.HTTP_400_BAD_REQUEST)
@api_view(['POST'])
def authenticate_customer(request):
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
return JsonResponse({'success': True})
else:
# Return the original email along with the error message
return JsonResponse({'success': False, 'error': 'Invalid credentials', 'email': email, 'password':password})