Skip to content

Commit

Permalink
[feature] Added view to collect email in SAML registration
Browse files Browse the repository at this point in the history
If the IdP does not include email address in SAML response,
then the user will be asked for email during sign-up.
  • Loading branch information
pandafy committed Nov 1, 2024
1 parent dcc5165 commit 4a7897f
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 12 deletions.
5 changes: 5 additions & 0 deletions openwisp_radius/saml/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ def get_saml_urls(saml_views=None):
saml_views.AssertionConsumerServiceView.as_view(),
name='saml2_acs',
),
path(
'additional-info/',
saml_views.LoginAdditionalInfoView.as_view(),
name='saml2_additional_info',
),
path(
'logout/',
saml_views.LogoutInitView.as_view(),
Expand Down
66 changes: 60 additions & 6 deletions openwisp_radius/saml/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import logging
from urllib.parse import parse_qs, urlparse
from urllib.parse import parse_qs, quote, urlencode, urlparse

import swapper
from allauth.account.utils import send_email_confirmation
from django import forms
from django.conf import settings
from django.contrib.auth import logout
from django.contrib.auth import get_user_model, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.shortcuts import get_object_or_404, render
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.generic import UpdateView
from djangosaml2.utils import validate_referral_url
from djangosaml2.views import (
AssertionConsumerServiceView as BaseAssertionConsumerServiceView,
)
Expand All @@ -20,6 +26,7 @@

logger = logging.getLogger(__name__)

User = get_user_model()
Organization = swapper.load_model('openwisp_users', 'Organization')
RadiusToken = load_model('RadiusToken')
RegisteredUser = load_model('RegisteredUser')
Expand Down Expand Up @@ -87,10 +94,57 @@ def custom_redirect(self, user, relay_state, session_info):
"""
Token.objects.filter(user=user).delete()
token, _ = Token.objects.get_or_create(user=user)
return (
f'{relay_state}?username={user.username}&token={token.key}&'
f'login_method=saml'
next = '{relay_state}?{params}'.format(
relay_state=relay_state,
params=urlencode(
{'username': user.username, 'token': token.key, 'login_method': 'saml'}
),
)
return '{path}?next={next}'.format(
path=reverse('radius:saml2_additional_info'), next=quote(next)
)


class LoginAdditionalInfoForm(forms.ModelForm):
class Meta:
model = User
fields = ['email']

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['email'].required = True


class LoginAdditionalInfoView(LoginRequiredMixin, UpdateView):
model = User
form_class = LoginAdditionalInfoForm
template_name = 'djangosaml2/login_additional_info.html'

def get_object(self):
return self.request.user

def get_response(self):
success_url = self.get_success_url()
if success_url:
return redirect(success_url)
return render(self.request, 'djangosaml2/login_error.html')

def get_success_url(self):
return validate_referral_url(self.request, self.request.GET.get('next'))

def form_valid(self, form):
user = form.save()
send_email_confirmation(self.request, user, signup=True, email=user.email)
return self.get_response()

def is_user_profile_complete(self):
return self.request.user.email

def get(self, request, *args, **kwargs):
# Redirect user to the next page if the user profile is complete.
if self.is_user_profile_complete():
return self.get_response()
return super().get(request, *args, **kwargs)


class LoginView(OrganizationSamlMixin, BaseLoginView):
Expand Down
12 changes: 12 additions & 0 deletions openwisp_radius/templates/djangosaml2/login_additional_info.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{% extends "account/base_manage.html" %}
{% load i18n %}

{% block content %}
<h1>{% trans "Add Your Email to Complete Your Account Setup" %}</h1>
<p>{% blocktrans %}It looks like we didn't receive your email from your identity provider.</br>Please enter your email address below to complete setting up your account.{% endblocktrans %}</p>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="button" value="{% trans "Save Email Address and Continue" %}">
</form>
{% endblock %}
62 changes: 56 additions & 6 deletions openwisp_radius/tests/test_saml/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
from urllib.parse import parse_qs, urlparse

import swapper
from django.conf import settings
from django.contrib.auth import SESSION_KEY, get_user_model
from django.core import mail
from django.test import TestCase, override_settings
from django.urls import reverse
from django.urls import reverse, reverse_lazy
from djangosaml2.tests import auth_response, conf
from djangosaml2.utils import get_session_id_from_saml2, saml2_from_httpredirect_request
from rest_framework.authtoken.models import Token
Expand Down Expand Up @@ -74,15 +76,18 @@ def _post_successful_auth_assertions(self, query_params, org_slug):
org_user = OrganizationUser.objects.get(user_id=user_id)
self.assertEqual(org_user.organization.slug, org_slug)
expected_query_params = {
'username': ['[email protected]'],
'token': [Token.objects.get(user_id=user_id).key],
'login_method': ['saml'],
'next': [
'/radius/saml2/additional-info/'
'?username=org_user%40example.com'
f'&token={Token.objects.get(user_id=user_id).key}'
'&login_method=saml'
]
}
self.assertDictEqual(query_params, expected_query_params)

@capture_any_output()
def test_organization_slug_present(self):
expected_redirect_url = 'https://captive-portal.example.com'
expected_redirect_url = '/radius/saml2/additional-info/'
org_slug = 'default'
relay_state = self._get_relay_state(
redirect_url=expected_redirect_url, org_slug=org_slug
Expand All @@ -102,7 +107,7 @@ def test_organization_slug_present(self):

@capture_any_output()
def test_relay_state_relative_path(self):
expected_redirect_path = '/captive/portal/page'
expected_redirect_path = '/radius/saml2/additional-info/'
org_slug = 'default'
relay_state = self._get_relay_state(
redirect_url=expected_redirect_path, org_slug=org_slug
Expand Down Expand Up @@ -165,6 +170,51 @@ def test_user_registered_with_non_saml_method(self):
self.assertEqual(user.username, '[email protected]')


@override_settings(SAML_ALLOWED_HOSTS=['captive-portal.example.com'])
class TestAdditionInfoView(TestSamlMixin, TestCase):
view_path = reverse_lazy('radius:saml2_additional_info')

def test_unauthenticated_user(self):
response = self.client.get(self.view_path)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, f'{settings.LOGIN_URL}?next={self.view_path}')

def test_user_has_email(self):
user = self._create_user()
self.client.force_login(user)
response = self.client.get(
f'{self.view_path}?next=https://captive-portal.example.com/login/'
)
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, 'https://captive-portal.example.com/login/')

def test_user_has_no_email(self):
user = self._create_user()
User.objects.filter(pk=user.pk).update(email='')
self.client.force_login(user)
url = f'{self.view_path}?next=https://captive-portal.example.com/login/'
response = self.client.get(url)
# Verify that a form is displayed to collect email
self.assertEqual(response.status_code, 200)
self.assertContains(
response,
'<input type="email" name="email" maxlength="254" required id="id_email">',
)

# Make post request to set email
response = self.client.post(url, data={'email': '[email protected]'})
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, 'https://captive-portal.example.com/login/')
user.refresh_from_db()
self.assertEqual(user.email, '[email protected]')
self.assertEqual(
user.emailaddress_set.filter(email='[email protected]').count(), 1
)
self.assertEqual(
mail.outbox[0].subject, '[example.com] Please Confirm Your Email Address'
)


@override_settings(
SAML_CONFIG=conf.create_conf(
sp_host='sp.example.com',
Expand Down
7 changes: 7 additions & 0 deletions tests/openwisp2/sample_radius/saml/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from openwisp_radius.saml.views import (
AssertionConsumerServiceView as BaseAssertionConsumerServiceView,
)
from openwisp_radius.saml.views import (
LoginAdditionalInfoView as BaseLoginAdditionalInfoView,
)
from openwisp_radius.saml.views import LoginView as BaseLoginView
from openwisp_radius.saml.views import LogoutInitView as BaseLogoutInitView
from openwisp_radius.saml.views import LogoutView as BaseLogoutView
Expand All @@ -11,6 +14,10 @@ class AssertionConsumerServiceView(BaseAssertionConsumerServiceView):
pass


class LoginAdditionalInfoView(BaseLoginAdditionalInfoView):
pass


class LoginView(BaseLoginView):
pass

Expand Down

0 comments on commit 4a7897f

Please sign in to comment.