Skip to content

Commit c5bd09e

Browse files
committed
Fix some more tests and other improvements
1 parent 24f79c0 commit c5bd09e

File tree

7 files changed

+308
-133
lines changed

7 files changed

+308
-133
lines changed

docs/conf.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,13 @@
1111
# documentation root, use os.path.abspath to make it absolute, like shown here.
1212
#
1313
import os
14-
15-
# sys.path.insert(0, os.path.abspath('.'))
14+
from datetime import datetime
1615

1716

1817
# -- Project information -----------------------------------------------------
1918

2019
project = "drf-user"
21-
copyright = "2020, 101 Loop"
20+
copyright = f"{datetime.now().year}, 101 Loop"
2221
author = "101 Loop"
2322

2423
parent_dir = os.path.dirname(os.path.dirname(__file__))

drf_user/admin.py

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,18 @@
11
"""
22
All Admin configuration related to drf_user
3-
4-
Author: Himanshu Shankar (https://himanshus.com)
53
"""
64
from django.contrib import admin
7-
from django.contrib.auth.admin import Group
8-
from django.contrib.auth.admin import GroupAdmin
9-
from django.contrib.auth.admin import UserAdmin
5+
from django.contrib.auth.admin import Group, GroupAdmin, UserAdmin
106
from django.utils.text import gettext_lazy as _
117

12-
from .models import AuthTransaction
13-
from .models import OTPValidation
14-
from .models import Role
15-
from .models import User
8+
from drf_user.models import AuthTransaction, OTPValidation, Role, User
169

1710

11+
@admin.register(User)
1812
class DRFUserAdmin(UserAdmin):
1913
"""
2014
Overrides UserAdmin to show fields name & mobile and remove fields:
2115
first_name, last_name
22-
23-
Author: Himanshu Shankar (https://himanshus.com)
2416
"""
2517

