thejagstudio commited on
Commit
92f34a6
·
verified ·
1 Parent(s): 0cd3ec3

Upload 48 files

Browse files
authentication/__pycache__/models.cpython-39.pyc CHANGED
Binary files a/authentication/__pycache__/models.cpython-39.pyc and b/authentication/__pycache__/models.cpython-39.pyc differ
 
authentication/__pycache__/views.cpython-39.pyc CHANGED
Binary files a/authentication/__pycache__/views.cpython-39.pyc and b/authentication/__pycache__/views.cpython-39.pyc differ
 
authentication/migrations/0005_userdata_refcode.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated by Django 4.2.16 on 2024-10-24 17:14
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+ dependencies = [
8
+ ("authentication", "0004_coupon_discription"),
9
+ ]
10
+
11
+ operations = [
12
+ migrations.AddField(
13
+ model_name="userdata",
14
+ name="refCode",
15
+ field=models.CharField(default="", max_length=50),
16
+ ),
17
+ ]
authentication/migrations/__pycache__/0005_userdata_refcode.cpython-39.pyc ADDED
Binary file (613 Bytes). View file
 
authentication/models.py CHANGED
@@ -38,6 +38,7 @@ class Coupon(models.Model):
38
 
39
  class UserData(models.Model):
40
  user = models.ForeignKey(User, on_delete=models.CASCADE)
 
41
  phone = models.CharField(max_length=15)
42
  birthDate = models.DateField()
43
  gender = models.CharField(max_length=10)
 
38
 
39
  class UserData(models.Model):
40
  user = models.ForeignKey(User, on_delete=models.CASCADE)
41
+ refCode = models.CharField(max_length=50, default="")
42
  phone = models.CharField(max_length=15)
43
  birthDate = models.DateField()
44
  gender = models.CharField(max_length=10)
