Files
dtf-system/app/mail.py
Cauê Faleiros 95be624cca
All checks were successful
Build and deploy / Validate source (push) Successful in 17s
Build and deploy / Integration suite on a real stack (push) Successful in 4m25s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m22s
feat: a new account is confirmed with a code sent to its e-mail
Anyone could open an account on someone else's e-mail. Now "Criar conta"
e-mails a 6-digit code, and the account exists only once it is entered: one
big field that takes a paste or the phone's autofill and confirms by itself,
"Reenviar código" after 60 s, "Trocar e-mail", and the sign-in box hidden
meanwhile.

Security: 15 minutes per code, 5 wrong attempts, at most 5 codes, limits per
address and per source; the password is hashed at the first step and the code
stored only as a hash, its e-mail erased once sent. An address that already
has an account gets the same answer on screen and a "você já tem conta"
e-mail instead of a code, so the form does not reveal who is registered.
Without e-mail (MAIL_ADAPTER=off) the account is created at once, as before.

The browser test reads the code from a local-only endpoint that exists only
where e-mail stays in the log. Tested: mail_test (wrong, locked, resent,
expired codes, existing address, erasure after SMTP), the full suite and the
browser test in a CI-style stack, and the screens in Brave on desktop and phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:18:37 -03:00

175 lines
7.7 KiB
Python

