# 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 import requests from django.utils import timezone from datetime import timedelta from .models import UserData import uuid # In-memory storage for OTPs (use a persistent storage in production) OTP_STORAGE = {} class RegisterView(APIView): permission_classes = [AllowAny] 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') phone = data.get('phone') birthDate = data.get('birthDate') gender = data.get('gender', 'male') streetName = data.get('streetName') city = data.get('city') state = data.get('state') country = data.get('country') pincode = data.get('pincode') getUpdates = data.get('getUpdates', False) birthDate = birthDate.split('T')[0] 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() userDataObj = UserData.objects.create( user=user, phone=phone, refCode=phone, birthDate=birthDate, gender=gender, streetName=streetName, city=city, state=state, country=country, pincode=pincode, isSubscribed=getUpdates ) 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, # ) # Add user to Revel system revel_payload = json.dumps({ "accept_checks": False, "account_balance": None, "account_limit": None, "active": True, "address": streetName, "birth_date": birthDate, "cc_exp": "03/22", "cc_first_name": first_name, "cc_last_name": last_name, "cc_last_4_digits": "1111", "city": city, "company_name": "B-Company", # "contract_expiration": "2019-05-16T00:00:00", "created_by": "/enterprise/User/9393/", "created_date": timezone.now().isoformat(), "customer_groups": [], "deleted": False, "discount": 0, "email": email, "email_opt_in": getUpdates, # "exp_date": "1919-05-16T00:00:00", "expensify_account": f'{{"{email}":["193"]}}', "first_name": first_name, "gender": 0 if gender.lower() == 'male' else 1, "gift_card_numbers": [], "is_visitor": False, "last_name": last_name, "lic_number": "EAK173", "loyalty_number": None, "loyalty_ref_id": "", "notes": "New Customer", "ok_to_email": False, "past_due": 0, "phone_number": phone, "phone_opt_in": getUpdates, "pin": "", "post_opt_in": False, "ref_number": "1731-147709", "reward_card_numbers": [], "source": None, "state": state, "tax_exempt": False, # "tax_location": "CA Orange County", # "third_party_id": "1731147709", "title": "Mr" if gender == "male" else "Ms", "total_purchases": 0, "total_visits": 0, "track_as_company": True, "type": 1, "updated_by": "/enterprise/User/9393/", "updated_date": timezone.now().isoformat(), "uuid": uuid.uuid4().hex, "vehicles": [], "version_date": timezone.now().isoformat(), "zipcode": pincode }) revel_headers = { 'content-type': 'application/json', 'API-AUTHENTICATION': 'fab57498544244e38bfc2741880f8d61:ed9628295b0642e1b38308795c9cdadd58012df4ceb84a3b9d441c017a1eeac0' } revel_response = requests.post("https://101smokeshop-uat.revelup.com/resources/Customer/", headers=revel_headers, data=revel_payload) # print(revel_response.json()) userDataObj.revelId = revel_response.json()['id'] userDataObj.save() refresh = RefreshToken.for_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) except Exception as e: print(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 refresh = RefreshToken.for_user(user) userDataObj = UserData.objects.get(user=user) userData = {} userData['email'] = user.email userData['access'] = str(refresh.access_token) userData['refresh'] = str(refresh) 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) def post(self, request): try: user = request.user userDataObj = UserData.objects.get(user=user) data = json.loads(request.body) user.email = data.get('email', user.email) user.first_name = data.get('first_name', user.first_name) user.last_name = data.get('last_name', user.last_name) userDataObj.phone = data.get('phone', userDataObj.phone) userDataObj.refCode = data.get('phone', userDataObj.phone) userDataObj.birthDate = data.get('birthDate', userDataObj.birthDate).split('T')[0] userDataObj.gender = data.get('gender', userDataObj.gender) userDataObj.streetName = data.get('streetName', userDataObj.streetName) userDataObj.city = data.get('city', userDataObj.city) userDataObj.state = data.get('state', userDataObj.state) userDataObj.country = data.get('country', userDataObj.country) userDataObj.pincode = data.get('pincode', userDataObj.pincode) user.save() userDataObj.save() userData = {} refresh = RefreshToken.for_user(user) userData['email'] = user.email userData['access'] = str(refresh.access_token) userData['refresh'] = str(refresh) 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({'message': 'User data updated successfully', "data": userData}, status=200) except Exception as e: return JsonResponse({'error': str(e)}, status=400) 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)