80 lines
2.6 KiB
Python
80 lines
2.6 KiB
Python
|
from rest_framework import serializers
|
||
|
from django.contrib.auth import get_user_model
|
||
|
from .models import ResetOTP
|
||
|
import random
|
||
|
from django.core.mail import EmailMessage, EmailMultiAlternatives, message, get_connection
|
||
|
import uuid
|
||
|
User = get_user_model()
|
||
|
import MNF.settings as settings
|
||
|
|
||
|
class PasswordResetEmailSerializer(serializers.Serializer):
|
||
|
email = serializers.EmailField(max_length=255)
|
||
|
|
||
|
class Meta:
|
||
|
fields = ['email']
|
||
|
|
||
|
def recovery_code(self):
|
||
|
while True:
|
||
|
random_number = random.randint(1000, 9999)
|
||
|
if 1000 <= random_number <= 9999:
|
||
|
if ResetOTP.objects.filter(otp=random_number).exists():
|
||
|
continue
|
||
|
return random_number
|
||
|
|
||
|
def recovery_uuid(self):
|
||
|
while True:
|
||
|
uid = uuid.uuid4()
|
||
|
if ResetOTP.objects.filter(uid=uid).exists():
|
||
|
continue
|
||
|
return uid
|
||
|
|
||
|
def validate(self, attrs):
|
||
|
email = attrs.get('email')
|
||
|
user = None
|
||
|
otp_obj = None
|
||
|
|
||
|
if User.objects.filter(username=email):
|
||
|
user = User.objects.get(username=email)
|
||
|
if User.objects.filter(email=email):
|
||
|
user = User.objects.get(email=email)
|
||
|
else:
|
||
|
raise serializers.ValidationError('You are not a Registered User')
|
||
|
|
||
|
|
||
|
if ResetOTP.objects.filter(user=user):
|
||
|
print('otp objects found')
|
||
|
otp_obj = ResetOTP.objects.filter(user=user).first()
|
||
|
else:
|
||
|
print('otp objects not found')
|
||
|
otp_obj = ResetOTP(user=user)
|
||
|
|
||
|
otp_obj.otp = self.recovery_code()
|
||
|
otp_obj.uid =self.recovery_uuid()
|
||
|
otp_obj.save()
|
||
|
|
||
|
connection = get_connection(
|
||
|
host=settings.smtp_host,
|
||
|
port=settings.smtp_port,
|
||
|
username=settings.smtp_username,
|
||
|
password=settings.smtp_password, use_tls=True
|
||
|
)
|
||
|
|
||
|
mail_subject = 'Reset your MNF account password!'
|
||
|
message = f"Hi,\n\nWe've received your request to reset your password. Your one time password is {otp_obj.otp}"
|
||
|
email_sender = EmailMessage(mail_subject, message, to=[email], connection=connection)
|
||
|
email_sender = email_sender.send()
|
||
|
return attrs
|
||
|
|
||
|
|
||
|
|
||
|
class VerifyEmailSerializer(serializers.Serializer):
|
||
|
code = serializers.CharField(required=True)
|
||
|
|
||
|
class PasswordResetSerializer(serializers.Serializer):
|
||
|
|
||
|
token = serializers.CharField(required=True, max_length=255)
|
||
|
password = serializers.CharField(
|
||
|
max_length=255, style={'input_type': 'password'})
|
||
|
|
||
|
class Meta:
|
||
|
fields = ['token', 'password']
|