2618
fieldsets = (
@@ -57,12 +49,14 @@ class DRFUserAdmin(UserAdmin):
5749
readonly_fields = ("date_joined", "last_login", "update_date")
5850

5951

52+
@admin.register(OTPValidation)
6053
class OTPValidationAdmin(admin.ModelAdmin):
6154
"""OTP Validation Admin"""
6255

6356
list_display = ("destination", "otp", "prop")
6457

6558

59+
@admin.register(AuthTransaction)
6660
class AuthTransactionAdmin(admin.ModelAdmin):
6761
"""AuthTransaction Admin"""
6862

@@ -89,7 +83,3 @@ def has_delete_permission(self, request, obj=None):
8983
# Source: https://stackoverflow.com/a/32445368
9084
admin.site.unregister(Group)
9185
admin.site.register(Role, GroupAdmin)
92-
93-
admin.site.register(User, DRFUserAdmin)
94-
admin.site.register(OTPValidation, OTPValidationAdmin)
95-
admin.site.register(AuthTransaction, AuthTransactionAdmin)

drf_user/serializers.py

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from drf_user import user_settings
1111
from drf_user.models import User
12-
from drf_user.utils import check_validation
12+
from drf_user.utils import check_validation, is_mobile_valid
1313
from drf_user.constants import EMAIL, MOBILE
1414

1515

@@ -234,6 +234,11 @@ class OTPLoginRegisterSerializer(serializers.Serializer):
234234
verify_otp = serializers.CharField(default=None, required=False)
235235
mobile = serializers.CharField(required=True)
236236

237+
def validate_mobile(self, value: str) -> str:
238+
"""Validate whether the mobile is unique."""
239+
is_mobile_valid(value)
240+
return value
241+
237242
@staticmethod
238243
def get_user(email: str, mobile: str):
239244
"""Fetches user object"""
@@ -242,27 +247,27 @@ def get_user(email: str, mobile: str):
242247
except User.DoesNotExist:
243248
try:
244249
user = User.objects.get(mobile=mobile)
245-
except User.DoesNotExist as e:
246-
raise NotFound(
247-
_(f"No user exists either for email={email} or mobile={mobile}")
248-
) from e
249-
250-
if user.email != email:
251-
raise serializers.ValidationError(
252-
_(
253-
"Your account is registered with {mobile} does not has "
254-
"{email} as registered email. Please login directly via "
255-
"OTP with your mobile.".format(mobile=mobile, email=email)
250+
except User.DoesNotExist:
251+
# new user is trying to register
252+
user = None
253+
254+
if user:
255+
if user.email != email:
256+
raise serializers.ValidationError(
257+
_(
258+
f"Your account is registered with {mobile} does not has "
259+
f"{email} as registered email. Please login directly via "
260+
"OTP with your mobile."
261+
)
256262
)
257-
)
258-
if user.mobile != mobile:
259-
raise serializers.ValidationError(
260-
_(
261-
"Your account is registered with {email} does not has "
262-
"{mobile} as registered mobile. Please login directly via "
263-
"OTP with your email.".format(mobile=mobile, email=email)
263+
if user.mobile != mobile:
264+
raise serializers.ValidationError(
265+
_(
266+
f"Your account is registered with {email} does not has "
267+
f"{mobile} as registered mobile. Please login directly via "
268+
"OTP with your email."
269+
)
264270
)
265-
)
266271
return user
267272

268273
def validate(self, attrs: dict) -> dict:

drf_user/utils.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ def check_validation(value: str) -> bool:
233233
return False
234234

235235

236-
def validate_mobile(mobile: str) -> bool:
236+
def is_mobile_valid(mobile: str) -> bool:
237237
"""
238238
This function checks if the mobile number is valid or not.
239239
Parameters
@@ -248,12 +248,12 @@ def validate_mobile(mobile: str) -> bool:
248248
Examples
249249
--------
250250
To check if '9999999999' is a valid mobile number
251-
>>> print(validate_mobile('9999999999'))
251+
>>> print(is_mobile_valid('9999999999'))
252252
True
253253
"""
254254
match = re.match(r"^[6-9]\d{9}$", str(mobile))
255255
if match is None:
256-
raise ValidationError("Invalid Mobile Number")
256+
raise ValidationError("Enter a valid mobile number.")
257257
return True
258258

259259

@@ -281,8 +281,8 @@ def validate_otp(*, destination: str, otp_val: int) -> bool:
281281
except OTPValidation.DoesNotExist as e:
282282
raise NotFound(
283283
detail=_(
284-
"No pending OTP validation request found for provided destination."
285-
" Kindly send an OTP first"
284+
f"No pending OTP validation request found for provided {destination}."
285+
" Kindly send an OTP first."
286286
)
287287
) from e
288288

@@ -350,7 +350,7 @@ def send_message(
350350

351351
if recip_mobile:
352352
# check for valid mobile numbers
353-
validate_mobile(recip_mobile)
353+
is_mobile_valid(recip_mobile)
354354

355355
try:
356356
send_mail(
@@ -361,7 +361,8 @@ def send_message(
361361
recipient_list=[recip_email],
362362
)
363363
except Exception as e: # noqa
364-
sent["message"] = f"Email Message sending failed! {str(e.args)}"
364+
logger.error("Email sending failed", exc_info=e)
365+
sent["message"] = str(e)
365366
sent["success"] = False
366367
else:
367368
sent["message"] = "Email Message sent successfully!"
@@ -371,8 +372,8 @@ def send_message(
371372
try:
372373
api.send_sms(body=message, to=recip_mobile, from_phone=None)
373374
except Exception as e: # noqa
374-
logger.debug("Message sending failed", exc_info=e)
375-
sent["mobile_message"] = f"Mobile Message sending failed! {str(e.args)}"
375+
logger.error("Message sending failed", exc_info=e)
376+
sent["mobile_message"] = str(e)
376377
else:
377378
sent["mobile_message"] = "Mobile Message sent successfully!"
378379

drf_user/views.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,8 +309,13 @@ def post(self, request, *args, **kwargs):
309309
sent_otp_resp: dict = send_otp(otp_obj=otp_obj, recip_email=email, recip_mobile=mobile)
310310

311311
if not sent_otp_resp["success"]:
312+
# delete otp object if OTP could not be sent
313+
otp_obj.delete()
312314
raise serializers.ValidationError(
313-
detail=_(f"OTP could not be sent! {sent_otp_resp['message']}")
315+
{
316+
"message": "OTP could not be sent! Please try again after some time.",
317+
"exc": sent_otp_resp["message"],
318+
}
314319
)
315320

316321
otp_obj.send_counter = F("send_counter") + 1
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
"""Store mock responses here"""
2+
3+
email_mobile_message_sent = {
4+
"success": True,
5+
"message": "Email Message sent successfully!",
6+
"mobile_message": "Mobile Message sent successfully!",
7+
}

0 commit comments

Comments
 (0)