django-chelseru 1.0.0__py3-none-any.whl → 1.0.2__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.
- django_chelseru-1.0.2.dist-info/METADATA +95 -0
- django_chelseru-1.0.2.dist-info/RECORD +22 -0
- django_chelseru-1.0.2.dist-info/top_level.txt +1 -0
- drfchelseru/admin.py +24 -0
- drfchelseru/apps.py +9 -0
- drfchelseru/middlewares.py +44 -0
- drfchelseru/migrations/0001_initial.py +33 -0
- drfchelseru/migrations/0002_otpcode_session_user.py +92 -0
- drfchelseru/migrations/0003_rename_mobile_otpcode_mobile_number.py +18 -0
- drfchelseru/models.py +77 -0
- drfchelseru/serializers.py +34 -0
- drfchelseru/services.py +239 -0
- drfchelseru/settings.py +187 -0
- drfchelseru/signals.py +38 -0
- drfchelseru/urls.py +11 -0
- drfchelseru/validators.py +15 -0
- drfchelseru/views.py +213 -0
- django_chelseru-1.0.0.dist-info/METADATA +0 -56
- django_chelseru-1.0.0.dist-info/RECORD +0 -31
- django_chelseru-1.0.0.dist-info/top_level.txt +0 -3
- drf_chelseru_auth/admin.py +0 -3
- drf_chelseru_auth/apps.py +0 -6
- drf_chelseru_auth/models.py +0 -3
- drf_chelseru_auth/views.py +0 -3
- drf_chelseru_chat/__init__.py +0 -0
- drf_chelseru_chat/admin.py +0 -5
- drf_chelseru_chat/apps.py +0 -6
- drf_chelseru_chat/consumers.py +0 -82
- drf_chelseru_chat/middleware.py +0 -33
- drf_chelseru_chat/migrations/0001_initial.py +0 -36
- drf_chelseru_chat/migrations/__init__.py +0 -0
- drf_chelseru_chat/models.py +0 -23
- drf_chelseru_chat/routing.py +0 -6
- drf_chelseru_chat/serializers.py +0 -26
- drf_chelseru_chat/urls.py +0 -12
- drf_chelseru_chat/views.py +0 -59
- drf_chelseru_sms/__init__.py +0 -0
- drf_chelseru_sms/admin.py +0 -3
- drf_chelseru_sms/apps.py +0 -6
- drf_chelseru_sms/migrations/__init__.py +0 -0
- drf_chelseru_sms/models.py +0 -3
- drf_chelseru_sms/tests.py +0 -3
- drf_chelseru_sms/views.py +0 -3
- {django_chelseru-1.0.0.dist-info → django_chelseru-1.0.2.dist-info}/WHEEL +0 -0
- {django_chelseru-1.0.0.dist-info → django_chelseru-1.0.2.dist-info}/licenses/LICENSE +0 -0
- {drf_chelseru_auth → drfchelseru}/__init__.py +0 -0
- {drf_chelseru_auth → drfchelseru}/migrations/__init__.py +0 -0
- {drf_chelseru_auth → drfchelseru}/tests.py +0 -0
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,56 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: django-chelseru
|
|
3
|
-
Version: 1.0.0
|
|
4
|
-
Summary: Authentication system, online and real-time chat, SMS system for Iranian SMS services.
|
|
5
|
-
Home-page: https://pip-django.chelseru.com
|
|
6
|
-
Author: Sobhan Bahman | Rashnu
|
|
7
|
-
Author-email: bahmanrashnu@gmail.com
|
|
8
|
-
Project-URL: Documentation, https://github.com/Chelseru/django-chelseru-lour/
|
|
9
|
-
Project-URL: Telegram Group, https://t.me/bahmanpy
|
|
10
|
-
Project-URL: Telegram Channel, https://t.me/ChelseruCom
|
|
11
|
-
Keywords: djangochelseruchat djangochat drfchat online-chat online real-time chat iran chelseru lor lur bahman rashnu lour sms djangoiransms iransms djangosms djangokavenegar djangomelipayamak sobhan چت سبحان بهمن رشنو چلسرو جنگو پایتون لر لور آنلاین ریل تایم
|
|
12
|
-
Classifier: Programming Language :: Python :: 3
|
|
13
|
-
Classifier: Framework :: Django
|
|
14
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
-
Classifier: Operating System :: OS Independent
|
|
16
|
-
Requires-Python: >=3.11
|
|
17
|
-
Description-Content-Type: text/markdown
|
|
18
|
-
License-File: LICENSE
|
|
19
|
-
Requires-Dist: Django>=5.1.6
|
|
20
|
-
Requires-Dist: djangorestframework==3.15.2
|
|
21
|
-
Requires-Dist: djangorestframework_simplejwt==5.5.0
|
|
22
|
-
Requires-Dist: channels==4.2.2
|
|
23
|
-
Requires-Dist: channels_redis==4.2.1
|
|
24
|
-
Requires-Dist: daphne==4.1.2
|
|
25
|
-
Dynamic: author
|
|
26
|
-
Dynamic: author-email
|
|
27
|
-
Dynamic: classifier
|
|
28
|
-
Dynamic: description
|
|
29
|
-
Dynamic: description-content-type
|
|
30
|
-
Dynamic: home-page
|
|
31
|
-
Dynamic: keywords
|
|
32
|
-
Dynamic: license-file
|
|
33
|
-
Dynamic: project-url
|
|
34
|
-
Dynamic: requires-dist
|
|
35
|
-
Dynamic: requires-python
|
|
36
|
-
Dynamic: summary
|
|
37
|
-
|
|
38
|
-
# Django Chelseru
|
|
39
|
-
|
|
40
|
-
---
|
|
41
|
-
|
|
42
|
-
## Installation
|
|
43
|
-
|
|
44
|
-
```bash
|
|
45
|
-
pip install django-chelseru
|
|
46
|
-
```
|
|
47
|
-
|
|
48
|
-
---
|
|
49
|
-
-
|
|
50
|
-
|
|
51
|
-
## License
|
|
52
|
-
|
|
53
|
-
MIT License
|
|
54
|
-
|
|
55
|
-
Sobhan Bahman | Rashnu
|
|
56
|
-
|
|
@@ -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,,
|
drf_chelseru_auth/admin.py
DELETED
drf_chelseru_auth/apps.py
DELETED
drf_chelseru_auth/models.py
DELETED
drf_chelseru_auth/views.py
DELETED
drf_chelseru_chat/__init__.py
DELETED
|
File without changes
|
drf_chelseru_chat/admin.py
DELETED
drf_chelseru_chat/apps.py
DELETED
drf_chelseru_chat/consumers.py
DELETED
|
@@ -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
|
-
}))
|
drf_chelseru_chat/middleware.py
DELETED
|
@@ -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)
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
# Generated by Django 5.1.6 on 2025-08-10 16:17
|
|
2
|
-
|
|
3
|
-
import django.db.models.deletion
|
|
4
|
-
from django.conf import settings
|
|
5
|
-
from django.db import migrations, models
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class Migration(migrations.Migration):
|
|
9
|
-
|
|
10
|
-
initial = True
|
|
11
|
-
|
|
12
|
-
dependencies = [
|
|
13
|
-
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
14
|
-
]
|
|
15
|
-
|
|
16
|
-
operations = [
|
|
17
|
-
migrations.CreateModel(
|
|
18
|
-
name='ChatRoom',
|
|
19
|
-
fields=[
|
|
20
|
-
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
21
|
-
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
22
|
-
('user_1', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user1_chats', to=settings.AUTH_USER_MODEL)),
|
|
23
|
-
('user_2', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user2_chats', to=settings.AUTH_USER_MODEL)),
|
|
24
|
-
],
|
|
25
|
-
),
|
|
26
|
-
migrations.CreateModel(
|
|
27
|
-
name='Message',
|
|
28
|
-
fields=[
|
|
29
|
-
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
|
30
|
-
('text', models.TextField()),
|
|
31
|
-
('timestamp', models.DateTimeField(auto_now_add=True)),
|
|
32
|
-
('chat_room', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='drf_chelseru_chat.chatroom')),
|
|
33
|
-
('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
|
34
|
-
],
|
|
35
|
-
),
|
|
36
|
-
]
|
|
File without changes
|
drf_chelseru_chat/models.py
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
from django.contrib.auth import get_user_model
|
|
2
|
-
from django.db import models
|
|
3
|
-
|
|
4
|
-
User = get_user_model()
|
|
5
|
-
|
|
6
|
-
class ChatRoom(models.Model):
|
|
7
|
-
user_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user1_chats')
|
|
8
|
-
user_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user2_chats')
|
|
9
|
-
|
|
10
|
-
created_at = models.DateTimeField(auto_now_add=True)
|
|
11
|
-
|
|
12
|
-
def __str__(self):
|
|
13
|
-
return f"ID: {self.id} | Chat between {self.user_1.username} and {self.user_2.username}"
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
class Message(models.Model):
|
|
17
|
-
chat_room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name='messages')
|
|
18
|
-
sender = models.ForeignKey(User, on_delete=models.CASCADE)
|
|
19
|
-
text = models.TextField()
|
|
20
|
-
timestamp = models.DateTimeField(auto_now_add=True)
|
|
21
|
-
|
|
22
|
-
def __str__(self):
|
|
23
|
-
return f"iD: {self.id} | Message from {self.sender.username} at {self.timestamp} | Chatroom ID: {self.chat_room.id}"
|
drf_chelseru_chat/routing.py
DELETED
drf_chelseru_chat/serializers.py
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
from rest_framework import serializers
|
|
2
|
-
from .models import ChatRoom, Message
|
|
3
|
-
from django.contrib.auth import get_user_model
|
|
4
|
-
|
|
5
|
-
User = get_user_model()
|
|
6
|
-
|
|
7
|
-
class UserSerializer(serializers.ModelSerializer):
|
|
8
|
-
class Meta:
|
|
9
|
-
model = User
|
|
10
|
-
fields = ['id', 'username', 'email']
|
|
11
|
-
|
|
12
|
-
class ChatRoomSerializer(serializers.ModelSerializer):
|
|
13
|
-
user_1, user_2 = UserSerializer(read_only=True), UserSerializer(read_only=True)
|
|
14
|
-
class Meta:
|
|
15
|
-
model = ChatRoom
|
|
16
|
-
fields = '__all__'
|
|
17
|
-
depth = 1
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
class MessageSerializer(serializers.ModelSerializer):
|
|
21
|
-
sender = UserSerializer(read_only=True)
|
|
22
|
-
|
|
23
|
-
class Meta:
|
|
24
|
-
model = Message
|
|
25
|
-
fields = '__all__'
|
|
26
|
-
depth = 1
|
drf_chelseru_chat/urls.py
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
# urls.py
|
|
2
|
-
from django.urls import path, include
|
|
3
|
-
from rest_framework.routers import DefaultRouter
|
|
4
|
-
from .views import ChatRoomViewSet, MessageViewSet
|
|
5
|
-
|
|
6
|
-
router = DefaultRouter()
|
|
7
|
-
router.register(r'chatrooms', ChatRoomViewSet, basename='chatroom')
|
|
8
|
-
router.register(r'messages', MessageViewSet, basename='messages')
|
|
9
|
-
|
|
10
|
-
urlpatterns = [
|
|
11
|
-
path('api/', include(router.urls)),
|
|
12
|
-
]
|
drf_chelseru_chat/views.py
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
from rest_framework import viewsets, permissions
|
|
2
|
-
from .models import ChatRoom, Message
|
|
3
|
-
from .serializers import ChatRoomSerializer, MessageSerializer
|
|
4
|
-
from django.db.models import Q
|
|
5
|
-
from rest_framework.decorators import action
|
|
6
|
-
from rest_framework.response import Response
|
|
7
|
-
from rest_framework import status as drf_status
|
|
8
|
-
from rest_framework.exceptions import PermissionDenied, NotFound, ValidationError
|
|
9
|
-
# from django_filters.rest_framework import DjangoFilterBackend
|
|
10
|
-
from django.contrib.auth.models import User
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
# views.py
|
|
14
|
-
class ChatRoomViewSet(viewsets.ModelViewSet):
|
|
15
|
-
serializer_class = ChatRoomSerializer
|
|
16
|
-
permission_classes = [permissions.IsAuthenticated]
|
|
17
|
-
model = serializer_class.Meta.model
|
|
18
|
-
|
|
19
|
-
def get_queryset(self):
|
|
20
|
-
return self.model.objects.filter(user_1=self.request.user) | self.model.objects.filter(user_2=self.request.user)
|
|
21
|
-
|
|
22
|
-
def perform_create(self, serializer):
|
|
23
|
-
user = self.request.user
|
|
24
|
-
|
|
25
|
-
user_id = self.request.data.get('user', None)
|
|
26
|
-
user_2 = User.objects.filter(id=user_id).first()
|
|
27
|
-
if not user_2:
|
|
28
|
-
raise NotFound("کاربر مورد نظر با آی دی فرستاده شده یافت نشد.")
|
|
29
|
-
|
|
30
|
-
chat_room = serializer.save(user_1=user, user_2=user_2)
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
class MessageViewSet(viewsets.ModelViewSet):
|
|
34
|
-
serializer_class = MessageSerializer
|
|
35
|
-
permission_classes = [permissions.IsAuthenticated]
|
|
36
|
-
|
|
37
|
-
def get_queryset(self):
|
|
38
|
-
user = self.request.user
|
|
39
|
-
|
|
40
|
-
queryset = self.serializer_class.Meta.model.objects.filter(user=profile.organization)
|
|
41
|
-
chat_room_id = self.request.query_params.get('chat_room')
|
|
42
|
-
if chat_room_id:
|
|
43
|
-
queryset = queryset.filter(chat_room_id=chat_room_id)
|
|
44
|
-
return queryset
|
|
45
|
-
|
|
46
|
-
def perform_create(self, serializer):
|
|
47
|
-
chat_room_id = self.request.data.get('chat_room')
|
|
48
|
-
if not chat_room_id:
|
|
49
|
-
raise ValidationError("فیلد chat_room اجباریه.")
|
|
50
|
-
|
|
51
|
-
try:
|
|
52
|
-
chat = ChatRoom.objects.get(id=chat_room_id)
|
|
53
|
-
except ChatRoom.DoesNotExist:
|
|
54
|
-
raise NotFound("چتروم پیدا نشد.")
|
|
55
|
-
|
|
56
|
-
message = serializer.save(sender=self.request.user, chat_room=chat)
|
|
57
|
-
chat = message.chat_room
|
|
58
|
-
chat.save()
|
|
59
|
-
|
drf_chelseru_sms/__init__.py
DELETED
|
File without changes
|
drf_chelseru_sms/admin.py
DELETED
drf_chelseru_sms/apps.py
DELETED
|
File without changes
|
drf_chelseru_sms/models.py
DELETED
drf_chelseru_sms/tests.py
DELETED