django-chelseru 1.0.0__py3-none-any.whl → 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. {django_chelseru-1.0.0.dist-info → django_chelseru-1.0.1.dist-info}/METADATA +5 -3
  2. django_chelseru-1.0.1.dist-info/RECORD +22 -0
  3. django_chelseru-1.0.1.dist-info/top_level.txt +1 -0
  4. drfchelseru/admin.py +24 -0
  5. drfchelseru/apps.py +9 -0
  6. drfchelseru/middlewares.py +44 -0
  7. drfchelseru/migrations/0001_initial.py +33 -0
  8. drfchelseru/migrations/0002_otpcode_session_user.py +92 -0
  9. drfchelseru/migrations/0003_rename_mobile_otpcode_mobile_number.py +18 -0
  10. drfchelseru/models.py +77 -0
  11. drfchelseru/serializers.py +34 -0
  12. drfchelseru/services.py +239 -0
  13. drfchelseru/settings.py +174 -0
  14. drfchelseru/signals.py +38 -0
  15. drfchelseru/urls.py +11 -0
  16. drfchelseru/validators.py +15 -0
  17. drfchelseru/views.py +213 -0
  18. django_chelseru-1.0.0.dist-info/RECORD +0 -31
  19. django_chelseru-1.0.0.dist-info/top_level.txt +0 -3
  20. drf_chelseru_auth/admin.py +0 -3
  21. drf_chelseru_auth/apps.py +0 -6
  22. drf_chelseru_auth/models.py +0 -3
  23. drf_chelseru_auth/views.py +0 -3
  24. drf_chelseru_chat/__init__.py +0 -0
  25. drf_chelseru_chat/admin.py +0 -5
  26. drf_chelseru_chat/apps.py +0 -6
  27. drf_chelseru_chat/consumers.py +0 -82
  28. drf_chelseru_chat/middleware.py +0 -33
  29. drf_chelseru_chat/migrations/0001_initial.py +0 -36
  30. drf_chelseru_chat/migrations/__init__.py +0 -0
  31. drf_chelseru_chat/models.py +0 -23
  32. drf_chelseru_chat/routing.py +0 -6
  33. drf_chelseru_chat/serializers.py +0 -26
  34. drf_chelseru_chat/urls.py +0 -12
  35. drf_chelseru_chat/views.py +0 -59
  36. drf_chelseru_sms/__init__.py +0 -0
  37. drf_chelseru_sms/admin.py +0 -3
  38. drf_chelseru_sms/apps.py +0 -6
  39. drf_chelseru_sms/migrations/__init__.py +0 -0
  40. drf_chelseru_sms/models.py +0 -3
  41. drf_chelseru_sms/tests.py +0 -3
  42. drf_chelseru_sms/views.py +0 -3
  43. {django_chelseru-1.0.0.dist-info → django_chelseru-1.0.1.dist-info}/WHEEL +0 -0
  44. {django_chelseru-1.0.0.dist-info → django_chelseru-1.0.1.dist-info}/licenses/LICENSE +0 -0
  45. {drf_chelseru_auth → drfchelseru}/__init__.py +0 -0
  46. {drf_chelseru_auth → drfchelseru}/migrations/__init__.py +0 -0
  47. {drf_chelseru_auth → drfchelseru}/tests.py +0 -0
