Files
DentalManagement09/apps/SeleniumService/helpers_email_otp.py
T
GiteadandClaude Opus 5.5 f5b91a75d4 feat: MassHealth eligibility on new portal with persistent session and Gmail OTP auto-read
- New MH eligibility worker for providers.masshealth-dental.org (same DentaQuest
  portal as Tufts SCO): persistent Chrome profile, OTP via app popup, member
  details PDF, address, service history, plan name and remaining benefit
- Reads the OTP from the office Gmail over IMAP (App Password) and types it in;
  falls back to the manual OTP popup
- Insurance credentials: OTP Email / Phone and OTP Email Password fields
- New patient status ACTIVE_PLAN_NOT_ACCEPTED (coverage active, plan not accepted)
- Removes the old MH eligibility, MH history and CMSP remaining workers/processors;
  batch appointment check and AI conversation use the new MH processor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 16:47:22 -05:00

185 lines
6.4 KiB
Python

"""Read a one-time passcode from an email inbox over IMAP (Gmail by default).
Used when a portal sends its OTP to the email saved as "OTP Email / Phone" in
Settings -> Insurance Credentials. The "OTP Email Password" must be a Gmail
App Password (16 characters); a normal Gmail password is rejected over IMAP.
Read-only: messages are fetched with BODY.PEEK so they are not marked as read.
"""
import email
import email.message
import imaplib
import os
import re
import time
from email.header import decode_header, make_header
from html import unescape
from typing import Iterable, Optional
IMAP_HOST = os.getenv("OTP_IMAP_HOST", "imap.gmail.com")
IMAP_PORT = int(os.getenv("OTP_IMAP_PORT", "993"))
MAILBOXES = ("INBOX", "[Gmail]/Spam")
_KEYWORD_CODE = re.compile(
r"(?:code|passcode|pass code|otp|one[- ]time|verification|verify|pin)"
r"[^0-9]{0,60}?\b(\d{4,8})\b",
re.I,
)
_CODE_COLON = re.compile(
r"\b(?:code|passcode|otp)(?:\s+(?:instead|is))?\s*[:\-]?\s*(?:is\s+)?(\d{4,8})\b", re.I
)
_SIX_DIGITS = re.compile(r"(?<![\d$.,/-])\b(\d{6})\b(?![\d.,/-])")
# Codes already used this process, so a retry never re-types an old code
_used_codes: set = set()
def looks_like_email(value: Optional[str]) -> bool:
return bool(value) and "@" in value
def _decode(value) -> str:
try:
return str(make_header(decode_header(value or "")))
except Exception:
return value or ""
def _body_text(msg: email.message.Message) -> str:
plain, html = [], []
for part in msg.walk() if msg.is_multipart() else [msg]:
ctype = part.get_content_type()
if ctype not in ("text/plain", "text/html"):
continue
try:
payload = part.get_payload(decode=True) or b""
text = payload.decode(part.get_content_charset() or "utf-8", errors="replace")
except Exception:
continue
(plain if ctype == "text/plain" else html).append(text)
if plain:
return "\n".join(plain)
text = "\n".join(html)
text = re.sub(r"(?is)<(script|style).*?</\1>", " ", text)
text = re.sub(r"<[^>]+>", " ", text)
return unescape(text)
def extract_code(subject: str, body: str) -> Optional[str]:
# Most specific first: "Enter a code instead: 081914" / "code: 081914"
for text in (subject, body):
m = _CODE_COLON.search(text or "")
if m:
return m.group(1)
for text in (subject, body):
m = _KEYWORD_CODE.search(text or "")
if m:
return m.group(1)
for text in (subject, body):
m = _SIX_DIGITS.search(text or "")
if m:
return m.group(1)
return None
def _matches(sender: str, subject: str, body: str, keywords: Iterable[str]) -> bool:
haystack = f"{sender}\n{subject}\n{body}".lower()
return any(k.lower() in haystack for k in keywords)
def _search_mailbox(conn, mailbox: str, since_ts: float, keywords) -> Optional[str]:
typ, _ = conn.select(f'"{mailbox}"', readonly=True)
if typ != "OK":
return None
since = time.strftime("%d-%b-%Y", time.gmtime(since_ts - 86400))
typ, data = conn.uid("SEARCH", None, "SINCE", since)
if typ != "OK" or not data or not data[0]:
return None
uids = data[0].split()[-15:] # newest 15 is plenty
for uid in reversed(uids):
typ, msg_data = conn.uid("FETCH", uid, "(INTERNALDATE BODY.PEEK[])")
if typ != "OK" or not msg_data or not isinstance(msg_data[0], tuple):
continue
meta, raw = msg_data[0]
received = imaplib.Internaldate2tuple(meta)
if received and time.mktime(received) < since_ts:
continue # older than this login attempt
msg = email.message_from_bytes(raw)
sender = _decode(msg.get("From"))
subject = _decode(msg.get("Subject"))
body = _body_text(msg)
if not _matches(sender, subject, body, keywords):
continue
code = extract_code(subject, body)
if code and code not in _used_codes:
print(f"[email OTP] Found code in '{subject[:60]}' from {sender[:60]}")
return code
return None
def check_email_login(address: str, password: str) -> Optional[str]:
"""Return None when the login works, else an error message."""
try:
conn = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT, timeout=20)
conn.login(address.strip(), "".join((password or "").split()))
conn.logout()
return None
except Exception as e:
return f"{type(e).__name__}: {e}"
def fetch_otp_from_email(
address: str,
password: str,
since_ts: float,
keywords: Iterable[str],
timeout: int = 120,
poll_every: int = 5,
should_stop=None,
) -> Optional[str]:
"""Poll the inbox until an OTP email received after `since_ts` arrives.
Blocking; run it with asyncio.to_thread. Returns the code or None.
`should_stop` is an optional callable checked between polls.
"""
address = (address or "").strip()
password = "".join((password or "").split()) # app passwords are shown with spaces
if not looks_like_email(address) or not password:
return None
deadline = time.time() + timeout
conn = None
while time.time() < deadline:
if should_stop and should_stop():
break
try:
if conn is None:
conn = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT, timeout=20)
conn.login(address, password)
print(f"[email OTP] Logged in to {IMAP_HOST}, waiting for code...")
for mailbox in MAILBOXES:
try:
code = _search_mailbox(conn, mailbox, since_ts, keywords)
except imaplib.IMAP4.error:
code = None # e.g. Spam folder name differs
if code:
_used_codes.add(code)
return code
except imaplib.IMAP4.error as e:
print(f"[email OTP] IMAP login/search failed: {e}")
if "AUTHENTICATIONFAILED" in str(e).upper() or "credentials" in str(e).lower():
break # wrong address / app password; retrying won't help
conn = None
except Exception as e:
print(f"[email OTP] Error: {type(e).__name__}: {e}")
conn = None
time.sleep(poll_every)
try:
if conn is not None:
conn.logout()
except Exception:
pass
print("[email OTP] No code found")
return None