Skip to content

Commit

Permalink
add ProConnectLoginMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentporte committed Dec 5, 2024
1 parent c1236be commit c0fd40a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 6 deletions.
18 changes: 12 additions & 6 deletions lacommunaute/openid_connect/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,17 @@ class ProConnectLoginMiddleware(MiddlewareMixin):
def process_request(self, request):
query_params = request.GET.copy()

if "proconnect_login" in query_params:
query_params.pop("proconnect_login")
new_url = f"{request.path}?{urlencode(query_params)}" if query_params else request.path
if "proconnect_login" not in query_params:
return

if not request.user.is_authenticated:
return HttpResponseRedirect(reverse("openid_connect:authorize") + f"?next={new_url}")
query_params.pop("proconnect_login")
new_url = (
f"{request.path}?{urlencode({k: v for k, v in query_params.items() if v})}"
if query_params
else request.path
)

return HttpResponseRedirect(new_url)
if not request.user.is_authenticated:
return HttpResponseRedirect(reverse("openid_connect:authorize") + f"?next={new_url}")

return HttpResponseRedirect(new_url)
51 changes: 51 additions & 0 deletions lacommunaute/openid_connect/tests/test_middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import pytest
from django.urls import reverse

from lacommunaute.users.factories import UserFactory


@pytest.mark.parametrize(
"params,expected",
[
("?proconnect_login=true", ""),
("?proconnect_login=true&param=1", "?param=1"),
("?param=1&proconnect_login=true", "?param=1"),
],
)
def test_redirect_for_authenticated_user(client, db, params, expected):
client.force_login(UserFactory())
response = client.get(f"/{params}")
assert response.url == f"/{expected}"
assert response.status_code == 302


@pytest.mark.parametrize(
"params,expected",
[
("?proconnect_login=true", "/"),
("?proconnect_login=true&param=1", "/?param=1"),
("?param=1&proconnect_login=true", "/?param=1"),
],
)
def test_redirect_for_anonymous_user(client, db, params, expected):
response = client.get(f"/{params}")
assert response.url == f"{reverse('openid_connect:authorize')}?next={expected}"
assert response.status_code == 302


@pytest.mark.parametrize(
"params, logged",
[
("", True),
("?param=1", True),
("?param=1&key=2", True),
("", False),
("?param=1", False),
("?param=1&key=2", False),
],
)
def test_wo_proconnect_login_param(client, db, logged, params):
if logged:
client.force_login(UserFactory())
response = client.get(f"/{params}")
assert response.status_code == 200

0 comments on commit c0fd40a

Please sign in to comment.