restore password

This commit is contained in:
Diego Calvo
2021-03-31 10:14:36 +02:00
parent 373e892463
commit 7399b6a480
4 changed files with 725 additions and 0 deletions

View File

@@ -1,4 +1,6 @@
import logging
import random
import string
from io import BytesIO
from django.contrib.auth import get_user_model
@@ -199,3 +201,7 @@ def coop_loader(csv_reader, request=None):
logging.error(f"Could not parse {row}")
return coop_counter, user_counter
def generate_password(length):
result_str = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(length))
return result_str

View File

@@ -15,6 +15,8 @@ from django.db import IntegrityError
from django.contrib.gis.geos import Point, GEOSGeometry
from django.shortcuts import redirect
from django.conf import settings
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from rest_framework import status
from rest_framework import viewsets
@@ -203,6 +205,42 @@ def activate_user(request, uidb64, token):
else:
return Response({"error": f"Tu token de verificacion no coincide con ningún usuario registrado"}, status=status.HTTP_406_NOT_ACCEPTABLE)
@api_view(['POST'])
@permission_classes([AllowAny,])
def forgotten_password(request):
"""Set new password for registered user and send email
"""
if 'email' not in request.data:
return Response({"error": "Missing parameter: email"}, status=400)
email = request.data['email']
user = User.objects.get(email=email)
if user:
try:
password = utils.generate_password(12)
print(password)
user.set_password(password)
user.save()
except:
return Response({'error': f"Could not set new password [{str(type(e))}]: {str(e)}"}, status=500)
try:
message = render_to_string('forgotten_password.html', {
'user': user,
'password': password,
})
subject = "[latienda.coop] Contraseña restablecida"
email = EmailMessage(subject, message, to=[email])
email.content_subtype = "html"
email.send()
logging.info(f"Email sent to {email}")
except Exception as e:
return Response({'error': f"Could not send emails [{str(type(e))}]: {str(e)}"}, status=500)
else:
return Response({'error': f"This email has no user related to it"}, status=404)
return Response()
@api_view(['GET',])
@permission_classes([IsAdminUser,])