"""E-mail: password recovery for customers and alerts for the team.
Messages are queued in the database inside the transaction that caused them
(an order paid, a quote waiting for review) and sent by the worker, so a slow
or unreachable mail server never holds up a request and a failed send is
retried. MAIL_ADAPTER chooses where they go:
off nothing is queued and recovery offers WhatsApp instead (the default,
until the client's SMTP details arrive);
log kept in the database and written to the worker's log, for the local
stack, where there is no mail server;
smtp sent through SMTP_HOST as MAIL_FROM.
A recovery link or a signup code lets someone in, so its text is erased once
it is sent (or once it expired unsent); only its subject stays as a record.
"""
import logging
import os
import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr, make_msgid, parseaddr
ADAPTER = os.environ.get('MAIL_ADAPTER', 'off')
# Every Kanban link in an alert points here.
KANBAN_ORIGIN = os.environ.get('KANBAN_ORIGIN', '').rstrip('/')
RESET_MINUTES = 60
CODE_MINUTES = 15
# Messages that let someone in: their text is erased once sent, or once they
# expired unsent (minutes).
SECRET_KINDS = {'reset': RESET_MINUTES, 'code': CODE_MINUTES}
MAX_ATTEMPTS = 12
log = logging.getLogger('dtf.mail')
def configured():
return ADAPTER in ('log', 'smtp')
def required_settings():
return ('SMTP_HOST', 'MAIL_FROM')
def queue(c, kind, to, subject, body):
"""Queue one message in the caller's transaction. Returns False when e-mail
is off, so the caller can say so instead of promising a message."""
if not configured():
return False
c.execute('INSERT INTO dtf_local.mail_queue(kind,to_addr,subject,body) VALUES(%s,%s,%s,%s)',
(kind, to, subject, body))
return True
def alert(c, subject, lines, link=''):
"""The same message to every active Kanban user who asked for alerts."""
if not configured():
return
body = '\n'.join(lines)
if link and KANBAN_ORIGIN:
body += f'\n\nAbrir no Kanban: {KANBAN_ORIGIN}{link}'
body += '\n\nVocê recebe este e-mail porque os alertas estão ligados no seu usuário do Kanban (Usuários → Editar).'
for row in c.execute('SELECT email FROM dtf_local.operators WHERE active AND alerts').fetchall():
queue(c, 'alert', row['email'], subject, body)
PRODUCTS = {'file': 'DTF Têxtil · folha montada', 'avulsa': 'DTF Têxtil · artes avulsas',
'uvfile': 'DTF UV · folha montada', 'uv': 'DTF UV · artes avulsas'}
def money(cents):
whole, cents = divmod(int(cents), 100)
return 'R$ ' + f'{whole:,}'.replace(',', '.') + f',{cents:02d}'
def summary(order):
"""The lines an alert shows about a cart or an order: who, what, delivery."""
customer = order.get('customer') or {}
cnpj = ''.join(ch for ch in str(customer.get('cnpj', '')) if ch.isdigit())
if len(cnpj) == 14:
cnpj = f'{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/{cnpj[8:12]}-{cnpj[12:]}'
lines = [f"Cliente: {cnpj} · {customer.get('mail', '')}"]
for item in order.get('items', []):
metres = item.get('billed_metres') or item.get('metres')
lines.append(f"{PRODUCTS.get(item.get('mode'), item.get('mode'))} · {str(metres).replace('.', ',')} m")
freight = order.get('freight') or {}
lines.append('Entrega: ' + ('retirada' if freight.get('service') == 'pickup' else 'frete'))
return lines
def message(to, subject, body):
sender = os.environ.get('MAIL_FROM', 'DTF Dropstar <nao-responda@localhost>')
name, address = parseaddr(sender)
msg = EmailMessage()
msg['From'] = formataddr((name or 'DTF Dropstar', address))
msg['To'] = to
msg['Subject'] = subject
msg['Message-ID'] = make_msgid(domain=address.split('@')[-1] or None)
reply = os.environ.get('MAIL_REPLY_TO', '')
if reply:
msg['Reply-To'] = reply
msg.set_content(body)
return msg
def send_smtp(msg):
host = os.environ['SMTP_HOST']
security = os.environ.get('SMTP_SECURITY', 'starttls')
port = int(os.environ.get('SMTP_PORT') or (465 if security == 'ssl' else 587))
user, password = os.environ.get('SMTP_USER', ''), os.environ.get('SMTP_PASSWORD', '')
context = ssl.create_default_context()
if security == 'ssl':
server = smtplib.SMTP_SSL(host, port, timeout=20, context=context)
else:
server = smtplib.SMTP(host, port, timeout=20)
with server:
if security == 'starttls':
server.starttls(context=context)
if user:
server.login(user, password)
server.send_message(msg)
def deliver(row):
msg = message(row['to_addr'], row['subject'], row['body'])
if ADAPTER == 'smtp':
send_smtp(msg)
else:
log.warning('mail (%s) to %s: %s', ADAPTER, row['to_addr'], row['subject'])
def send_pending(connect, limit=5, ids=None):
"""Send what is due, a few at a time. Called by the worker every second;
`ids` sends just those messages, due or not (the tests use it)."""
if not configured():
return
with connect() as c:
# A link or a code that expired before it could be sent is useless.
for kind, minutes in SECRET_KINDS.items():
c.execute("""UPDATE dtf_local.mail_queue SET body='', last_error='expirou sem ser enviado', failed_at=now()
WHERE kind=%s AND sent_at IS NULL AND failed_at IS NULL
AND created_at < now() - %s * interval '1 minute'""", (kind, minutes))
rows = c.execute('''SELECT * FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL
AND (id = ANY(%s) OR (%s::bigint[] IS NULL AND available_at <= now()))
ORDER BY id FOR UPDATE SKIP LOCKED LIMIT %s''', (ids or [], ids, limit)).fetchall()
for row in rows:
try:
deliver(row)
except Exception as exc:
attempts = row['attempts'] + 1
gave_up = attempts >= MAX_ATTEMPTS
c.execute('''UPDATE dtf_local.mail_queue SET attempts=%s, last_error=%s,
available_at=now() + %s * interval '1 second',
failed_at=CASE WHEN %s THEN now() END WHERE id=%s''',
(attempts, str(exc)[:500], min(3600, 2 ** min(attempts + 3, 12)), gave_up, row['id']))
log.warning('mail to %s failed (attempt %s): %s', row['to_addr'], attempts, exc)
continue
# The local log keeps the text so the link can be followed by hand.
erase = row['kind'] in SECRET_KINDS and ADAPTER != 'log'
c.execute('''UPDATE dtf_local.mail_queue SET sent_at=now(), attempts=attempts+1, last_error=NULL,
body=CASE WHEN %s THEN '' ELSE body END WHERE id=%s''', (erase, row['id']))
def status(c):
"""What the Kanban's Integrações shows about e-mail."""
last = c.execute('SELECT max(sent_at) AS at FROM dtf_local.mail_queue').fetchone()['at']
failing = c.execute('''SELECT to_addr, last_error, created_at FROM dtf_local.mail_queue
WHERE sent_at IS NULL AND last_error IS NOT NULL ORDER BY id DESC LIMIT 1''').fetchone()
pending = c.execute('SELECT count(*) AS n FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL').fetchone()['n']
alerts = c.execute('SELECT count(*) AS n FROM dtf_local.operators WHERE active AND alerts').fetchone()['n']
return {'adapter': ADAPTER, 'from': os.environ.get('MAIL_FROM', '') if configured() else '',
'host': os.environ.get('SMTP_HOST', '') if ADAPTER == 'smtp' else '',
'last_sent': last, 'pending': pending, 'alerts': alerts,
'error': {'to': failing['to_addr'], 'error': failing['last_error'], 'at': failing['created_at']} if failing else None}