File size: 7,345 Bytes
7c53168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# 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)