47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
|
|
"""
|
||
|
|
Contact-detail masking.
|
||
|
|
|
||
|
|
The dataset contains real personal data (e-mail addresses, mobile numbers,
|
||
|
|
street addresses). Exposing it to every authenticated user would be both a
|
||
|
|
privacy and a compliance problem, so contact details are masked unless the
|
||
|
|
caller holds a role that is explicitly allowed to see them
|
||
|
|
(:pyattr:`apps.accounts.models.User.can_view_pii`).
|
||
|
|
|
||
|
|
Masking happens in the serialisation layer - the raw values never leave the
|
||
|
|
database for an unprivileged caller, and the search index stores them in a
|
||
|
|
non-searchable field so a keyword query can never be used to confirm an e-mail
|
||
|
|
address by brute force.
|
||
|
|
"""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import re
|
||
|
|
|
||
|
|
_EMAIL_RE = re.compile(r"^([^@]+)@(.+)$")
|
||
|
|
|
||
|
|
|
||
|
|
def mask_email(address: str) -> str:
|
||
|
|
"""``joseph.holland@garver.com`` -> ``jo************@garver.com``."""
|
||
|
|
match = _EMAIL_RE.match(address or "")
|
||
|
|
if not match:
|
||
|
|
return "***"
|
||
|
|
local, domain = match.groups()
|
||
|
|
keep = min(2, max(len(local) - 1, 0))
|
||
|
|
return f"{local[:keep]}{'*' * max(len(local) - keep, 1)}@{domain}"
|
||
|
|
|
||
|
|
|
||
|
|
def mask_phone(number: str) -> str:
|
||
|
|
"""``+19402058928`` -> ``+1940*****28``."""
|
||
|
|
digits = (number or "").strip()
|
||
|
|
if len(digits) < 6:
|
||
|
|
return "***"
|
||
|
|
return f"{digits[:5]}{'*' * (len(digits) - 7)}{digits[-2:]}"
|
||
|
|
|
||
|
|
|
||
|
|
def mask_emails(emails: list[dict[str, str]]) -> list[dict[str, str]]:
|
||
|
|
return [{**item, "address": mask_email(item.get("address", ""))} for item in emails or []]
|
||
|
|
|
||
|
|
|
||
|
|
def mask_phones(numbers: list[str]) -> list[str]:
|
||
|
|
return [mask_phone(number) for number in numbers or []]
|