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
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
# 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}',
            #     '[email protected]',  # 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}',
                '[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)


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)