feat(email): each account gets its own email, in its own zone (milestone 495)
Milestone 495 "Email goes to each account, in its own time zone", on the operator's ruling (System 156): notifications go to each user, times in their zone, defaults on, toggled per user or per role. - users.notify_alerts / notify_report (migration 0036): None follows the role's default, notify.<kind>.<role> in settings, all on to start. - mail.pick_recipients: active accounts that want the email and have an address mail can reach (an SSO placeholder like name@oidc is skipped and flagged), each in its own zone with no UTC beside it, then the Also send to addresses in their chosen zone with UTC beside. One copy per address, all over one SMTP connection. - Alerts, the weekly report and the test email (to you, in your zone, plus the typed addresses) send that way. The save-time smtp.tz capture is gone. - Notifications: a role × email table of defaults, who each email reaches and who can't be reached, and Also send to with its own zone, which starts as the first admin's to open the page. - Account page: your address and your two switches. Users: an Emailed column, and an admin sets an account's switches on its page. - The Alerts page counts the accounts it emails. zone_select macro and formatting.zones_by_region shared by Account and Notifications. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+42
-13
@@ -216,18 +216,31 @@ async def save_thresholds():
|
||||
@settings_bp.get("/notifications/")
|
||||
@require_role(UserRole.admin)
|
||||
async def notifications():
|
||||
from steward.core.formatting import zones_by_region
|
||||
from steward.core.mail import audience
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
settings = await get_all_settings(db)
|
||||
if not settings["smtp.tz"] and session.get("tz"):
|
||||
# "Also send to" reads times in the first admin's zone until one is chosen.
|
||||
async with db.begin():
|
||||
await set_setting(db, "smtp.tz", session["tz"])
|
||||
settings["smtp.tz"] = session["tz"]
|
||||
await _reload_app_config()
|
||||
who = await audience(db)
|
||||
from urllib.parse import urlsplit
|
||||
webhook_host = urlsplit(settings.get("webhook.url") or "").hostname or ""
|
||||
return await render_template("settings/notifications.html", settings=settings,
|
||||
webhook_host=webhook_host)
|
||||
webhook_host=webhook_host, audience=who,
|
||||
roles=list(UserRole), zones=zones_by_region())
|
||||
|
||||
|
||||
@settings_bp.post("/notifications/")
|
||||
@require_role(UserRole.admin)
|
||||
async def save_notifications():
|
||||
from steward.core.formatting import zone_names
|
||||
from steward.core.mail import KINDS
|
||||
form = await request.form
|
||||
extra_tz = form.get("smtp.tz", "")
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
async with db.begin():
|
||||
recipients_raw = form.get("smtp.recipients", "")
|
||||
@@ -240,7 +253,12 @@ async def save_notifications():
|
||||
await set_setting(db, "smtp.password", form.get("smtp.password"))
|
||||
await set_setting(db, "smtp.recipients", recipients)
|
||||
await set_setting(db, "smtp.from", form.get("smtp.from", "").strip())
|
||||
await set_setting(db, "smtp.tz", session.get("tz") or "")
|
||||
if extra_tz in zone_names():
|
||||
await set_setting(db, "smtp.tz", extra_tz)
|
||||
for kind in KINDS:
|
||||
for role in UserRole:
|
||||
key = f"notify.{kind}.{role.value}"
|
||||
await set_setting(db, key, key in form)
|
||||
if "webhook.remove" in form:
|
||||
await set_setting(db, "webhook.url", "")
|
||||
elif form.get("webhook.url", "").strip():
|
||||
@@ -295,31 +313,42 @@ async def test_webhook():
|
||||
@settings_bp.post("/notifications/test-email")
|
||||
@require_role(UserRole.admin)
|
||||
async def test_email():
|
||||
"""Send a sample alert email using the SMTP settings in the form (unsaved);
|
||||
a blank password uses the saved one."""
|
||||
from steward.core.mail import alert_email
|
||||
"""Send a sample alert email using the SMTP settings in the form (unsaved):
|
||||
to you, in your zone, and to the Also send to addresses in the form, in
|
||||
the zone chosen for them. A blank password uses the saved one."""
|
||||
from steward.core.formatting import zone
|
||||
from steward.core.mail import Recipient, alert_email, is_real_address, pick_recipients
|
||||
from steward.core.notifications import _send_email, smtp_mode
|
||||
from steward.models.users import User
|
||||
form = await request.form
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
saved = to_smtp_cfg(await get_all_settings(db))
|
||||
me = await db.get(User, session.get("user_id"))
|
||||
try:
|
||||
port = int(form.get("smtp.port") or 587)
|
||||
except ValueError:
|
||||
return await _notify_test_result("email", False, "The port must be a number.")
|
||||
extra = [r.strip() for r in form.get("smtp.recipients", "").split(",") if r.strip()]
|
||||
cfg = {"host": (form.get("smtp.host") or "").strip(), "port": port,
|
||||
"tls": "smtp.tls" in form, "username": form.get("smtp.username", ""),
|
||||
"password": form.get("smtp.password") or saved["password"],
|
||||
"from": (form.get("smtp.from") or "").strip(),
|
||||
"tz": session.get("tz") or "", "base_url": saved["base_url"],
|
||||
"recipients": [r.strip() for r in form.get("smtp.recipients", "").split(",") if r.strip()]}
|
||||
if not cfg["host"] or not cfg["recipients"]:
|
||||
return await _notify_test_result("email", False, "Enter an SMTP host and at least one recipient.")
|
||||
"from": (form.get("smtp.from") or "").strip(), "base_url": saved["base_url"]}
|
||||
to = ([Recipient(me.email.strip(), zone(me.time_zone), False, me.username)]
|
||||
if me is not None and is_real_address(me.email) else [])
|
||||
to += [r for r in pick_recipients([], "alerts", {}, extra, form.get("smtp.tz") or saved["tz"])
|
||||
if r.address.lower() not in {t.address.lower() for t in to}]
|
||||
if not cfg["host"]:
|
||||
return await _notify_test_result("email", False, "Enter an SMTP host.")
|
||||
if not to:
|
||||
return await _notify_test_result(
|
||||
"email", False, "Your account has no email address mail can reach, and no Also send to "
|
||||
"addresses are entered. Set your address on the Account page.")
|
||||
alert = _sample_alert()
|
||||
sent = await _send_email(cfg, alert)
|
||||
sent = await _send_email(cfg, alert, to)
|
||||
how = {"ssl": "implicit TLS", "starttls": "STARTTLS", "plain": "no TLS"}[smtp_mode(port, cfg["tls"])]
|
||||
result = (f"Sent to {', '.join(cfg['recipients'])} via {cfg['host']}:{port} ({how})."
|
||||
result = (f"Sent to {', '.join(r.address for r in to)} via {cfg['host']}:{port} ({how})."
|
||||
if sent["sent"] else f"{cfg['host']}:{port} ({how}): {sent['error']}")
|
||||
return await _notify_test_result("email", sent["sent"], result, alert_email(cfg, alert)[1])
|
||||
return await _notify_test_result("email", sent["sent"], result, alert_email(cfg, alert, to[0])[1])
|
||||
|
||||
|
||||
# ── Ansible Sources ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -16,7 +16,9 @@ from sqlalchemy import func, or_, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from steward.auth.middleware import require_role
|
||||
from steward.core import mail
|
||||
from steward.core.audit import audit_request
|
||||
from steward.core.settings import get_all_settings
|
||||
from steward.models.alerts import AlertRule, MaintenanceWindow
|
||||
from steward.models.ansible import AnsibleRun
|
||||
from steward.models.api_tokens import ApiToken
|
||||
@@ -102,9 +104,13 @@ async def users_list():
|
||||
users = (await db.execute(select(User))).scalars().all()
|
||||
last = await _last_sign_ins(db)
|
||||
tokens = await _token_counts(db)
|
||||
settings = await get_all_settings(db)
|
||||
users = sorted(users, key=lambda u: (not u.is_active, u.username.lower()))
|
||||
gets = {u.id: [label for kind, label in (("alerts", "alerts"), ("report", "report"))
|
||||
if u.is_active and mail.wants(u, kind, settings)] for u in users}
|
||||
return await render_template(
|
||||
"settings/users.html", users=users, last=last, tokens=tokens, sources=SOURCES,
|
||||
gets=gets, reachable={u.id for u in users if mail.is_real_address(u.email)},
|
||||
admins=sum(1 for u in users if u.role == UserRole.admin and u.is_active),
|
||||
disabled=sum(1 for u in users if not u.is_active))
|
||||
|
||||
@@ -150,6 +156,7 @@ async def user_create():
|
||||
|
||||
|
||||
_DONE = {"created": "Account added.", "saved": "Saved.", "role": "Role changed.",
|
||||
"email": "Email settings saved.",
|
||||
"password": "Password set. It works from their next sign-in.",
|
||||
"disabled": "Account disabled. They are signed out at their next click.",
|
||||
"enabled": "Account enabled."}
|
||||
@@ -162,9 +169,11 @@ async def _user_page(user_id: str, error: str | None = None, status: int = 200):
|
||||
last = (await _last_sign_ins(db)).get(user.id)
|
||||
tokens = (await _token_counts(db)).get(user.id, 0)
|
||||
holds = await held_by(db, user.id)
|
||||
defaults = mail.role_defaults(user, await get_all_settings(db))
|
||||
me = session.get("user_id")
|
||||
return await render_template(
|
||||
"settings/user.html", user=user, last_sign_in=last, tokens=tokens, holds=holds,
|
||||
defaults=defaults, reachable=mail.is_real_address(user.email),
|
||||
source=SOURCES.get(user.auth_source, user.auth_source), roles=list(UserRole),
|
||||
min_password=MIN_PASSWORD, error=error, done=_DONE.get(request.args.get("done", "")),
|
||||
demote_refused=refusal("demote", user, me, admins),
|
||||
@@ -231,6 +240,23 @@ async def user_role(user_id: str):
|
||||
return redirect(f"/settings/users/{user_id}?done=role")
|
||||
|
||||
|
||||
@users_bp.post("/<user_id>/email")
|
||||
@require_role(UserRole.admin)
|
||||
async def user_email(user_id: str):
|
||||
"""Whether this account is emailed alerts and the weekly report (milestone
|
||||
495); its address is edited with its name."""
|
||||
form = {k: v for k, v in (await request.form).items() if k != "email"}
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
async with db.begin():
|
||||
user = await _target(db, user_id)
|
||||
changes, error = mail.apply_email_form(user, form)
|
||||
if error:
|
||||
return await _user_page(user_id, error, 400)
|
||||
if changes:
|
||||
await audit_request("user.email_settings", "user", user_id, {"username": user.username} | changes)
|
||||
return redirect(f"/settings/users/{user_id}?done=email")
|
||||
|
||||
|
||||
@users_bp.post("/<user_id>/password")
|
||||
@require_role(UserRole.admin)
|
||||
async def user_password(user_id: str):
|
||||
|
||||
Reference in New Issue
Block a user