Skip to content

Commit

Permalink
-display magic link in messages area, when debug mode is on
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentporte committed Nov 18, 2024
1 parent 7be0265 commit 4ba2f4a
Show file tree
Hide file tree
Showing 3 changed files with 175 additions and 4 deletions.
104 changes: 104 additions & 0 deletions lacommunaute/users/tests/__snapshots__/tests_views.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,58 @@



<section class="s-title-01 mt-lg-5">
<div class="s-title-01__container container">
<div class="s-title-01__row row">
<div class="s-title-01__col col-lg-8 col-12">
<h1 class="s-title-01__title h1">Se connecter | S'inscrire</h1>
</div>
</div>
</div>
</section>
<section class="s-section">
<div class="s-section__container container">
<div class="s-section__row row">
<div class="s-section__col col-12 col-lg-7">
<p>
Un lien de connexion vous a été envoyé à l'adresse [email protected]. Veuillez vérifier votre boîte de réception et cliquer sur le lien pour vous connecter.
</p>
</div>
</div>
</div>
</section>


</main>
'''
# ---
# name: TestCreateUserView.test_post_new_mail_in_debug_mode[debug_login_view_content]
'''
<main class="s-main" id="main" role="main">


<section class="s-section m-0">
<div class="s-section__container container">
<div class="s-section__row row">
<div class="s-section__col col-12"><div id="messages">


<div class="alert alert-success alert-dismissible fade show mt-3" role="status">
<button aria-label="Fermer" class="btn-close" data-bs-dismiss="alert" type="button"></button>
<a href="LOGIN_LINK>Login link</a> sent to [email protected]
</div>


</div>
</div>
</div>
</div>
</section>





<section class="s-title-01 mt-lg-5">
<div class="s-title-01__container container">
<div class="s-title-01__row row">
Expand Down Expand Up @@ -502,6 +554,58 @@



<section class="s-title-01 mt-lg-5">
<div class="s-title-01__container container">
<div class="s-title-01__row row">
<div class="s-title-01__col col-lg-8 col-12">
<h1 class="s-title-01__title h1">Se connecter | S'inscrire</h1>
</div>
</div>
</div>
</section>
<section class="s-section">
<div class="s-section__container container">
<div class="s-section__row row">
<div class="s-section__col col-12 col-lg-7">
<p>
Un lien de connexion vous a été envoyé à l'adresse [email protected]. Veuillez vérifier votre boîte de réception et cliquer sur le lien pour vous connecter.
</p>
</div>
</div>
</div>
</section>


</main>
'''
# ---
# name: TestLoginView.test_post_in_debug_mode[debug_login_view_content]
'''
<main class="s-main" id="main" role="main">


<section class="s-section m-0">
<div class="s-section__container container">
<div class="s-section__row row">
<div class="s-section__col col-12"><div id="messages">


<div class="alert alert-success alert-dismissible fade show mt-3" role="status">
<button aria-label="Fermer" class="btn-close" data-bs-dismiss="alert" type="button"></button>
<a href="LOGIN_LINK>Login link</a> sent to [email protected]
</div>


</div>
</div>
</div>
</div>
</section>





<section class="s-title-01 mt-lg-5">
<div class="s-title-01__container container">
<div class="s-title-01__row row">
Expand Down
63 changes: 62 additions & 1 deletion lacommunaute/users/tests/tests_views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import re
from unittest import mock
from urllib.parse import urlencode

Expand All @@ -7,6 +8,7 @@
import respx
from django.conf import settings
from django.contrib.auth.tokens import default_token_generator
from django.test import RequestFactory, override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
Expand All @@ -24,6 +26,21 @@
next_url_tuples = [("/", "/"), ("/topics/", "/topics/"), ("http://www.unallowed_host.com", "/")]


@pytest.fixture(name="override_debug_toolbar_settings")
def override_debug_toolbar_settings_fixture():
with override_settings(
DEBUG=True,
INSTALLED_APPS=[app for app in settings.INSTALLED_APPS if app != "debug_toolbar"],
MIDDLEWARE=[
middleware
for middleware in settings.MIDDLEWARE
if middleware != "debug_toolbar.middleware.DebugToolbarMiddleware"
],
DEBUG_TOOLBAR_CONFIG={},
):
yield


@pytest.fixture(name="mock_respx_post_to_sib_smtp_url")
def mock_respx_post_to_sib_smtp_url_fixture():
with respx.mock:
Expand Down Expand Up @@ -80,9 +97,10 @@ def validate_magiclink_payload(payload_as_str, uidb64, token, expected):

