From 2d1510aae1698872a86424c5c7779ae49c064578 Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Mon, 30 Aug 2021 15:28:48 +0200 Subject: [PATCH] adapters: truncate username to the field's max_length (#56482) --- mellon/adapters.py | 5 ++++- tests/test_default_adapter.py | 6 +++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/mellon/adapters.py b/mellon/adapters.py index ee95a2f..64004cb 100644 --- a/mellon/adapters.py +++ b/mellon/adapters.py @@ -27,6 +27,7 @@ import requests import requests.exceptions from atomicwrites import atomic_write from django.contrib import auth, messages +from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.core.exceptions import FieldDoesNotExist, PermissionDenied from django.core.files.storage import default_storage @@ -56,6 +57,8 @@ def display_truncated_list(l, max_length=10): class DefaultAdapter: + user_class = get_user_model() + def __init__(self, request=None): self.request = request @@ -275,7 +278,7 @@ class DefaultAdapter: username_template = utils.get_setting(idp, 'USERNAME_TEMPLATE') try: username = force_text(username_template).format(realm=realm, attributes=saml_attributes, idp=idp)[ - :30 + : self.user_class._meta.get_field('username').max_length ] except ValueError: logger.error('mellon: invalid username template %r', username_template) diff --git a/tests/test_default_adapter.py b/tests/test_default_adapter.py index 771c885..8617a28 100644 --- a/tests/test_default_adapter.py +++ b/tests/test_default_adapter.py @@ -68,9 +68,9 @@ def jane(db): def test_format_username(settings, idp, saml_attributes): adapter = DefaultAdapter() assert adapter.format_username(idp, {}) is None - assert adapter.format_username(idp, saml_attributes) == ('x' * 32 + '@saml')[:30] + assert adapter.format_username(idp, saml_attributes) == ('x' * 32 + '@saml') settings.MELLON_USERNAME_TEMPLATE = '{attributes[name_id_content]}' - assert adapter.format_username(idp, saml_attributes) == ('x' * 32)[:30] + assert adapter.format_username(idp, saml_attributes) == ('x' * 32) settings.MELLON_USERNAME_TEMPLATE = '{attributes[username][0]}' assert adapter.format_username(idp, saml_attributes) == 'foobar' @@ -127,7 +127,7 @@ def test_provision_user_attributes(settings, django_user_model, idp, saml_attrib 'last_name': '{attributes[last_name][0]}', } user = SAMLBackend().authenticate(saml_attributes=saml_attributes) - assert user.username == 'x' * 30 + assert user.username == 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@saml' assert user.first_name == 'Foo' assert user.last_name == 'Bar' assert user.email == 'test@example.net'