Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correctly catch FieldDoesNotExist exceptions #96

Merged
merged 1 commit into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions mozilla_django_oidc_db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError
from django.core.exceptions import FieldDoesNotExist, ValidationError
from django.db import models
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _
Expand Down Expand Up @@ -325,14 +325,14 @@ def clean(self):
for field in self.claim_mapping.keys():
try:
User._meta.get_field(field)
except models.FieldDoesNotExist:
except FieldDoesNotExist as exc:
raise ValidationError(
{
"claim_mapping": _(
"Field {field} does not exist on the user model"
"Field '{field}' does not exist on the user model"
).format(field=field)
}
)
) from exc

if User.USERNAME_FIELD in self.claim_mapping:
raise ValidationError(
Expand Down
36 changes: 36 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from django.core.exceptions import ValidationError
from django.test.utils import isolate_apps
from django.utils.translation import gettext as _

import pytest

Expand Down Expand Up @@ -53,3 +55,37 @@ def custom_oidc_db_prefix(cls):

# Prefix taken from `mozilla_django_oidc_dv/settings.py`
assert CustomConfig.get_cache_key() == "oidc:customconfig"


def test_validate_claim_mapping_fields():
instance = OpenIDConnectConfig(
claim_mapping={
"bad_field_no_cookie": ["har"],
}
)

with pytest.raises(ValidationError) as exc_context:
instance.clean()

err_dict = exc_context.value.message_dict
assert "claim_mapping" in err_dict
error = _("Field '{field}' does not exist on the user model").format(
field="bad_field_no_cookie"
)
assert error in err_dict["claim_mapping"]


def test_validate_username_field_not_in_claim_mapping():
instance = OpenIDConnectConfig(
claim_mapping={
"username": ["nope"],
}
)

with pytest.raises(ValidationError) as exc_context:
instance.clean()

err_dict = exc_context.value.message_dict
assert "claim_mapping" in err_dict
error = _("The username field may not be in the claim mapping")
assert error in err_dict["claim_mapping"]