py3-validate-email/validate_email/domainlist_check.py

47 lines
1.4 KiB
Python
Raw Normal View History

2019-11-21 15:41:05 +01:00
from typing import Optional
from .exceptions import DomainBlacklistedError
2019-11-24 14:18:07 +01:00
from .updater import BLACKLIST_FILE_PATH, BlacklistUpdater
2019-11-21 15:41:05 +01:00
SetOrNone = Optional[set]
2019-11-24 14:18:07 +01:00
# Start an optional update on module load
blacklist_updater = BlacklistUpdater()
blacklist_updater.process(force=False)
2019-11-21 15:41:05 +01:00
class DomainListValidator(object):
'Check the provided email against domain lists.'
2019-11-24 16:25:08 +01:00
domain_whitelist = set()
domain_blacklist = set('localhost')
2019-11-21 15:41:05 +01:00
def __init__(
self, whitelist: SetOrNone = None, blacklist: SetOrNone = None):
if whitelist:
self.domain_whitelist = set(x.lower() for x in whitelist)
if blacklist:
self.domain_blacklist = set(x.lower() for x in blacklist)
else:
self._load_builtin_blacklist()
def _load_builtin_blacklist(self):
'Load our built-in blacklist.'
try:
2019-11-24 14:18:07 +01:00
with open(BLACKLIST_FILE_PATH) as fd:
2019-11-21 15:41:05 +01:00
lines = fd.readlines()
except FileNotFoundError:
return
2019-11-24 16:25:08 +01:00
self.domain_blacklist.update(
x.strip().lower() for x in lines if x.strip())
2019-11-21 15:41:05 +01:00
def __call__(self, user_part: str, domain_part: str) -> bool:
2019-11-21 15:41:05 +01:00
'Do the checking here.'
if domain_part in self.domain_whitelist:
return True
if domain_part in self.domain_blacklist:
raise DomainBlacklistedError
2019-11-21 15:41:05 +01:00
return True
domainlist_check = DomainListValidator()