mirror of
https://github.com/GSA/notifications-admin.git
synced 2026-07-29 20:48:30 -04:00
Simplifying code for checking email domains
Since this code isn’t trying to inherit from the code that also looked
up domain names in `domains.yml` it can go back to being a lot simpler.
This code is thoroughly tested already here:
a249382e69/tests/app/main/test_validators.py (L74-L155)
This commit is contained in:
56
app/utils.py
56
app/utils.py
@@ -36,6 +36,11 @@ FAILURE_STATUSES = ['failed', 'temporary-failure', 'permanent-failure',
|
||||
'technical-failure', 'virus-scan-failed', 'validation-failed']
|
||||
REQUESTED_STATUSES = SENDING_STATUSES + DELIVERED_STATUSES + FAILURE_STATUSES
|
||||
|
||||
with open('{}/email_domains.yml'.format(
|
||||
os.path.dirname(os.path.realpath(__file__))
|
||||
)) as email_domains:
|
||||
GOVERNMENT_EMAIL_DOMAIN_NAMES = yaml.safe_load(email_domains)
|
||||
|
||||
|
||||
def user_has_permissions(*permissions, **permission_kwargs):
|
||||
def wrap(func):
|
||||
@@ -280,11 +285,13 @@ def get_help_argument():
|
||||
|
||||
|
||||
def is_gov_user(email_address):
|
||||
try:
|
||||
GovernmentEmailDomain(email_address)
|
||||
return True
|
||||
except NotGovernmentEmailDomain:
|
||||
return False
|
||||
return any(
|
||||
email_address.lower().endswith((
|
||||
"@{}".format(known),
|
||||
".{}".format(known),
|
||||
))
|
||||
for known in GOVERNMENT_EMAIL_DOMAIN_NAMES
|
||||
)
|
||||
|
||||
|
||||
def get_template(
|
||||
@@ -398,45 +405,6 @@ def set_status_filters(filter_args):
|
||||
)))
|
||||
|
||||
|
||||
_dir_path = os.path.dirname(os.path.realpath(__file__))
|
||||
|
||||
|
||||
class NotGovernmentEmailDomain(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class GovernmentEmailDomain():
|
||||
|
||||
with open('{}/email_domains.yml'.format(_dir_path)) as email_domains:
|
||||
domain_names = yaml.safe_load(email_domains)
|
||||
|
||||
def __init__(self, email_address_or_domain):
|
||||
try:
|
||||
self._match = next(filter(
|
||||
self.get_matching_function(email_address_or_domain),
|
||||
self.domain_names,
|
||||
))
|
||||
except StopIteration:
|
||||
raise NotGovernmentEmailDomain()
|
||||
|
||||
@staticmethod
|
||||
def get_matching_function(email_address_or_domain):
|
||||
|
||||
email_address_or_domain = email_address_or_domain.lower()
|
||||
|
||||
def fn(domain):
|
||||
|
||||
return (
|
||||
email_address_or_domain == domain
|
||||
) or (
|
||||
email_address_or_domain.endswith("@{}".format(domain))
|
||||
) or (
|
||||
email_address_or_domain.endswith(".{}".format(domain))
|
||||
)
|
||||
|
||||
return fn
|
||||
|
||||
|
||||
def unicode_truncate(s, length):
|
||||
encoded = s.encode('utf-8')[:length]
|
||||
return encoded.decode('utf-8', 'ignore')
|
||||
|
||||
Reference in New Issue
Block a user