authentication/views.py CHANGED
@@ -1,252 +1,252 @@
1
- # authentication/views.py
2
-
3
- from django.contrib.auth.models import User
4
- from django.contrib.auth import authenticate
5
- from django.http import JsonResponse
6
- from rest_framework.views import APIView
7
- from django.views.decorators.csrf import csrf_exempt
8
- import json
9
- from rest_framework_simplejwt.tokens import RefreshToken
10
- from rest_framework.permissions import IsAuthenticated, AllowAny
11
- from django.core.mail import send_mail
12
- import random
13
- from django.utils import timezone
14
- from datetime import timedelta
15
- from .models import UserData
16
-
17
- # In-memory storage for OTPs (use a persistent storage in production)
18
- OTP_STORAGE = {}
19
-
20
-
21
- class RegisterView(APIView):
22
- authentication_classes = ()
23
- permission_classes = () # Allow any
24
-
25
- def post(self, request):
26
- try:
27
- data = json.loads(request.body)
28
- email = data.get('email')
29
- password = data.get('password')
30
- first_name = data.get('first_name')
31
- last_name = data.get('last_name')
32
-
33
- if User.objects.filter(email=email).exists():
34
- return JsonResponse({'error': 'Email already exists'}, status=400)
35
-
36
- user = User.objects.create_user(
37
- username=email,
38
- email=email,
39
- password=password,
40
- first_name=first_name,
41
- last_name=last_name
42
- )
43
- user.save()
44
- otp = random.randint(100000, 999999)
45
- OTP_STORAGE[email] = {
46
- 'otp': otp,
47
- 'expires_at': timezone.now() + timedelta(minutes=10) # OTP valid for 10 minutes
48
- }
49
- print(otp)
50
- # Send OTP via email
51
- send_mail(
52
- 'Password Reset OTP',
53
- f'Your OTP for password reset is {otp}',
54
- '[email protected]', # Replace with your email
55
- [email],
56
- fail_silently=False,
57
- )
58
- return JsonResponse({'message': 'User registered successfully'}, status=201)
59
- except Exception as e:
60
- return JsonResponse({'error': str(e)}, status=400)
61
-
62
-
63
- class LoginView(APIView):
64
- permission_classes = [AllowAny]
65
-
66
- def post(self, request):
67
- try:
68
- data = json.loads(request.body)
69
- username = data.get('username')
70
- password = data.get('password')
71
-
72
- user = authenticate(username=username, password=password)
73
- if user is not None:
74
- refresh = RefreshToken.for_user(user)
75
- userDataObj = UserData.objects.get(user=user)
76
- userData ={}
77
- userData['email'] = user.email
78
- userData['first_name'] = user.first_name
79
- userData['last_name'] = user.last_name
80
- userData['access'] = str(refresh.access_token)
81
- userData['refresh'] = str(refresh)
82
- userData["phone"] = userDataObj.phone
83
- userData["refCode"] = userDataObj.refCode
84
- userData["birthDate"] = userDataObj.birthDate
85
- userData["gender"] = userDataObj.gender
86
- userData["streetName"] = userDataObj.streetName
87
- userData["city"] = userDataObj.city
88
- userData["state"] = userDataObj.state
89
- userData["country"] = userDataObj.country
90
- userData["pincode"] = userDataObj.pincode
91
- userData["rewardPoints"] = userDataObj.rewardPoints
92
- userData["isVerified"] = userDataObj.isVerified
93
- userData["isSubscribed"] = userDataObj.isSubscribed
94
- userData["isBlocked"] = userDataObj.isBlocked
95
- userData["isDeleted"] = userDataObj.isDeleted
96
- return JsonResponse(userData, status=200)
97
- else:
98
- return JsonResponse({'error': 'Invalid credentials'}, status=401)
99
- except Exception as e:
100
- print(e)
101
- return JsonResponse({'error': str(e)}, status=400)
102
-
103
-
104
- class LogoutView(APIView):
105
- permission_classes = [IsAuthenticated]
106
-
107
- def post(self, request):
108
- refresh_token = request.data.get('refresh')
109
- if not refresh_token:
110
- return JsonResponse({
111
- 'error': 'Refresh token is required',
112
- 'status': 'error'
113
- }, status=400)
114
- else:
115
- try:
116
- refresh = RefreshToken(refresh_token)
117
- refresh.blacklist()
118
- return JsonResponse({
119
- 'status': 'success',
120
- 'message': 'Successfully logged out'
121
- })
122
- except :
123
- return JsonResponse({
124
- "error": "Invalid token",
125
- "status": "error"
126
- }, status=400)
127
-
128
-
129
-
130
- class RequestPasswordResetView(APIView):
131
- authentication_classes = ()
132
- permission_classes = () # Allow any
133
-
134
- def post(self, request):
135
- try:
136
- data = json.loads(request.body)
137
- email = data.get('email')
138
- if not email:
139
- return JsonResponse({'error': 'Email is required'}, status=400)
140
- try:
141
- user = User.objects.get(email=email)
142
- except User.DoesNotExist:
143
- return JsonResponse({'error': 'User with this email does not exist'}, status=400)
144
-
145
- # Generate OTP
146
- otp = random.randint(100000, 999999)
147
- OTP_STORAGE[email] = {
148
- 'otp': otp,
149
- 'expires_at': timezone.now() + timedelta(minutes=10) # OTP valid for 10 minutes
150
- }
151
- print(otp)
152
- # Send OTP via email
153
- send_mail(
154
- 'Password Reset OTP',
155
- f'Your OTP for password reset is {otp}',
156
- '[email protected]', # Replace with your email
157
- [email],
158
- fail_silently=False,
159
- )
160
-
161
- return JsonResponse({'message': 'OTP sent to email'}, status=200)
162
- except Exception as e:
163
- return JsonResponse({'error': str(e)}, status=400)
164
-
165
-
166
- class ResendOTPView(APIView):
167
- authentication_classes = ()
168
- permission_classes = () # Allow any
169
-
170
- def post(self, request):
171
- try:
172
- data = json.loads(request.body)
173
- email = data.get('email')
174
- if not email:
175
- return JsonResponse({'error': 'Email is required'}, status=400)
176
- try:
177
- user = User.objects.get(email=email)
178
- except User.DoesNotExist:
179
- return JsonResponse({'error': 'User with this email does not exist'}, status=400)
180
-
181
- # Generate new OTP
182
- otp = random.randint(100000, 999999)
183
- OTP_STORAGE[email] = {
184
- 'otp': otp,
185
- 'expires_at': timezone.now() + timedelta(minutes=10) # OTP valid for 10 minutes
186
- }
187
- print(otp)
188
- # Send OTP via email
189
- send_mail(
190
- 'Password Reset OTP',
191
- f'Your new OTP for password reset is {otp}',
192
- '[email protected]', # Replace with your email
193
- [email],
194
- fail_silently=False,
195
- )
196
-
197
- return JsonResponse({'message': 'OTP resent to email'}, status=200)
198
- except Exception as e:
199
- return JsonResponse({'error': str(e)}, status=400)
200
-
201
-
202
- class ResetPasswordView(APIView):
203
- authentication_classes = ()
204
- permission_classes = () # Allow any
205
-
206
- def post(self, request):
207
- try:
208
- data = json.loads(request.body)
209
- email = data.get('email')
210
- otp = data.get('otp')
211
- new_password = data.get('new_password')
212
-
213
- if not all([email, otp, new_password]):
214
- return JsonResponse({'error': 'All fields are required'}, status=400)
215
-
216
- otp_record = OTP_STORAGE.get(email)
217
- if not otp_record:
218
- return JsonResponse({'error': 'OTP not found. Please request a new one.'}, status=400)
219
-
220
- if timezone.now() > otp_record['expires_at']:
221
- del OTP_STORAGE[email]
222
- return JsonResponse({'error': 'OTP has expired. Please request a new one.'}, status=400)
223
-
224
- if int(otp) != otp_record['otp']:
225
- return JsonResponse({'error': 'Invalid OTP'}, status=400)
226
-
227
- try:
228
- user = User.objects.get(email=email)
229
- except User.DoesNotExist:
230
- return JsonResponse({'error': 'User with this email does not exist'}, status=400)
231
-
232
- user.set_password(new_password)
233
- user.save()
234
-
235
- # Remove OTP after successful reset
236
- del OTP_STORAGE[email]
237
-
238
- return JsonResponse({'message': 'Password reset successful'}, status=200)
239
- except Exception as e:
240
- return JsonResponse({'error': str(e)}, status=400)
241
-
242
- class refreshTokenView(APIView):
243
- def post(self, request):
244
- try:
245
- data = json.loads(request.body)
246
- refresh = data.get('refresh')
247
- token = RefreshToken(refresh)
248
- access = str(token.access_token)
249
- return JsonResponse({'access': access}, status=200)
250
- except Exception as e:
251
- return JsonResponse({'error': str(e)}, status=400)
252
 
 
1
+ # authentication/views.py
2
+
3
+ from django.contrib.auth.models import User
4
+ from django.contrib.auth import authenticate
5
+ from django.http import JsonResponse
6
+ from rest_framework.views import APIView
7
+ from django.views.decorators.csrf import csrf_exempt
8
+ import json
9
+ from rest_framework_simplejwt.tokens import RefreshToken
10
+ from rest_framework.permissions import IsAuthenticated, AllowAny
11
+ from django.core.mail import send_mail
12
+ import random
13
+ from django.utils import timezone
14
+ from datetime import timedelta
15
+ from .models import UserData
16
+
17
+ # In-memory storage for OTPs (use a persistent storage in production)
18
+ OTP_STORAGE = {}
19
+
20
+
21
+ class RegisterView(APIView):
22
+ authentication_classes = ()
23
+ permission_classes = () # Allow any
24
+
25
+ def post(self, request):
26
+ try:
27
+ data = json.loads(request.body)
28
+ email = data.get('email')
29
+ password = data.get('password')
30
+ first_name = data.get('first_name')
31
+ last_name = data.get('last_name')
32
+
33
+ if User.objects.filter(email=email).exists():
34
+ return JsonResponse({'error': 'Email already exists'}, status=400)
35
+
36
+ user = User.objects.create_user(
37
+ username=email,
38
+ email=email,
39
+ password=password,
40
+ first_name=first_name,
41
+ last_name=last_name
42
+ )
43
+ user.save()
44
+ otp = random.randint(100000, 999999)
45
+ OTP_STORAGE[email] = {
46
+ 'otp': otp,
47
+ 'expires_at': timezone.now() + timedelta(minutes=10) # OTP valid for 10 minutes
48
+ }
49
+ print(otp)
50
+ # Send OTP via email
51
+ send_mail(
52
+ 'Password Reset OTP',
53
+ f'Your OTP for password reset is {otp}',
54
+ '[email protected]', # Replace with your email
55
+ [email],
56
+ fail_silently=False,
57
+ )
58
+ return JsonResponse({'message': 'User registered successfully'}, status=201)
59
+ except Exception as e:
60
+ return JsonResponse({'error': str(e)}, status=400)
61
+
62
+
63
+ class LoginView(APIView):
64
+ permission_classes = [AllowAny]
65
+
66
+ def post(self, request):
67
+ try:
68
+ data = json.loads(request.body)
69
+ username = data.get('username')
70
+ password = data.get('password')
71
+
72
+ user = authenticate(username=username, password=password)
73
+ if user is not None:
74
+ refresh = RefreshToken.for_user(user)
75
+ userDataObj = UserData.objects.get(user=user)
76
+ userData ={}
77
+ userData['email'] = user.email
78
+ userData['first_name'] = user.first_name
79
+ userData['last_name'] = user.last_name
80
+ userData['access'] = str(refresh.access_token)
81
+ userData['refresh'] = str(refresh)
82
+ userData["phone"] = userDataObj.phone
83
+ userData["refCode"] = userDataObj.refCode
84
+ userData["birthDate"] = userDataObj.birthDate
85
+ userData["gender"] = userDataObj.gender
86
+ userData["streetName"] = userDataObj.streetName
87
+ userData["city"] = userDataObj.city
88
+ userData["state"] = userDataObj.state
89
+ userData["country"] = userDataObj.country
90
+ userData["pincode"] = userDataObj.pincode
91
+ userData["rewardPoints"] = userDataObj.rewardPoints
92
+ userData["isVerified"] = userDataObj.isVerified
93
+ userData["isSubscribed"] = userDataObj.isSubscribed
94
+ userData["isBlocked"] = userDataObj.isBlocked
95
+ userData["isDeleted"] = userDataObj.isDeleted
96
+ return JsonResponse(userData, status=200)
97
+ else:
98
+ return JsonResponse({'error': 'Invalid credentials'}, status=401)
99
+ except Exception as e:
100
+ print(e)
101
+ return JsonResponse({'error': str(e)}, status=400)
102
+
103
+
104
+ class LogoutView(APIView):
105
+ permission_classes = [IsAuthenticated]
106
+
107
+ def post(self, request):
108
+ refresh_token = request.data.get('refresh')
109
+ if not refresh_token:
110
+ return JsonResponse({
111
+ 'error': 'Refresh token is required',
112
+ 'status': 'error'
113
+ }, status=400)
114
+ else:
115
+ try:
116
+ refresh = RefreshToken(refresh_token)
117
+ refresh.blacklist()
118
+ return JsonResponse({
119
+ 'status': 'success',
120
+ 'message': 'Successfully logged out'
121
+ })
122
+ except :
123
+ return JsonResponse({
124
+ "error": "Invalid token",
125
+ "status": "error"
126
+ }, status=400)
127
+
128
+
129
+
130
+ class RequestPasswordResetView(APIView):
131
+ authentication_classes = ()
132
+ permission_classes = () # Allow any
133
+
134
+ def post(self, request):
135
+ try:
136
+ data = json.loads(request.body)
137
+ email = data.get('email')
138
+ if not email:
139
+ return JsonResponse({'error': 'Email is required'}, status=400)
140
+ try:
141
+ user = User.objects.get(email=email)
142
+ except User.DoesNotExist:
143
+ return JsonResponse({'error': 'User with this email does not exist'}, status=400)
144
+
145
+ # Generate OTP
146
+ otp = random.randint(100000, 999999)
147
+ OTP_STORAGE[email] = {
148
+ 'otp': otp,
149
+ 'expires_at': timezone.now() + timedelta(minutes=10) # OTP valid for 10 minutes
150
+ }
151
+ print(otp)
152
+ # Send OTP via email
153
+ send_mail(
154
+ 'Password Reset OTP',
155
+ f'Your OTP for password reset is {otp}',
156
+ '[email protected]', # Replace with your email
157
+ [email],
158
+ fail_silently=False,
159
+ )
160
+
161
+ return JsonResponse({'message': 'OTP sent to email'}, status=200)
162
+ except Exception as e:
163
+ return JsonResponse({'error': str(e)}, status=400)
164
+
165
+
166
+ class ResendOTPView(APIView):
167
+ authentication_classes = ()
168
+ permission_classes = () # Allow any
169
+
170
+ def post(self, request):
171
+ try:
172
+ data = json.loads(request.body)
173
+ email = data.get('email')
174
+ if not email:
175
+ return JsonResponse({'error': 'Email is required'}, status=400)
176
+ try:
177
+ user = User.objects.get(email=email)
178
+ except User.DoesNotExist:
179
+ return JsonResponse({'error': 'User with this email does not exist'}, status=400)
180
+
181
+ # Generate new OTP
182
+ otp = random.randint(100000, 999999)
183
+ OTP_STORAGE[email] = {
184
+ 'otp': otp,
185
+ 'expires_at': timezone.now() + timedelta(minutes=10) # OTP valid for 10 minutes
186
+ }
187
+ print(otp)
188
+ # Send OTP via email
189
+ send_mail(
190
+ 'Password Reset OTP',
191
+ f'Your new OTP for password reset is {otp}',
192
+ '[email protected]', # Replace with your email
193
+ [email],
194
+ fail_silently=False,
195
+ )
196
+
197
+ return JsonResponse({'message': 'OTP resent to email'}, status=200)
198
+ except Exception as e:
199
+ return JsonResponse({'error': str(e)}, status=400)
200
+
201
+
202
+ class ResetPasswordView(APIView):
203
+ authentication_classes = ()
204
+ permission_classes = () # Allow any
205
+
206
+ def post(self, request):
207
+ try:
208
+ data = json.loads(request.body)
209
+ email = data.get('email')
210
+ otp = data.get('otp')
211
+ new_password = data.get('new_password')
212
+
213
+ if not all([email, otp, new_password]):
214
+ return JsonResponse({'error': 'All fields are required'}, status=400)
215
+
216
+ otp_record = OTP_STORAGE.get(email)
217
+ if not otp_record:
218
+ return JsonResponse({'error': 'OTP not found. Please request a new one.'}, status=400)
219
+
220
+ if timezone.now() > otp_record['expires_at']:
221
+ del OTP_STORAGE[email]
222
+ return JsonResponse({'error': 'OTP has expired. Please request a new one.'}, status=400)
223
+
224
+ if int(otp) != otp_record['otp']:
225
+ return JsonResponse({'error': 'Invalid OTP'}, status=400)
226
+
227
+ try:
228
+ user = User.objects.get(email=email)
229
+ except User.DoesNotExist:
230
+ return JsonResponse({'error': 'User with this email does not exist'}, status=400)
231
+
232
+ user.set_password(new_password)
233
+ user.save()
234
+
235
+ # Remove OTP after successful reset
236
+ del OTP_STORAGE[email]
237
+
238
+ return JsonResponse({'message': 'Password reset successful'}, status=200)
239
+ except Exception as e:
240
+ return JsonResponse({'error': str(e)}, status=400)
241
+
242
+ class refreshTokenView(APIView):
243
+ def post(self, request):
244
+ try:
245
+ data = json.loads(request.body)
246
+ refresh = data.get('refresh')
247
+ token = RefreshToken(refresh)
248
+ access = str(token.access_token)
249
+ return JsonResponse({'access': access}, status=200)
250
+ except Exception as e:
251
+ return JsonResponse({'error': str(e)}, status=400)
252