-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathutility.py
301 lines (240 loc) · 7.5 KB
/
utility.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
import hashlib
from typing import Any
import uuid
import jwt
import qrcode
from django.core.files import File
from io import BytesIO
from django.core.mail import send_mail
from anwesha.settings import EMAIL_HOST_USER, COOKIE_ENCRYPTION_SECRET
import datetime
from django.template.loader import render_to_string
from django.utils.html import strip_tags
import csv
from django.http import HttpResponse, JsonResponse
import bcrypt
import hmac
import base64
def verification_mail(email, user):
"""
Sends a verification email to the given email address.
Args:
email (str): Email address to send the email to.
user (str): User's name.
Returns:
int: Number of successfully sent emails.
"""
payload = {
'email': email,
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
"iat": datetime.datetime.utcnow()
}
token = jwt.encode(
payload, COOKIE_ENCRYPTION_SECRET, algorithm='HS256')
link = "https://backend.anwesha.live/campasambassador/verifyemail/" + token
localhost_link = "http://127.0.0.1:8000/campasambassador/verifyemail/" + token
subject = "No reply"
body = f'''
Hello {user},\n\n
Please click on the link below to verify your email address for anwesha login:
\n{link}
\n\nThanks,
\nTeam Anwesha
'''
recipient_list = [email]
res = send_mail(subject, body, EMAIL_HOST_USER, recipient_list)
return res
def hashpassword(password):
"""
Hashes the given password using SHA256 algorithm.
Args:
password (str): Password to hash.
Returns:
str: Hashed password.
"""
return hashlib.sha256(password.encode()).hexdigest()
def createId(prefix, length):
"""
Utility function to create a random ID of given length.
Args:
prefix (str): Prefix of the ID (e.g., "TEAM", "ANW").
length (int): Length of the ID excluding the prefix.
Returns:
str: Randomly generated ID.
"""
id = str(uuid.uuid4()).replace("-", "")
return prefix + id[:length]
def checkPhoneNumber(phone_number: str):
"""
Checks if the given phone number is valid or not.
Args:
phone_number (str): Phone number to check.
Returns:
None
"""
pass
def isemail(email_id: str):
"""
Checks if the given email ID is valid or not.
Args:
email_id (str): Email ID to check.
Returns:
bool: True if the email ID is valid, False otherwise.
"""
if "@" in email_id:
return True
return False
def get_anwesha_id(request):
"""
Retrieves the anwesha_id of the user from the cookie.
Args:
request: Django request object.
Returns:
str: Anwesha ID of the user.
"""
token = request.COOKIES.get("jwt")
if not token:
return None
try:
payload = jwt.decode(token, "ufdhufhufgefef", algorithms="HS256")
id = payload["id"]
return id
except jwt.ExpiredSignatureError:
return None
def generate_qr(anwesha_id):
"""
Generates a QR code for the given Anwesha ID.
Args:
anwesha_id (str): Anwesha ID.
Returns:
File: QR code image file.
"""
img = qrcode.make(anwesha_id)
blob = BytesIO()
img.save(blob, "PNG")
qr = File(blob, name=anwesha_id + "-qr.png")
return qr
def generate_jwt_token(anwesha_id):
"""
Generates a JWT token for the given Anwesha ID.
Args:
anwesha_id (str): Anwesha ID.
Returns:
str: JWT token.
"""
return anwesha_id
def export_as_csv(self, request, queryset):
"""
Exports the queryset as a CSV file.
Args:
self: Django model admin object.
request: Django request object.
queryset: Queryset to export.
Returns:
HttpResponse: HTTP response with the CSV file.
"""
restricted_fields = [
'password',
'is_loggedin',
'validation',
'profile_photo',
'intrests',
'is_email_verified',
'is_profile_completed',
'is_locked',
]
meta = self.model._meta
field_names = []
for field in meta.fields:
if field.name not in restricted_fields:
field_names.append(field.name)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
writer = csv.writer(response)
writer.writerow(field_names)
for obj in queryset:
row = writer.writerow([getattr(obj, field) for field in field_names])
return response
def check_token(request):
"""
Checks the token from the request's cookie.
Args:
request: Django request object.
Returns:
JsonResponse: JSON response with the token payload or an error message.
"""
token = request.COOKIES.get('jwt')
if not token:
return JsonResponse({"message": "you are unauthenticated, Please Log in First"}, status=401)
try:
payload = jwt.decode(token, COOKIE_ENCRYPTION_SECRET, algorithms='HS256')
return payload
except jwt.ExpiredSignatureError:
return JsonResponse({"message": "Your token is expired, please login again"}, status=409)
def hash_password(password: str):
"""
Hashes a password for storing.
Args:
password (str): The password to hash.
Returns:
str: A string of length 60, containing the algorithm used and the hashed password.
"""
return str(bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()))[2:-1]
def check_password(password1: str, password2: str):
"""
Checks a hashed password using bcrypt.
Args:
password1 (str): The password to check.
password2 (str): The hash to check the password against.
Returns:
bool: True if the password matches, False otherwise.
"""
result = bcrypt.checkpw(password1.encode('utf-8'), password2.encode('utf-8'))
return result
class EmailSending:
def __init__(self, user) -> None:
self.address = user.email_id
self.subject = None
self.body = None
self.user = user
def email_varification(self):
"""
Sends an email verification email.
Returns:
int: Number of successfully sent emails.
"""
payload = {
'id': self.user.anwesha_id,
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
"iat": datetime.datetime.utcnow()
}
token = jwt.encode(
payload, COOKIE_ENCRYPTION_SECRET, algorithm='HS256')
link = "https://backend.anwesha.live/user/verifyemail/" + token
localhost_link = "http://127.0.0.1:8000/user/verifyemail/" + token
subject = "No reply"
body = f'''
Hello {self.address},\n
Please click on the link below to verify your email address for anwesha login:
\n{link}
\n\nThanks,
\nTeam Anwesha
'''
recipient_list = [self.address]
res = send_mail(subject, body, EMAIL_HOST_USER, recipient_list)
print(res)
return res
def hash_id(anwesha_id, secret):
"""
Hashes the given Anwesha ID using HMAC-SHA256.
Args:
anwesha_id (str): Anwesha ID to hash.
secret (str): Secret key.
Returns:
str: Hashed ID.
"""
anwesha_id = anwesha_id.encode('utf-8')
secret = secret.encode('utf-8')
digest = hmac.new(secret, msg=anwesha_id, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(digest).decode()
return signature