-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathviews.py
497 lines (389 loc) · 17.7 KB
/
views.py
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
from rest_framework import permissions, generics, status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.contrib.auth import login
from knox.auth import TokenAuthentication
from knox.views import LoginView as KnoxLoginView
from blissedmaths.utils import phone_validator, password_generator, otp_generator
from .serializers import (CreateUserSerializer, ChangePasswordSerializer,
UserSerializer, LoginUserSerializer, ForgetPasswordSerializer)
from accounts.models import User, PhoneOTP
from django.shortcuts import get_object_or_404
from django.db.models import Q
import requests
from rest_framework.views import APIView
class LoginAPI(KnoxLoginView):
permission_classes = (permissions.AllowAny,)
def post(self, request, format=None):
serializer = LoginUserSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
if user.last_login is None :
user.first_login = True
user.save()
elif user.first_login:
user.first_login = False
user.save()
login(request, user)
return super().post(request, format=None)
class UserAPI(generics.RetrieveAPIView):
authentication_classes = (TokenAuthentication,)
permission_classes = [permissions.IsAuthenticated, ]
serializer_class = UserSerializer
def get_object(self):
return self.request.user
class ChangePasswordAPI(generics.UpdateAPIView):
"""
Change password endpoint view
"""
authentication_classes = (TokenAuthentication, )
serializer_class = ChangePasswordSerializer
permission_classes = [permissions.IsAuthenticated, ]
def get_object(self, queryset=None):
"""
Returns current logged in user instance
"""
obj = self.request.user
return obj
def update(self, request, *args, **kwargs):
self.object = self.get_object()
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
if not self.object.check_password(serializer.data.get('password_1')):
return Response({
'status': False,
'current_password': 'Does not match with our data',
}, status=status.HTTP_400_BAD_REQUEST)
self.object.set_password(serializer.data.get('password_2'))
self.object.password_changed = True
self.object.save()
return Response({
"status": True,
"detail": "Password has been successfully changed.",
})
return Response(serializer.error, status=status.HTTP_400_BAD_REQUEST)
def send_otp(phone):
"""
This is an helper function to send otp to session stored phones or
passed phone number as argument.
"""
if phone:
key = otp_generator()
phone = str(phone)
otp_key = str(key)
#link = f'https://2factor.in/API/R1/?module=TRANS_SMS&apikey=fc9e5177-b3e7-11e8-a895-0200cd936042&to={phone}&from=wisfrg&templatename=wisfrags&var1={otp_key}'
#result = requests.get(link, verify=False)
return otp_key
else:
return False
def send_otp_forgot(phone):
if phone:
key = otp_generator()
phone = str(phone)
otp_key = str(key)
user = get_object_or_404(User, phone__iexact = phone)
if user.name:
name = user.name
else:
name = phone
#link = f'https://2factor.in/API/R1/?module=TRANS_SMS&apikey=fc9e5177-b3e7-11e8-a895-0200cd936042&to={phone}&from=wisfgs&templatename=Wisfrags&var1={name}&var2={otp_key}'
#result = requests.get(link, verify=False)
#print(result)
return otp_key
else:
return False
############################################################################################################################################################################################
################################################################################################################################################################
class ValidatePhoneSendOTP(APIView):
'''
This class view takes phone number and if it doesn't exists already then it sends otp for
first coming phone numbers'''
def post(self, request, *args, **kwargs):
phone_number = request.data.get('phone')
if phone_number:
phone = str(phone_number)
user = User.objects.filter(phone__iexact = phone)
if user.exists():
return Response({'status': False, 'detail': 'Phone Number already exists'})
# logic to send the otp and store the phone number and that otp in table.
else:
otp = send_otp(phone)
print(phone, otp)
if otp:
otp = str(otp)
count = 0
old = PhoneOTP.objects.filter(phone__iexact = phone)
if old.exists():
count = old.first().count
old.first().count = count + 1
old.first().save()
else:
count = count + 1
PhoneOTP.objects.create(
phone = phone,
otp = otp,
count = count
)
if count > 7:
return Response({
'status' : False,
'detail' : 'Maximum otp limits reached. Kindly support our customer care or try with different number'
})
else:
return Response({
'status': 'False', 'detail' : "OTP sending error. Please try after some time."
})
return Response({
'status': True, 'detail': 'Otp has been sent successfully.'
})
else:
return Response({
'status': 'False', 'detail' : "I haven't received any phone number. Please do a POST request."
})
class ValidateOTP(APIView):
'''
If you have received otp, post a request with phone and that otp and you will be redirected to set the password
'''
def post(self, request, *args, **kwargs):
phone = request.data.get('phone', False)
otp_sent = request.data.get('otp', False)
if phone and otp_sent:
old = PhoneOTP.objects.filter(phone__iexact = phone)
if old.exists():
old = old.first()
otp = old.otp
if str(otp) == str(otp_sent):
old.logged = True
old.save()
return Response({
'status' : True,
'detail' : 'OTP matched, kindly proceed to save password'
})
else:
return Response({
'status' : False,
'detail' : 'OTP incorrect, please try again'
})
else:
return Response({
'status' : False,
'detail' : 'Phone not recognised. Kindly request a new otp with this number'
})
else:
return Response({
'status' : 'False',
'detail' : 'Either phone or otp was not recieved in Post request'
})
class Register(APIView):
'''Takes phone and a password and creates a new user only if otp was verified and phone is new'''
def post(self, request, *args, **kwargs):
phone = request.data.get('phone', False)
password = request.data.get('password', False)
if phone and password:
phone = str(phone)
user = User.objects.filter(phone__iexact = phone)
if user.exists():
return Response({'status': False, 'detail': 'Phone Number already have account associated. Kindly try forgot password'})
else:
old = PhoneOTP.objects.filter(phone__iexact = phone)
if old.exists():
old = old.first()
if old.logged:
Temp_data = {'phone': phone, 'password': password }
serializer = CreateUserSerializer(data=Temp_data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
user.save()
old.delete()
return Response({
'status' : True,
'detail' : 'Congrts, user has been created successfully.'
})
else:
return Response({
'status': False,
'detail': 'Your otp was not verified earlier. Please go back and verify otp'
})
else:
return Response({
'status' : False,
'detail' : 'Phone number not recognised. Kindly request a new otp with this number'
})
else:
return Response({
'status' : 'False',
'detail' : 'Either phone or password was not recieved in Post request'
})
class ValidatePhoneForgot(APIView):
'''
Validate if account is there for a given phone number and then send otp for forgot password reset'''
def post(self, request, *args, **kwargs):
phone_number = request.data.get('phone')
if phone_number:
phone = str(phone_number)
user = User.objects.filter(phone__iexact = phone)
if user.exists():
otp = send_otp_forgot(phone)
print(phone, otp)
if otp:
otp = str(otp)
count = 0
old = PhoneOTP.objects.filter(phone__iexact = phone)
if old.exists():
old = old.first()
k = old.count
if k > 10:
return Response({
'status' : False,
'detail' : 'Maximum otp limits reached. Kindly support our customer care or try with different number'
})
old.count = k + 1
old.save()
return Response({'status': True, 'detail': 'OTP has been sent for password reset. Limits about to reach.'})
else:
count = count + 1
PhoneOTP.objects.create(
phone = phone,
otp = otp,
count = count,
forgot = True,
)
return Response({'status': True, 'detail': 'OTP has been sent for password reset'})
else:
return Response({
'status': 'False', 'detail' : "OTP sending error. Please try after some time."
})
else:
return Response({
'status' : False,
'detail' : 'Phone number not recognised. Kindly try a new account for this number'
})
# class ValidatePhoneSendOTP(APIView):
# '''
# This class view takes phone number and if it doesn't exists already then it sends otp for
# first coming phone numbers'''
# def post(self, request, *args, **kwargs):
# phone_number = request.data.get('phone')
# if phone_number:
# phone = str(phone_number)
# user = User.objects.filter(phone__iexact = phone)
# if user.exists():
# return Response({'status': False, 'detail': 'Phone Number already exists'})
# # logic to send the otp and store the phone number and that otp in table.
# else:
# otp = send_otp(phone)
# print(phone, otp)
# if otp:
# otp = str(otp)
# count = 0
# old = PhoneOTP.objects.filter(phone__iexact = phone)
# if old.exists():
# count = old.first().count
# old.first().count = count + 1
# old.first().save()
# else:
# count = count + 1
# PhoneOTP.objects.create(
# phone = phone,
# otp = otp,
# count = count
# )
# if count > 7:
# return Response({
# 'status' : False,
# 'detail' : 'Maximum otp limits reached. Kindly support our customer care or try with different number'
# })
# else:
# return Response({
# 'status': 'False', 'detail' : "OTP sending error. Please try after some time."
# })
# return Response({
# 'status': True, 'detail': 'Otp has been sent successfully.'
# })
# else:
# return Response({
# 'status': 'False', 'detail' : "I haven't received any phone number. Please do a POST request."
# })
class ForgotValidateOTP(APIView):
'''
If you have received an otp, post a request with phone and that otp and you will be redirected to reset the forgotted password
'''
def post(self, request, *args, **kwargs):
phone = request.data.get('phone', False)
otp_sent = request.data.get('otp', False)
if phone and otp_sent:
old = PhoneOTP.objects.filter(phone__iexact = phone)
if old.exists():
old = old.first()
if old.forgot == False:
return Response({
'status' : False,
'detail' : 'This phone havenot send valid otp for forgot password. Request a new otp or contact help centre.'
})
otp = old.otp
if str(otp) == str(otp_sent):
old.forgot_logged = True
old.save()
return Response({
'status' : True,
'detail' : 'OTP matched, kindly proceed to create new password'
})
else:
return Response({
'status' : False,
'detail' : 'OTP incorrect, please try again'
})
else:
return Response({
'status' : False,
'detail' : 'Phone not recognised. Kindly request a new otp with this number'
})
else:
return Response({
'status' : 'False',
'detail' : 'Either phone or otp was not recieved in Post request'
})
class ForgetPasswordChange(APIView):
'''
if forgot_logged is valid and account exists then only pass otp, phone and password to reset the password. All three should match.APIView
'''
def post(self, request, *args, **kwargs):
phone = request.data.get('phone', False)
otp = request.data.get("otp", False)
password = request.data.get('password', False)
if phone and otp and password:
old = PhoneOTP.objects.filter(Q(phone__iexact = phone) & Q(otp__iexact = otp))
if old.exists():
old = old.first()
if old.forgot_logged:
post_data = {
'phone' : phone,
'password' : password
}
user_obj = get_object_or_404(User, phone__iexact=phone)
serializer = ForgetPasswordSerializer(data = post_data)
serializer.is_valid(raise_exception = True)
if user_obj:
user_obj.set_password(serializer.data.get('password'))
user_obj.active = True
user_obj.save()
old.delete()
return Response({
'status' : True,
'detail' : 'Password changed successfully. Please Login'
})
else:
return Response({
'status' : False,
'detail' : 'OTP Verification failed. Please try again in previous step'
})
else:
return Response({
'status' : False,
'detail' : 'Phone and otp are not matching or a new phone has entered. Request a new otp in forgot password'
})
else:
return Response({
'status' : False,
'detail' : 'Post request have parameters mising.'
})