Snippets

Sergio Delgado Quintero Remind credentials

Created by Sergio Delgado Quintero
def remind_credentials(request):
    if request.user.is_authenticated():
        return redirect("videos")

    if request.method == "POST":
        form = RemindCredentialsForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get("email")
            # validation already checked that user exists
            u = User.objects.get(email=email)
            id = uuid.uuid1()
            redis_key = "reset_{}".format(id)
            settings.REDIS.set(redis_key, u.username)
            send_remind_credentials_email.delay(
                u.username,
                "http://{}/reset_password/{}/".format(
                    settings.BASE_DOMAIN,
                    id
                ),
                email
            )
            messages.add_message(
                request,
                messages.SUCCESS,
                "Se ha enviado un correo electrónico a la dirección "
                "proporcionada. "
                "Revisa tu bandeja de entrada para resetear la contraseña."
            )
            return render(
                request,
                "app/message.html"
            )
    else:
        form = RemindCredentialsForm()

    return render(
        request,
        "app/remind_credentials.html",
        {"form": form}
    )


def reset_password(request, reset_id):
    if request.user.is_authenticated():
        return redirect("videos")

    redis_key = "reset_{}".format(reset_id)
    if not settings.REDIS.exists(redis_key):
        messages.add_message(
            request,
            messages.ERROR,
            "Identificador de reseteo de contraseña no encontrado."
        )
        url_next = reverse("login")
        return render(
            request,
            "app/message.html",
            {"url_next": url_next}
        )
    if request.method == "POST":
        form = ResetPasswordForm(request.POST)
        if form.is_valid():
            password = form.cleaned_data.get("password")
            username = settings.REDIS.get(redis_key)
            u = User.objects.get(username=username)
            u.set_password(password)
            u.save()
            messages.add_message(
                request,
                messages.SUCCESS,
                "La contraseña ha sido reestablecida con éxito."
            )
            settings.REDIS.delete(redis_key)
            return render(
                request,
                "app/message.html",
                {"url_next": reverse("login")}
            )
    else:
        form = ResetPasswordForm()

    return render(
        request,
        "app/reset_password.html",
        {"form": form}
    )

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.