reset password added

This commit is contained in:
mi1468 2025-05-04 17:14:46 +03:30
parent 76be3636f7
commit ad5604d1fc
3 changed files with 133 additions and 1 deletions

View File

@ -29,9 +29,13 @@ urlpatterns = [
re_path('submitEmailVerification', userView.submitEmailVerification), re_path('submitEmailVerification', userView.submitEmailVerification),
re_path('submitSmsVerification', userView.submitSmsVerification), re_path('submitSmsVerification', userView.submitSmsVerification),
re_path('sendForgetPasswordCode', userView.sendForgetPasswordCode), re_path('sendForgetPasswordCode', userView.sendForgetPasswordCode),
re_path('sendCodeAndNewPassword', userView.sendCodeAndNewPassword), re_path('sendCodeAndNewPassword', userView.sendCodeAndNewPassword),
re_path('requestResetCode', userView.requestResetCode),
re_path('verifyResetCode', userView.verifyResetCode),

View File

@ -45,6 +45,11 @@ import json
import logging import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
from django.core.cache import cache
import random
import string
import requests
import json
def send_sms(to_number, code): def send_sms(to_number, code):
@ -713,3 +718,126 @@ def resetPassword(request):
# and optionally return a new token # and optionally return a new token
return Response({'message': 'Password updated successfully'}, status=status.HTTP_200_OK) return Response({'message': 'Password updated successfully'}, status=status.HTTP_200_OK)
def generate_code(length=6):
"""Generate a random verification code."""
return ''.join(random.choices(string.digits, k=length))
@api_view(['POST'])
def requestResetCode(request):
"""
Request a password reset code for the given mobile number.
Expects: {'mobile_number': 'string'}
Returns: {'success': bool, 'message': 'string'}
"""
mobile_number = request.data.get('mobile_number')
if not mobile_number:
return Response(
{'success': False, 'message': 'Mobile number is required'},
status=status.HTTP_400_BAD_REQUEST
)
# Check if customer exists with the mobile number
customer = Customer.objects.get(mobile_number=mobile_number)
user = customer.user # Get the associated User
# Generate verification code
code = generate_code()
# Store code in cache with 10-minute expiration
cache_key = f"reset_code_{mobile_number}"
cache.set(cache_key, code, timeout=600)
# Send code via SMS
sms_result = send_sms(mobile_number, code)
if sms_result == 0:
return Response(
{'success': False, 'message': sms_result['message']},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
return Response(
{'success': True, 'message': 'Verification code sent successfully'},
status=status.HTTP_200_OK
)
@api_view(['POST'])
def verifyResetCode(request):
"""
Verify the reset code and update the password.
Expects: {'mobile_number': 'string', 'code': 'string', 'password': 'string'}
Returns: {'success': bool, 'message': 'string'}
"""
mobile_number = request.data.get('mobile_number')
code = request.data.get('code')
new_password = request.data.get('password')
if not all([mobile_number, code, new_password]):
return Response(
{'success': False, 'message': 'Mobile number, code, and new password are required'},
status=status.HTTP_400_BAD_REQUEST
)
try:
# Retrieve customer and associated user
customer = Customer.objects.get(mobile_number=mobile_number)
user = customer.user # Get the associated User
# Check cached code
cache_key = f"reset_code_{mobile_number}"
stored_code = cache.get(cache_key)
if not stored_code:
return Response(
{'success': False, 'message': 'Code has expired or is invalid'},
status=status.HTTP_400_BAD_REQUEST
)
if stored_code != code:
return Response(
{'success': False, 'message': 'Invalid verification code'},
status=status.HTTP_400_BAD_REQUEST
)
# Validate password (basic example; add more validation as needed)
if len(new_password) < 6:
return Response(
{'success': False, 'message': 'Password must be at least 8 characters long'},
status=status.HTTP_400_BAD_REQUEST
)
# Update password
print(new_password)
user.set_password(new_password)
user.save()
# Clear the cache
cache.delete(cache_key)
return Response(
{'success': True, 'message': 'Password reset successfully'},
status=status.HTTP_200_OK
)
except Customer.DoesNotExist:
return Response(
{'success': False, 'message': 'No user found with this mobile number'},
status=status.HTTP_404_NOT_FOUND
)
except Exception as e:
return Response(
{'success': False, 'message': f'Error resetting password: {str(e)}'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)

Binary file not shown.