class TestSendMagicLink:
def test_send_magic_link(self, db, snapshot, mock_respx_post_to_sib_smtp_url):
request = RequestFactory().get("/")
user = UserFactory(first_name="Edith", last_name="Martin", email="[email protected]")
next_url = "/topics/"
send_magic_link(user, next_url)
send_magic_link(request, user, next_url)

token = default_token_generator.make_token(user)
uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
Expand Down Expand Up @@ -130,6 +148,28 @@ def test_post(
payload_as_str = respx.calls[0].request.content.decode()
assert validate_magiclink_payload(payload_as_str, uidb64, token, expected)

def test_post_in_debug_mode(
self,
client,
db,
fixed_user_token,
snapshot,
mock_token_generator,
mock_respx_post_to_sib_smtp_url,
override_debug_toolbar_settings,
):
user, uidb64, token = fixed_user_token
response = client.post(
reverse("users:login"),
data={"email": user.email, "next": "/topics/"},
)
assert response.status_code == 200

content = parse_response_to_soup(response, selector="main")
pattern = r'http.*?next=%2Ftopics%2F"'
content_as_str = re.sub(pattern, "LOGIN_LINK", str(content))
assert content_as_str == snapshot(name="debug_login_view_content")

@pytest.mark.parametrize("next_url,expected", next_url_tuples)
def test_redirection_when_email_is_unknown(self, client, db, next_url, expected, mock_respx_post_to_sib_smtp_url):
response = client.post(
Expand Down Expand Up @@ -201,6 +241,27 @@ def test_post_existing_email(
payload_as_str = respx.calls[0].request.content.decode()
assert validate_magiclink_payload(payload_as_str, uidb64, token, expected)

def test_post_new_mail_in_debug_mode(
self,
client,
db,
snapshot,
mock_token_generator,
mock_respx_post_to_sib_smtp_url,
override_debug_toolbar_settings,
):
email = "[email protected]"
response = client.post(
reverse("users:create"),
data={"email": email, "first_name": "John", "last_name": "Travolta", "next": "/topics/"},
)
assert response.status_code == 200

content = parse_response_to_soup(response, selector="main")
pattern = r'http.*?next=%2Ftopics%2F"'
content_as_str = re.sub(pattern, "LOGIN_LINK", str(content))
assert content_as_str == snapshot(name="debug_login_view_content")


class TestLoginWithLinkView:
def test_user_not_found(self, client, db):
Expand Down
12 changes: 9 additions & 3 deletions lacommunaute/users/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
from urllib.parse import urlencode

from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login, logout
from django.contrib.auth.tokens import default_token_generator
from django.http import HttpResponseRedirect
from django.shortcuts import redirect, render
from django.urls import reverse
from django.utils.encoding import force_bytes, force_str
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
from django.utils.safestring import mark_safe
from django.views.generic import FormView

from lacommunaute.forum_member.models import ForumProfile
Expand All @@ -24,7 +26,7 @@
logger = logging.getLogger(__name__)


def send_magic_link(user, next_url):
def send_magic_link(request, user, next_url):
token = default_token_generator.make_token(user)
uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
url = reverse("users:login_with_link", kwargs={"uidb64": uidb64, "token": token})
Expand All @@ -38,6 +40,10 @@ def send_magic_link(user, next_url):
template_id=settings.SIB_MAGIC_LINK_TEMPLATE,
)

if settings.DEBUG is True:
message = mark_safe(f'<a href="{login_link}">Login link</a> sent to {user.email}')
messages.success(request, message)


class LoginView(FormView):
template_name = "registration/login_with_magic_link.html"
Expand All @@ -62,7 +68,7 @@ def form_valid(self, form):
query_params = {"email": email, "next": clean_next_url(next_url)}
return HttpResponseRedirect(f"{base_url}?{urlencode(query_params)}")

send_magic_link(user, next_url)
send_magic_link(self.request, user, next_url)
return render(self.request, "registration/login_link_sent.html", {"email": email})


Expand Down Expand Up @@ -91,7 +97,7 @@ def form_valid(self, form):
)
ForumProfile.objects.create(user=user)

send_magic_link(user, next_url)
send_magic_link(self.request, user, next_url)
return render(self.request, "registration/login_link_sent.html", {"email": email})


Expand Down

0 comments on commit 4ba2f4a

Please sign in to comment.