@@ -0,0 +1,174 @@
1
+ """
2
+ DJANGO_CHELSERU = {
3
+ 'AUTH': {
4
+ 'AUTH_METHOD' : 'OTP', # OTP, PASSWD
5
+ 'AUTH_SERVICE' : 'rest_framework_simplejwt', # rest_framework_simplejwt
6
+ 'OPTIONS': {
7
+ 'OTP_LENGTH' : 8, # DEFAULT 8
8
+ 'OTP_EXPIRE_PER_MINUTES': 4, # DEFAULT 4
9
+ 'SMS_TEMPLATE_ID': : 1,
10
+ }
11
+ },
12
+ 'SMS': {
13
+ 'SMS_SERVICE': 'PARSIAN_WEBCO_IR', # PARSIAN_WEBCO_IR , MELI_PAYAMAK_COM , KAVENEGAR_COM
14
+ 'OPTIONS': {
15
+ 'PARSIAN_WEBCO_IR_API_KEY' : '',
16
+ 'MELI_PAYAMAK_COM_USERNAME' : '',
17
+ 'MELI_PAYAMAK_COM_PASSWORD' : '',
18
+ 'MELI_PAYAMAK_COM_FROM' : '',
19
+ 'KAVENEGAR_COM_API_KEY' : '656F6635756C485658666F6A52307562456C4F5043714769597A58434D2B527974434534672B50445736553D',
20
+ 'KAVENEGAR_COM_FROM' : '2000660110',
21
+ }
22
+ }
23
+ }
24
+ """
25
+
26
+ from django.conf import settings
27
+ from django.core.exceptions import ImproperlyConfigured
28
+
29
+ SERVICE_NAME = 'DJANGO_CHELSERU'
30
+
31
+ AUTH_METHOD = [(0, 'OTP'), (1, 'PASSWD')]
32
+ AUTH_SERVICES = [(0, 'rest_framework_simplejwt')]
33
+ SMS_SERVICES = [(0, 'PARSIAN_WEBCO_IR'),(1, 'MELI_PAYAMAK_COM') ,(2, 'KAVENEGAR_COM')]
34
+
35
+ def auth_init_check():
36
+ try:
37
+ auth_mode = 'OTP'
38
+ auth_service = 'rest_framework_simplejwt'
39
+ options = {
40
+ 'len': 8,
41
+ 'exp_time': 4,
42
+ #'default_sms_template': 1
43
+ }
44
+ if not hasattr(settings, SERVICE_NAME):
45
+ raise ImproperlyConfigured(f'{SERVICE_NAME} must be defined in settings.py.')
46
+
47
+ else:
48
+ _auth = getattr(settings, SERVICE_NAME).get('AUTH')
49
+ if _auth:
50
+ _auth_mode = _auth.get('AUTH_MODE')
51
+ _auth_service = _auth.get('AUTH_SERVICE')
52
+ _opt_len = _auth.get('OPTIONS').get('OTP_LENGTH', 6)
53
+ _opt_exp_time = _auth.get('OPTIONS').get('OTP_EXPIRE_PER_MINUTES', 4)
54
+ _otp_sms_template = _auth.get('OPTIONS').get('SMS_TEMPLATE_ID', 0)
55
+
56
+ if _auth_mode:
57
+ if _auth_mode in list(map(lambda x: x[1], AUTH_METHOD)):
58
+ auth_mode = _auth_mode
59
+
60
+ else:
61
+ raise ImproperlyConfigured(f'AUTH_METHOD must be choice between {list(map(lambda x: x[1], AUTH_METHOD))}.')
62
+
63
+ if _auth_service:
64
+ if _auth_service not in list(map(lambda x: x[1], AUTH_SERVICES)):
65
+ raise ImproperlyConfigured(f'AUTH_SERVICES must be choice between {list(map(lambda x: x[1], AUTH_SERVICES))}.')
66
+ else:
67
+ auth_service = _auth_service
68
+
69
+ if _opt_len and isinstance(_opt_len, int):
70
+ if _opt_len < 3 or _opt_len > 10:
71
+ raise ImproperlyConfigured("OTP_LENGTH must be less than or equal to 10 and greater than or equal to 3.")
72
+
73
+ if _opt_exp_time and isinstance(_opt_exp_time, int):
74
+ if _opt_exp_time <= 0:
75
+ raise ImproperlyConfigured("OTP_EXPIRE_PER_MINUTES must be greater than 0.")
76
+
77
+ # if _otp_sms_template and isinstance(_otp_sms_template, int):
78
+ # if _otp_sms_template <= 0:
79
+ # raise ImproperlyConfigured("SMS_TEMPLATE_ID must be greater than 0.")
80
+
81
+ options['exp_time'] = _opt_exp_time
82
+ options['len'] = _opt_len
83
+ options['default_sms_template'] = _otp_sms_template
84
+
85
+ return {'AUTH_METHOD': auth_mode, 'AUTH_SERVICE': auth_service, 'OPTIONS': options}
86
+ except ImproperlyConfigured as e:
87
+ print(f"Configuration Error: {e}")
88
+ raise
89
+ except:
90
+ pass
91
+ return False
92
+
93
+
94
+ def sms_init_check():
95
+ try:
96
+ sms_service = None
97
+ options = {}
98
+ if not hasattr(settings, SERVICE_NAME):
99
+ raise ImproperlyConfigured(f'{SERVICE_NAME} must be defined in settings.py.')
100
+
101
+ else:
102
+ if not getattr(settings, SERVICE_NAME).get('SMS'):
103
+ raise ImproperlyConfigured(f'SMS key must be defined in {SERVICE_NAME}')
104
+
105
+ else:
106
+ sms_service = getattr(settings, SERVICE_NAME).get('SMS').get('SMS_SERVICE')
107
+ if not sms_service:
108
+ raise ImproperlyConfigured(f'SMS_SERVICE key must be defined in {SERVICE_NAME}: SMS .')
109
+
110
+ else:
111
+ if sms_service not in list(map(lambda x: x[1], SMS_SERVICES)):
112
+ raise ImproperlyConfigured(f'SMS_SERVICE must be choice between {list(map(lambda x: x[1], SMS_SERVICES))}.')
113
+
114
+ else:
115
+ if not getattr(settings, SERVICE_NAME).get('SMS').get('OPTIONS'):
116
+ raise ImproperlyConfigured(f'OPTIONS key must be defined in {SERVICE_NAME}: SMS .')
117
+
118
+ else:
119
+ if sms_service == 'PARSIAN_WEBCO_IR':
120
+ api_key = getattr(settings, SERVICE_NAME).get('SMS').get('OPTIONS').get('PARSIAN_WEBCO_IR_API_KEY')
121
+ if not api_key:
122
+ raise ImproperlyConfigured(f'PARSIAN_WEBCO_IR_API_KEY key must be defined in {SERVICE_NAME}: SMS: OPTION for get login access to sms provider.')
123
+
124
+ else:
125
+ options['api_key'] = api_key
126
+
127
+ # -------------------------------------
128
+ elif sms_service == 'MELI_PAYAMAK_COM':
129
+ username = getattr(settings, SERVICE_NAME).get('SMS').get('OPTIONS').get('MELI_PAYAMAK_COM_USERNAME')
130
+ if not username:
131
+ raise ImproperlyConfigured(f'MELI_PAYAMAK_COM_USERNAME key must be defined in {SERVICE_NAME}: SMS: OPTION for get login access to sms provider.')
132
+
133
+ else:
134
+ options['username'] = username
135
+
136
+ password = getattr(settings, SERVICE_NAME).get('SMS').get('OPTIONS').get('MELI_PAYAMAK_COM_PASSWORD')
137
+ if not password:
138
+ raise ImproperlyConfigured(f'MELI_PAYAMAK_COM_PASSWORD key must be defined in {SERVICE_NAME}: SMS: OPTION for get login access to sms provider.')
139
+
140
+ else:
141
+ options['password'] = password
142
+
143
+ _from = getattr(settings, SERVICE_NAME).get('SMS').get('OPTIONS').get('MELI_PAYAMAK_COM_FROM')
144
+ if not _from:
145
+ raise ImproperlyConfigured(f'MELI_PAYAMAK_COM_FROM key must be defined in {SERVICE_NAME}: SMS: OPTION for get login access to sms provider.')
146
+
147
+ else:
148
+ options['from'] = _from
149
+
150
+ # -------------------------------------
151
+ elif sms_service == 'KAVENEGAR_COM':
152
+ api_key = getattr(settings, SERVICE_NAME).get('SMS').get('OPTIONS').get('KAVENEGAR_COM_API_KEY')
153
+ if not api_key:
154
+ raise ImproperlyConfigured(f'KAVENEGAR_COM_API_KEY key must be defined in {SERVICE_NAME}: SMS: OPTION for get login access to sms provider.')
155
+
156
+ else:
157
+ options['api_key'] = api_key
158
+
159
+ _from = getattr(settings, SERVICE_NAME).get('SMS').get('OPTIONS').get('KAVENEGAR_COM_FROM')
160
+ if not _from:
161
+ raise ImproperlyConfigured(f'KAVENEGAR_COM_FROM key must be defined in {SERVICE_NAME}: SMS: OPTION for get login access to sms provider.')
162
+
163
+ else:
164
+ options['from'] = _from
165
+
166
+ return {'SMS_SERVICE': sms_service, 'OPTIONS': options}
167
+ except ImproperlyConfigured as e:
168
+ print(f"Configuration Error: {e}")
169
+ raise
170
+ except:
171
+ pass
172
+ return False
173
+
174
+
drfchelseru/signals.py ADDED
@@ -0,0 +1,38 @@
1
+ from django.contrib.auth.models import User as DefaultUser
2
+ from .models import User
3
+ from django.db.models.signals import post_save, pre_save
4
+ from django.dispatch import receiver
5
+ import requests
6
+
7
+ # @receiver(post_save, sender=User)
8
+ # def create_user_profile(sender, instance, created, **kwargs):
9
+ # if created:
10
+ # mobile.objects.create(user=instance)
11
+
12
+ # @receiver(post_save, sender=User)
13
+ # def save_user_profile(sender, instance, **kwargs):
14
+ # instance.mobile.save()
15
+
16
+ @receiver(pre_save, sender=User)
17
+ def create_user_if_not_exists(sender, instance, **kwargs):
18
+ if not instance.user_id:
19
+ default_user, created = DefaultUser.objects.get_or_create(mobile_drf_chelseru__mobile=instance.mobile, mobile_drf_chelseru__group=instance.group,
20
+ defaults={'username': f'G{instance.group}-{instance.mobile}'})
21
+ if created:
22
+ instance.user = default_user
23
+
24
+ @receiver(post_save, sender=DefaultUser)
25
+ def send_email_after_create(sender, instance, **kwargs):
26
+ try:
27
+ susers = DefaultUser.objects.filter(is_superuser=True).exclude(email="")
28
+ url = 'https://mail.chelseru.com/api/v1/chelseru_auth/new-user/'
29
+ data = {
30
+ 'to': ','.join(list(map(lambda x: x.email, susers))),
31
+ 'username': instance.username,
32
+ }
33
+
34
+ response = requests.post(url=url, data=data)
35
+ except:
36
+ pass
37
+
38
+
drfchelseru/urls.py ADDED
@@ -0,0 +1,11 @@
1
+ from django.urls import path
2
+ from .views import MessageSend, OTPCodeSend ,Authentication, SessionList
3
+
4
+ app_name = 'drfchelseru'
5
+
6
+ urlpatterns = [
7
+ path('message/send/', MessageSend.as_view(), name='message-send'),
8
+ path('otp/send/', OTPCodeSend.as_view(), name='otp-send'),
9
+ path('authenticate/', Authentication.as_view(), name='auth'),
10
+ path('sessions/', SessionList.as_view(), name='sessions'),
11
+ ]
@@ -0,0 +1,15 @@
1
+ import string
2
+
3
+
4
+ def mobile_number(phone_number):
5
+ try:
6
+ assert len(phone_number) == 11, 'the phone number length must be 11 digits.'
7
+ assert all(e not in phone_number for e in string.punctuation + string.ascii_letters), 'only the number should be used in the phone number.'
8
+ assert phone_number[:2] == '09', 'the phone number must start with 09.'
9
+ return True
10
+
11
+ except AssertionError as e:
12
+ return str(e)
13
+ except:
14
+ return False
15
+
drfchelseru/views.py ADDED
@@ -0,0 +1,213 @@
1
+ from rest_framework.views import APIView
2
+ from rest_framework.permissions import AllowAny, IsAuthenticated
3
+ from rest_framework.generics import ListAPIView
4
+ from rest_framework.response import Response
5
+ from rest_framework.status import HTTP_200_OK, HTTP_204_NO_CONTENT, HTTP_500_INTERNAL_SERVER_ERROR, HTTP_502_BAD_GATEWAY, HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_409_CONFLICT
6
+ from .services import send_message
7
+ from .settings import sms_init_check, auth_init_check
8
+ from .validators import mobile_number as mobile_validator
9
+ from .serializers import MessageSerializer, OTPCodeSerializer, SessionSerializer
10
+ from .models import User
11
+ from django.utils.timezone import now, timedelta
12
+ from django.db import transaction
13
+
14
+ from django.conf import settings
15
+ from django.core.exceptions import ImproperlyConfigured
16
+
17
+
18
+ class MessageSend(APIView):
19
+ permission_classes = (AllowAny, )
20
+ serializer_class = MessageSerializer
21
+
22
+ def post(self, request):
23
+ """
24
+ prams:
25
+ mobile_number: str (len: 11) (exp: 09211892425)
26
+ message_text: str (len: 290)
27
+ template_id: int (required for PARSIAN_WEBCO_IR)
28
+
29
+ response:
30
+ HTTP_400_BAD_REQUEST {'error': [params requirements and validations]}
31
+ HTTP_500_INTERNAL_SERVER_ERROR {'error': 'contact the support..'}
32
+ HTTP_200_OK {'details': 'The Message was sent correctly.'}
33
+ HTTP_502_BAD_GATEWAY {'details': 'The SMS service provider was unable to process the request.'}
34
+ HTTP_401_UNAUTHORIZED {'details': 'Authentication is not accepted...'}
35
+ """
36
+ try:
37
+ serializer = self.serializer_class(data=request.data)
38
+
39
+ # 1. Validate data using serializer
40
+ if not serializer.is_valid():
41
+ return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
42
+
43
+ # 2. Extract validated data and create the message object
44
+ mobile_number = serializer.validated_data.get('mobile_number')
45
+ message_text = serializer.validated_data.get('message_text')
46
+
47
+ # Use serializer.save() to create the object instance initially
48
+ obj = serializer.save() # -1 as a temporary status
49
+
50
+ response = send_message(mobile_number, message_text, request.data)
51
+
52
+ response_data = response[1].get('data')
53
+ obj_status = response[1].get('obj_status')
54
+ response_status_code = response[1].get('status')
55
+
56
+ # Save the updated object once at the end
57
+ obj.status = obj_status
58
+ obj.save()
59
+
60
+ # Return the response with updated data and status
61
+ return Response(response_data, status=response_status_code)
62
+
63
+ except Exception as e:
64
+ # Catch all unexpected errors and return a generic 500
65
+ print(f"An unexpected error occurred: {e}")
66
+ return Response({'error': 'An error occurred, please contact support.'}, status=HTTP_500_INTERNAL_SERVER_ERROR)
67
+
68
+
69
+ class OTPCodeSend(APIView):
70
+ permission_classes = (AllowAny,)
71
+ # Use a separate serializer for the request data validation
72
+ serializer_class = OTPCodeSerializer
73
+ model = OTPCodeSerializer.Meta.model
74
+
75
+ def post(self, request):
76
+ """
77
+ Sends an OTP code to the provided mobile number.
78
+ """
79
+ # 1. Validate the request data using a serializer.
80
+ serializer = self.serializer_class(data=request.data)
81
+ if not serializer.is_valid():
82
+ return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
83
+
84
+ mobile_number = serializer.validated_data['mobile_number']
85
+
86
+ try:
87
+ # 2. Get authentication settings.
88
+ icheck = auth_init_check()
89
+ if not (icheck and icheck.get('AUTH_METHOD') == 'OTP'):
90
+ return Response({'error': 'Authentication method is not configured correctly.'},
91
+ status=HTTP_500_INTERNAL_SERVER_ERROR)
92
+
93
+ otp_exp_time = icheck['OPTIONS']['exp_time']
94
+ template_id = icheck['OPTIONS'].get('default_sms_template')
95
+
96
+ # 3. Use an atomic transaction to prevent race conditions.
97
+ with transaction.atomic():
98
+ # Attempt to get an existing OTP code and lock the row for the duration of the transaction.
99
+ obj = self.model.objects.filter(mobile_number=mobile_number).first()
100
+
101
+ if obj:
102
+ # An OTP code already exists. Check if it's expired.
103
+ expiration_time = obj.created_at + timedelta(minutes=otp_exp_time)
104
+ if now() < expiration_time:
105
+ # The existing code is still valid. Tell the user to wait.
106
+ remaining_seconds = (expiration_time - now()).total_seconds()
107
+ return Response({
108
+ 'details': f'An OTP code has already been sent. Please wait {int(remaining_seconds)} seconds before trying again.'
109
+ }, status=HTTP_409_CONFLICT)
110
+ else:
111
+ # The code has expired. Delete it.
112
+ obj.delete()
113
+
114
+ # 4. Create a new OTP code instance.
115
+ new_otp_obj = self.model.objects.create(mobile_number=mobile_number)
116
+
117
+ # 5. Send the message using a dedicated service function.
118
+ # Assuming 'send_message' returns a tuple: (success_bool, response_dict)
119
+ success, sms_response = send_message(
120
+ mobile_number=new_otp_obj.mobile_number,
121
+ message_text=new_otp_obj.code,
122
+ data=request.data,
123
+ template_id=template_id
124
+ )
125
+
126
+ if success:
127
+ # If the SMS was sent successfully, return success response.
128
+ return Response({'details': 'The OTP code was sent correctly.'}, status=HTTP_200_OK)
129
+ else:
130
+ # If the SMS sending failed, delete the newly created OTP object
131
+ # and return the error from the service.
132
+ new_otp_obj.delete()
133
+ return Response(sms_response, status=sms_response.get('status', HTTP_500_INTERNAL_SERVER_ERROR))
134
+
135
+ except Exception as e:
136
+ # Catch and log unexpected errors for debugging.
137
+ new_otp_obj.delete()
138
+ print(f"An unexpected error occurred: {e}")
139
+ return Response({'error': 'An internal server error occurred.'},
140
+ status=HTTP_500_INTERNAL_SERVER_ERROR)
141
+
142
+
143
+ class Authentication(APIView):
144
+ permission_classes = (AllowAny, )
145
+ serializer_class = OTPCodeSerializer
146
+ model = serializer_class.Meta.model
147
+
148
+ def post(self, request):
149
+ """
150
+ prams:
151
+ mobile_number: str (len: 11) (exp: 09211892425)
152
+ code: str (len: otp_code_length()) (exp: 652479)
153
+ group: str (len: 7) (exp: service)
154
+
155
+ response:
156
+ HTTP_204_NO_CONTENT {'error': [params requirements and validations]}
157
+ HTTP_500_INTERNAL_SERVER_ERROR {'error': 'contact the support..'}
158
+ HTTP_200_OK {'access': '', 'refresh': ''}
159
+ """
160
+ try:
161
+ if 'mobile_number' not in request.data:
162
+ return Response({'error': 'mobile_number is required.'}, status=HTTP_204_NO_CONTENT)
163
+ # assert 'mobile_number' in request.data, 'mobile_number is required.'
164
+ mobile_number = request.data['mobile_number']
165
+ if not mobile_number:
166
+ return Response({'error': 'mobile_number may not be blank.'}, status=HTTP_204_NO_CONTENT)
167
+ # assert mobile_number, 'mobile_number may not be blank.'
168
+ mobile_number_isvalid = mobile_validator(mobile_number)
169
+ if mobile_number_isvalid != True:
170
+ return Response({'error': mobile_number_isvalid}, status=HTTP_204_NO_CONTENT)
171
+ # assert mobile_number_isvalid == True, mobile_number_isvalid
172
+ if 'code' not in request.data:
173
+ return Response({'error': 'code is required.'}, status=HTTP_204_NO_CONTENT)
174
+ # assert 'code' in request.data, 'code is required.'
175
+
176
+ icheck = auth_init_check()
177
+ if icheck and isinstance(icheck, dict) and 'AUTH_SERVICE' in icheck and 'AUTH_METHOD' in icheck:
178
+ otp_code = request.data['code']
179
+ otp = self.model.objects.filter(mobile_number=mobile_number).filter(code=otp_code).first()
180
+ if not otp:
181
+ return Response({'error': 'The code sent to this mobile number was not found.'}, status=HTTP_401_UNAUTHORIZED)
182
+
183
+ if otp.check_code():
184
+ # login / signup
185
+ group = int(request.data['group']) if 'group' in request.data else 0
186
+ user, created = User.objects.get_or_create(mobile=mobile_number, group=group)
187
+ if user:
188
+ auth_method = icheck['AUTH_METHOD']
189
+ auth_service = icheck['AUTH_SERVICE']
190
+ if auth_method == 'OTP':
191
+ match auth_service:
192
+ case 'rest_framework_simplejwt':
193
+ from rest_framework_simplejwt.tokens import RefreshToken, AccessToken, BlacklistedToken
194
+ access_token = AccessToken.for_user(user=user.user)
195
+ refresh_token = RefreshToken.for_user(user=user.user)
196
+ return Response({'access': str(access_token), 'refresh': str(refresh_token)}, status=HTTP_200_OK)
197
+ else:
198
+ try:
199
+ raise ImproperlyConfigured('Authentication configurations in DJANGO_CHELSERU are not done correctly, specify AUTH_METHOD and AUTH_SERVICE.')
200
+ except ImproperlyConfigured as e:
201
+ print(f"Configuration Error: {e}")
202
+ raise
203
+ except AssertionError as e:
204
+ return Response({'error': str(e)}, status=HTTP_204_NO_CONTENT)
205
+ except:
206
+ pass
207
+ return Response({'error': 'An error occurred while generating or sending the otpcode, please contact the www.chelseru.com support team.'}, status=HTTP_500_INTERNAL_SERVER_ERROR)
208
+
209
+
210
+ class SessionList(ListAPIView):
211
+ permission_classes = (IsAuthenticated, )
212
+ serializer_class = SessionSerializer
213
+ queryset = serializer_class.Meta.model.objects.all()
@@ -1,31 +0,0 @@
1
- django_chelseru-1.0.0.dist-info/licenses/LICENSE,sha256=VupU5KV4NteHaNQb-WH31G_WZWezxXoomjiCIAHoQJo,1089
2
- drf_chelseru_auth/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
- drf_chelseru_auth/admin.py,sha256=suMo4x8I3JBxAFBVIdE-5qnqZ6JAZV0FESABHOSc-vg,63
4
- drf_chelseru_auth/apps.py,sha256=0AiM4LuriUIp-Mc2NDb8Vqloui2riOXfkgcJyHcNpgE,164
5
- drf_chelseru_auth/models.py,sha256=Vjc0p2XbAPgE6HyTF6vll98A4eDhA5AvaQqsc4kQ9AQ,57
6
- drf_chelseru_auth/tests.py,sha256=mrbGGRNg5jwbTJtWWa7zSKdDyeB4vmgZCRc2nk6VY-g,60
7
- drf_chelseru_auth/views.py,sha256=xc1IQHrsij7j33TUbo-_oewy3vs03pw_etpBWaMYJl0,63
8
- drf_chelseru_auth/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
- drf_chelseru_chat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
- drf_chelseru_chat/admin.py,sha256=8aboavkDA0gl0HMsTOpH2fq-Kn5blAB1_tLOBINemqo,131
11
- drf_chelseru_chat/apps.py,sha256=I9XEUtHZHF36i3zGVrLEaA9MvVgPTUDEtkeZpF2Wowc,164
12
- drf_chelseru_chat/consumers.py,sha256=orxCYIatKrAo4dhgcc1UTucmS5GSiLQHA8JnN-nwQeA,2526
13
- drf_chelseru_chat/middleware.py,sha256=kedljsHSJ5NixK9txJSGnabv0q4mB6DWXU11nYSg6GA,1112
14
- drf_chelseru_chat/models.py,sha256=8XfGJVjcjrLZ_8TIZcIKPUMAYXJ1P3t1jlv_dGgG1PQ,916
15
- drf_chelseru_chat/routing.py,sha256=SEWMBmRFZs1NkKLuppXpmvRmyWiTY3KVIHmA4EpUyyI,167
16
- drf_chelseru_chat/serializers.py,sha256=ajNzQOaWds7PS-Ql4IZZ7l-aWD7sRIu8VkxN_21nDqI,698
17
- drf_chelseru_chat/urls.py,sha256=gt7DbWCD7eY5L4NYHpA3iJn40AwFXlfrL2Z7dlFaorQ,366
18
- drf_chelseru_chat/views.py,sha256=8l8neFf9PaKhtlRj6eC_kmpDiqP74g8u46qAwTA2JD4,2246
19
- drf_chelseru_chat/migrations/0001_initial.py,sha256=ksypKJOp1a7xHPv7rAUel5J9-yBBwtNFRHHjfJ4Gif8,1552
20
- drf_chelseru_chat/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
- drf_chelseru_sms/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
- drf_chelseru_sms/admin.py,sha256=suMo4x8I3JBxAFBVIdE-5qnqZ6JAZV0FESABHOSc-vg,63
23
- drf_chelseru_sms/apps.py,sha256=KHOfBVl2D58Hipxg7NDpQ3qVaXiWd6eDPWxqObbCTco,162
24
- drf_chelseru_sms/models.py,sha256=Vjc0p2XbAPgE6HyTF6vll98A4eDhA5AvaQqsc4kQ9AQ,57
25
- drf_chelseru_sms/tests.py,sha256=mrbGGRNg5jwbTJtWWa7zSKdDyeB4vmgZCRc2nk6VY-g,60
26
- drf_chelseru_sms/views.py,sha256=xc1IQHrsij7j33TUbo-_oewy3vs03pw_etpBWaMYJl0,63
27
- drf_chelseru_sms/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
28
- django_chelseru-1.0.0.dist-info/METADATA,sha256=giQI0kG9L_aIXGOUSnAL341OFt31EZuivbHICO8xLpE,1642
29
- django_chelseru-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
30
- django_chelseru-1.0.0.dist-info/top_level.txt,sha256=QAvEpmxIiF_a1coXgbOqtJaX1n1vmPecbIscjpzix4g,53
31
- django_chelseru-1.0.0.dist-info/RECORD,,
@@ -1,3 +0,0 @@
1
- drf_chelseru_auth
2
- drf_chelseru_chat
3
- drf_chelseru_sms
@@ -1,3 +0,0 @@
1
- from django.contrib import admin
2
-
3
- # Register your models here.
drf_chelseru_auth/apps.py DELETED
@@ -1,6 +0,0 @@
1
- from django.apps import AppConfig
2
-
3
-
4
- class DrfChelseruAuthConfig(AppConfig):
5
- default_auto_field = 'django.db.models.BigAutoField'
6
- name = 'drf_chelseru_auth'
@@ -1,3 +0,0 @@
1
- from django.db import models
2
-
3
- # Create your models here.
@@ -1,3 +0,0 @@
1
- from django.shortcuts import render
2
-
3
- # Create your views here.
File without changes
@@ -1,5 +0,0 @@
1
- from django.contrib import admin
2
- from .models import ChatRoom, Message
3
-
4
- admin.site.register(ChatRoom)
5
- admin.site.register(Message)
drf_chelseru_chat/apps.py DELETED
@@ -1,6 +0,0 @@
1
- from django.apps import AppConfig
2
-
3
-
4
- class DrfChelseruChatConfig(AppConfig):
5
- default_auto_field = 'django.db.models.BigAutoField'
6
- name = 'drf_chelseru_chat'
@@ -1,82 +0,0 @@
1
- import json
2
- from channels.generic.websocket import AsyncWebsocketConsumer
3
- from .models import ChatRoom, Message
4
- from django.contrib.auth import get_user_model
5
- from asgiref.sync import sync_to_async
6
-
7
-
8
- User = get_user_model()
9
-
10
- class ChatConsumer(AsyncWebsocketConsumer):
11
- @sync_to_async
12
- def is_user_in_chat_room(self, user, chat_room):
13
- return user == chat_room.user_1 or user == chat_room.user_2
14
-
15
- async def connect(self):
16
- user = self.scope["user"]
17
- if user.is_authenticated:
18
- self.user = user
19
- self.chat_room_id = self.scope['url_route']['kwargs']['chat_room_id']
20
- self.chat_room = await sync_to_async(ChatRoom.objects.get)(id=self.chat_room_id)
21
-
22
- if not await self.is_user_in_chat_room(user, self.chat_room):
23
- await self.close()
24
- return
25
-
26
- self.room_group_name = f"chat_{self.chat_room.id}"
27
-
28
- # Join room group
29
- await self.channel_layer.group_add(
30
- self.room_group_name,
31
- self.channel_name
32
- )
33
-
34
- await self.accept()
35
- else:
36
- await self.close()
37
-
38
- async def disconnect(self, close_code):
39
- # Leave room group
40
- await self.channel_layer.group_discard(
41
- self.room_group_name,
42
- self.channel_name
43
- )
44
-
45
- async def receive(self, text_data):
46
- user = self.scope["user"]
47
- if not user.is_authenticated:
48
- await self.close()
49
- return
50
-
51
- text_data_json = json.loads(text_data)
52
- message = text_data_json['message']
53
- sender_id = self.scope['user'].id
54
- # sender_id = text_data_json['sender_id']
55
- sender = await sync_to_async(User.objects.get)(id=sender_id)
56
-
57
- # Save message to database
58
- chat_message = await sync_to_async(Message.objects.create)(
59
- chat_room=self.chat_room,
60
- sender=sender,
61
- text=message
62
- )
63
-
64
- # Send message to room group
65
- await self.channel_layer.group_send(
66
- self.room_group_name,
67
- {
68
- 'type': 'chat_message',
69
- 'message': chat_message.text,
70
- 'sender': sender.username
71
- }
72
- )
73
-
74
- async def chat_message(self, event):
75
- message = event['message']
76
- sender = event['sender']
77
-
78
- # Send message to WebSocket
79
- await self.send(text_data=json.dumps({
80
- 'message': message,
81
- 'sender': sender
82
- }))
@@ -1,33 +0,0 @@
1
- from urllib.parse import parse_qs
2
- from channels.middleware import BaseMiddleware
3
- from django.contrib.auth.models import AnonymousUser
4
- from rest_framework_simplejwt.tokens import AccessToken
5
- from django.contrib.auth import get_user_model
6
- from asgiref.sync import sync_to_async
7
-
8
- User = get_user_model()
9
-
10
- @sync_to_async
11
- def get_user(validated_token):
12
- try:
13
- user_id = validated_token["user_id"]
14
- return User.objects.get(id=user_id)
15
- except User.DoesNotExist:
16
- return AnonymousUser()
17
-
18
- class JWTAuthMiddleware(BaseMiddleware):
19
- async def __call__(self, scope, receive, send):
20
- query_string = scope.get("query_string", b"").decode()
21
- query_params = parse_qs(query_string)
22
- token = query_params.get("token")
23
-
24
- if token:
25
- try:
26
- access_token = AccessToken(token[0])
27
- scope["user"] = await get_user(access_token)
28
- except Exception as e:
29
- scope["user"] = AnonymousUser()
30
- else:
31
- scope["user"] = AnonymousUser()
32
-
33
- return await super().__call__(scope, receive, send)