Spaces:
Runtime error
Runtime error
# 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 django.core.mail import send_mail | |
import random | |
from django.utils import timezone | |
from datetime import timedelta | |
# 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}', | |
'[email protected]', # 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): | |
authentication_classes = () | |
permission_classes = () | |
def post(self, request): | |
try: | |
data = json.loads(request.body) | |
username = data.get('username') | |
password = data.get('password') | |
print(username, password) | |
user = authenticate(username=username, password=password) | |
if user is not None: | |
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) | |
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 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}', | |
'[email protected]', # 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}', | |
'[email protected]', # 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) | |