# authentication/views.py from django.contrib.auth.models import User from django.contrib.auth import authenticate from django.http import JsonResponse from rest_framework.views import APIView from django.views.decorators.csrf import csrf_exempt import json from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.permissions import IsAuthenticated, AllowAny from django.core.mail import send_mail import random from django.utils import timezone from datetime import timedelta from .models import UserData # In-memory storage for OTPs (use a persistent storage in production) OTP_STORAGE = {} class RegisterView(APIView): authentication_classes = () permission_classes = () # Allow any def post(self, request): try: data = json.loads(request.body) email = data.get('email') password = data.get('password') first_name = data.get('first_name') last_name = data.get('last_name') if User.objects.filter(email=email).exists(): return JsonResponse({'error': 'Email already exists'}, status=400) user = User.objects.create_user( username=email, email=email, password=password, first_name=first_name, last_name=last_name ) user.save() otp = random.randint(100000, 999999) OTP_STORAGE[email] = { 'otp': otp, 'expires_at': timezone.now() + timedelta(minutes=10) # OTP valid for 10 minutes } print(otp) # Send OTP via email send_mail( 'Password Reset OTP', f'Your OTP for password reset is {otp}', 'noreply@example.com', # Replace with your email [email], fail_silently=False, ) return JsonResponse({'message': 'User registered successfully'}, status=201) except Exception as e: return JsonResponse({'error': str(e)}, status=400) class LoginView(APIView): permission_classes = [AllowAny] def post(self, request): try: data = json.loads(request.body) username = data.get('username') password = data.get('password') user = authenticate(username=username, password=password) if user is not None: refresh = RefreshToken.for_user(user) userDataObj = UserData.objects.get(user=user) userData ={} userData['email'] = user.email userData['first_name'] = user.first_name userData['last_name'] = user.last_name userData['access'] = str(refresh.access_token) userData['refresh'] = str(refresh) userData["phone"] = userDataObj.phone userData["refCode"] = userDataObj.refCode userData["birthDate"] = userDataObj.birthDate userData["gender"] = userDataObj.gender userData["streetName"] = userDataObj.streetName userData["city"] = userDataObj.city userData["state"] = userDataObj.state userData["country"] = userDataObj.country userData["pincode"] = userDataObj.pincode userData["rewardPoints"] = userDataObj.rewardPoints userData["isVerified"] = userDataObj.isVerified userData["isSubscribed"] = userDataObj.isSubscribed userData["isBlocked"] = userDataObj.isBlocked userData["isDeleted"] = userDataObj.isDeleted return JsonResponse(userData, status=200) else: return JsonResponse({'error': 'Invalid credentials'}, status=401) except Exception as e: print(e) return JsonResponse({'error': str(e)}, status=400) class UserDetailView(APIView): permission_classes = [IsAuthenticated] def get(self, request): user = request.user userDataObj = UserData.objects.get(user=user) userData ={} userData['email'] = user.email userData['first_name'] = user.first_name userData['last_name'] = user.last_name userData["phone"] = userDataObj.phone userData["refCode"] = userDataObj.refCode userData["birthDate"] = userDataObj.birthDate userData["gender"] = userDataObj.gender userData["streetName"] = userDataObj.streetName userData["city"] = userDataObj.city userData["state"] = userDataObj.state userData["country"] = userDataObj.country userData["pincode"] = userDataObj.pincode userData["rewardPoints"] = userDataObj.rewardPoints userData["isVerified"] = userDataObj.isVerified userData["isSubscribed"] = userDataObj.isSubscribed userData["isBlocked"] = userDataObj.isBlocked userData["isDeleted"] = userDataObj.isDeleted return JsonResponse(userData, status=200) class LogoutView(APIView): permission_classes = [IsAuthenticated] def post(self, request): refresh_token = request.data.get('refresh') if not refresh_token: return JsonResponse({ 'error': 'Refresh token is required', 'status': 'error' }, status=400) else: try: refresh = RefreshToken(refresh_token) refresh.blacklist() return JsonResponse({ 'status': 'success', 'message': 'Successfully logged out' }) except : return JsonResponse({ "error": "Invalid token", "status": "error" }, status=400) class RequestPasswordResetView(APIView): authentication_classes = () permission_classes = () # Allow any def post(self, request): try: data = json.loads(request.body) email = data.get('email') if not email: return JsonResponse({'error': 'Email is required'}, status=400) try: user = User.objects.get(email=email) except User.DoesNotExist: return JsonResponse({'error': 'User with this email does not exist'}, status=400) # Generate OTP otp = random.randint(100000, 999999) OTP_STORAGE[email] = { 'otp': otp, 'expires_at': timezone.now() + timedelta(minutes=10) # OTP valid for 10 minutes } print(otp) # Send OTP via email send_mail( 'Password Reset OTP', f'Your OTP for password reset is {otp}', 'noreply@example.com', # Replace with your email [email], fail_silently=False, ) return JsonResponse({'message': 'OTP sent to email'}, status=200) except Exception as e: return JsonResponse({'error': str(e)}, status=400) class ResendOTPView(APIView): authentication_classes = () permission_classes = () # Allow any def post(self, request): try: data = json.loads(request.body) email = data.get('email') if not email: return JsonResponse({'error': 'Email is required'}, status=400) try: user = User.objects.get(email=email) except User.DoesNotExist: return JsonResponse({'error': 'User with this email does not exist'}, status=400) # Generate new OTP otp = random.randint(100000, 999999) OTP_STORAGE[email] = { 'otp': otp, 'expires_at': timezone.now() + timedelta(minutes=10) # OTP valid for 10 minutes } print(otp) # Send OTP via email send_mail( 'Password Reset OTP', f'Your new OTP for password reset is {otp}', 'noreply@example.com', # Replace with your email [email], fail_silently=False, ) return JsonResponse({'message': 'OTP resent to email'}, status=200) except Exception as e: return JsonResponse({'error': str(e)}, status=400) class ResetPasswordView(APIView): authentication_classes = () permission_classes = () # Allow any def post(self, request): try: data = json.loads(request.body) email = data.get('email') otp = data.get('otp') new_password = data.get('new_password') if not all([email, otp, new_password]): return JsonResponse({'error': 'All fields are required'}, status=400) otp_record = OTP_STORAGE.get(email) if not otp_record: return JsonResponse({'error': 'OTP not found. Please request a new one.'}, status=400) if timezone.now() > otp_record['expires_at']: del OTP_STORAGE[email] return JsonResponse({'error': 'OTP has expired. Please request a new one.'}, status=400) if int(otp) != otp_record['otp']: return JsonResponse({'error': 'Invalid OTP'}, status=400) try: user = User.objects.get(email=email) except User.DoesNotExist: return JsonResponse({'error': 'User with this email does not exist'}, status=400) user.set_password(new_password) user.save() # Remove OTP after successful reset del OTP_STORAGE[email] return JsonResponse({'message': 'Password reset successful'}, status=200) except Exception as e: return JsonResponse({'error': str(e)}, status=400) class refreshTokenView(APIView): def post(self, request): try: data = json.loads(request.body) refresh = data.get('refresh') token = RefreshToken(refresh) access = str(token.access_token) return JsonResponse({'access': access}, status=200) except Exception as e: return JsonResponse({'error': str(e)}, status=400)