Skip to content

Commit

Permalink
[change] Saml-Authentication-creates-EmailAddress-Objects openwisp#523
Browse files Browse the repository at this point in the history
- Check if the NameID is an email and use it as the user's email.
- If NameID is not an email, check for the 'email' attribute in the SAML response.
- Create an EmailAddress object using the retrieved email.

Fixes openwisp#523
  • Loading branch information
kaushikaryan04 committed Jul 27, 2024
1 parent fd8a230 commit cf028b2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
17 changes: 17 additions & 0 deletions openwisp_radius/saml/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from urllib.parse import parse_qs, urlparse

import swapper
from allauth.account.models import EmailAddress
from django.conf import settings
from django.contrib.auth import logout
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
Expand Down Expand Up @@ -66,6 +67,22 @@ def post_login_hook(self, request, user, session_info):
try:
user.registered_user
except ObjectDoesNotExist:
email = None
uid_is_email = 'email' in getattr(
settings, 'SAML_ATTRIBUTE_MAPPING', {}
).get('uid', ())
if uid_is_email:
email = session_info['name_id'].text
if email is None:
email = session_info['ava'].get('email', [None])[0]
if email:
user.email = email
user.save()
email_address = EmailAddress.objects.create(
user=user, email=email, verified=True, primary=True
)
email_address.save()

registered_user = RegisteredUser(
user=user, method='saml', is_verified=app_settings.SAML_IS_VERIFIED
)
Expand Down
3 changes: 3 additions & 0 deletions openwisp_radius/tests/test_saml/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from urllib.parse import parse_qs, urlparse

import swapper
from allauth.account.models import EmailAddress
from django.contrib.auth import SESSION_KEY, get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
Expand Down Expand Up @@ -69,6 +70,8 @@ def _post_successful_auth_assertions(self, query_params, org_slug):
self.assertEqual(User.objects.count(), 1)
user_id = self.client.session[SESSION_KEY]
user = User.objects.get(id=user_id)
email = EmailAddress.objects.filter(user=user)
self.assertEqual(email.count(), 1)
self.assertEqual(user.username, 'org_user@example.com')
self.assertEqual(OrganizationUser.objects.count(), 1)
org_user = OrganizationUser.objects.get(user_id=user_id)
Expand Down

0 comments on commit cf028b2

Please sign in to comment.