From 6e8ce786030f0bcea42ad8af7718551b6776b100 Mon Sep 17 00:00:00 2001 From: Chris Hill-Scott Date: Thu, 7 Mar 2019 11:23:42 +0000 Subject: [PATCH] Choose most specific domains first MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If we had organisations for GDS and Cabinet Office, then we’d always want someone whose email address ends in `@cabinet-office.gov.uk` to match to `cabinet-office.gov.uk` before matching to `digital.cabinet-office.gov.uk`. Sorting the list by shortest first addresses this. --- app/dao/organisation_dao.py | 5 ++++- tests/app/service/test_rest.py | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/app/dao/organisation_dao.py b/app/dao/organisation_dao.py index eca2787b4..bdd430c8c 100644 --- a/app/dao/organisation_dao.py +++ b/app/dao/organisation_dao.py @@ -1,3 +1,5 @@ +from sqlalchemy.sql.expression import func + from app import db from app.dao.dao_utils import transactional from app.models import ( @@ -28,7 +30,8 @@ def dao_get_organisation_by_email_address(email_address): email_address = email_address.lower() - for domain in Domain().query.all(): + for domain in Domain.query.order_by(func.char_length(Domain.domain).desc()).all(): + if ( email_address.endswith("@{}".format(domain.domain)) or email_address.endswith(".{}".format(domain.domain)) diff --git a/tests/app/service/test_rest.py b/tests/app/service/test_rest.py index e216f8801..744f509e9 100644 --- a/tests/app/service/test_rest.py +++ b/tests/app/service/test_rest.py @@ -271,6 +271,10 @@ def test_create_service_with_domain_sets_organisation( expected_org, ): + red_herring_org = create_organisation(name='Sub example') + create_domain('specific.example.gov.uk', red_herring_org.id) + create_domain('aaaaaaaa.example.gov.uk', red_herring_org.id) + org = create_organisation() create_domain('example.gov.uk', org.id) create_domain('test.gov.uk', org.id)