I have been using django for some year now but not as always
what would probably be the issue to the email verification keeps failing sometimes.
here are the code i wrote
from django.contrib.auth.tokens import PasswordResetTokenGenerator
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
str(user.pk) + str(timestamp) + str(user.is_active)
)
generate_token = TokenGenerator()
def send_account_verification_email(user):
uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
token = generate_token.make_token(user)
# production email link
verification_link = f'https://culture-lancer.vercel.app/account-verification/{uidb64}/{token}/'
# verification_link = f'http://localhost:3000/account-verification/{uidb64}/{token}/'
# Prepare email context
context = {
'user': user,
'verification_link': verification_link,
}
# Render the HTML email template
html_message = render_to_string('account_verification_email.html', context)
plain_message = strip_tags(html_message) # Fallback for email clients that don't support HTML
# Send email
send_mail(
'Verify Your Email - CultureLancer',
plain_message,
settings.DEFAULT_FROM_EMAIL,
[user.email],
html_message=html_message,
)
class ApplicantVerifyEmailView(APIView):
"""
endpoint to verify email after signup pass the uidb64 and token
"""
def get(self, request, uidb64,token):
try:
# Decode the UID and get the user and assessment ID
uid = urlsafe_base64_decode(uidb64).decode()
user = CareerUser.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, CareerUser.DoesNotExist):
return Response({'error': 'Invalid user ID'}, status=status.HTTP_400_BAD_REQUEST)
# Check the token validity
if user is not None and generate_token.check_token(user, token):
user.is_active = True # Activate user
user.save()
return Response({'message': 'Email verified successfully,'}, status=status.HTTP_200_OK)
else:
return Response({'error': 'Invalid token'}, status=status.HTTP_400_BAD_REQUEST)