askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
mail_accounts.py · 8.1 KB · 184 lines
| 1 | """Mail Accounts page -- the signed-in person's IMAP mailboxes, how each |
| 2 | one's sync is going, and whether its password is set. |
| 3 | |
| 4 | The password is the one field the generic form cannot show, because it is |
| 5 | not a field: it lives in the owner's write-only identity vault as |
| 6 | ``imap-<account id>`` (docs/secrets-and-credentials.md). So this page does |
| 7 | the one thing the generic renderer cannot: it asks the vault which services |
| 8 | are SET (never their values) and renders "set" / "not set", with an input |
| 9 | that PUTs straight to /identity/users/{you}/service-keys. The value goes |
| 10 | from the browser to the vault and never passes through a record, this |
| 11 | page's HTML, or a response. |
| 12 | |
| 13 | Saving a password also zeroes the account's sync_attempts, so an account |
| 14 | that was waiting after failed logins tries again on the next pass instead |
| 15 | of after its backoff -- the person who just fixed the password is the one |
| 16 | person certain the next try is worth making. |
| 17 | |
| 18 | Everything else (add, edit) is the generic form over mail_accounts, and the |
| 19 | page reads only rows whose owner_id is the signed-in user. |
| 20 | """ |
| 21 | |
| 22 | import html |
| 23 | import json |
| 24 | import os |
| 25 | |
| 26 | import object_feature_flags |
| 27 | import object_mail |
| 28 | import object_records |
| 29 | import object_service_keys |
| 30 | |
| 31 | _SCRIPT = """ |
| 32 | const panel = document.getElementById("accountpanel"); |
| 33 | function openForm(record) { |
| 34 | document.getElementById("paneltitle").textContent = record ? "Edit account" : "Add account"; |
| 35 | panel.style.display = "block"; |
| 36 | window.dbbasicForm("mail_accounts", { |
| 37 | mount: "#formmount", owner: OWNER_ID, record: record || undefined, |
| 38 | onSaved: () => { location.reload(); }, |
| 39 | onCancel: () => { panel.style.display = "none"; }, |
| 40 | }); |
| 41 | } |
| 42 | document.getElementById("addaccount").addEventListener("click", () => openForm(null)); |
| 43 | document.querySelectorAll("[data-edit]").forEach((btn) => btn.addEventListener("click", () => |
| 44 | openForm(ACCOUNTS.find((a) => a.id === btn.dataset.edit)))); |
| 45 | document.querySelectorAll("form[data-password]").forEach((form) => form.addEventListener("submit", async (e) => { |
| 46 | e.preventDefault(); |
| 47 | const id = form.dataset.password; |
| 48 | const input = form.querySelector("input[type=password]"); |
| 49 | const note = form.querySelector("[data-note]"); |
| 50 | if (!input.value) { note.textContent = "Type the password first."; return; } |
| 51 | const res = await fetch("/identity/users/" + encodeURIComponent(OWNER_ID) + "/service-keys", { |
| 52 | method: "PUT", credentials: "same-origin", |
| 53 | headers: {"content-type": "application/json", accept: "application/json"}, |
| 54 | body: JSON.stringify({service: "imap-" + id, key: input.value})}); |
| 55 | input.value = ""; |
| 56 | if (!res.ok) { note.textContent = "Not saved (" + res.status + ")."; return; } |
| 57 | await fetch("/collections/mail_accounts/records/" + encodeURIComponent(id), { |
| 58 | method: "PUT", credentials: "same-origin", |
| 59 | headers: {"content-type": "application/json", accept: "application/json"}, |
| 60 | body: JSON.stringify({sync_attempts: "0"})}); |
| 61 | note.textContent = "Saved. The next sync uses it."; |
| 62 | const state = form.closest(".account").querySelector("[data-pwstate]"); |
| 63 | if (state) state.textContent = "set"; |
| 64 | })); |
| 65 | """ |
| 66 | |
| 67 | |
| 68 | def _base_dir(): |
| 69 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 70 | |
| 71 | |
| 72 | def _text(value): |
| 73 | return str(value if value is not None else "").strip() |
| 74 | |
| 75 | |
| 76 | def _js(value): |
| 77 | """JSON for inside a <script> element: "</" escaped so no value can |
| 78 | close the element early.""" |
| 79 | return json.dumps(value).replace("</", "<\\/") |
| 80 | |
| 81 | |
| 82 | def _status(account): |
| 83 | """One honest sentence about where this account's sync stands.""" |
| 84 | if _text(account.get("enabled")).lower() in {"false", "0", "no", "off"}: |
| 85 | return "Not syncing: turned off for this account." |
| 86 | attempts = _text(account.get("sync_attempts")) or "0" |
| 87 | error = _text(account.get("sync_error")) |
| 88 | if error and attempts not in {"", "0"}: |
| 89 | return f"Failing ({attempts} tries in a row): {error}" |
| 90 | last = _text(account.get("last_synced_at")) |
| 91 | return f"Up to date as of {last}." if last else "Not synced yet." |
| 92 | |
| 93 | |
| 94 | def _card(account, password_set): |
| 95 | e = html.escape |
| 96 | account_id = e(account["id"]) |
| 97 | title = e(_text(account.get("label")) or _text(account.get("email_address"))) |
| 98 | detail = e(f"{_text(account.get('email_address'))} on {_text(account.get('host'))} " |
| 99 | f"({_text(account.get('security')) or 'ssl'})") |
| 100 | folders = e(_text(account.get("folders")) or "INBOX and Sent, found on the first sync") |
| 101 | return f""" |
| 102 | <div class="account card" style="margin-bottom:1rem"> |
| 103 | <div class="pagehead"><h2 style="font-size:1rem;margin:0">{title}</h2> |
| 104 | <button class="btn" data-edit="{account_id}">Edit</button></div> |
| 105 | <p class="hint">{detail}. Folders: {folders}.</p> |
| 106 | <p>{e(_status(account))}</p> |
| 107 | <form class="stack" data-password="{account_id}"> |
| 108 | <label>Password: <strong data-pwstate>{"set" if password_set else "not set"}</strong></label> |
| 109 | <input type="password" autocomplete="new-password" placeholder="{"Replace the password" if password_set else "The mailbox password"}"> |
| 110 | <div><button class="btn primary" type="submit">Save password</button> <span class="hint" data-note></span></div> |
| 111 | </form> |
| 112 | </div>""" |
| 113 | |
| 114 | |
| 115 | def GET(request): |
| 116 | identity = request.get("_identity", {}) or {} |
| 117 | user_id = identity.get("user_id") |
| 118 | if not user_id: |
| 119 | body = ('<p class="hint"><a href="/login?next=/mail/accounts">Sign in</a> ' |
| 120 | 'to manage your mail accounts.</p>') |
| 121 | script = "" |
| 122 | else: |
| 123 | base = _base_dir() |
| 124 | try: |
| 125 | rows = object_records.read_collection_records("mail_accounts", base_dir=base) |
| 126 | except (LookupError, OSError, ValueError): |
| 127 | rows = None |
| 128 | if rows is None: |
| 129 | body = '<p class="hint">Mail sync is not installed on this server.</p>' |
| 130 | script = "" |
| 131 | else: |
| 132 | accounts = [row for row in rows if _text(row.get("owner_id")) == str(user_id)] |
| 133 | try: |
| 134 | services = {entry["service"] for entry in |
| 135 | object_service_keys.list_service_key_status(str(user_id), base_dir=base)} |
| 136 | except (object_service_keys.InvalidServiceKeyError, OSError): |
| 137 | services = set() |
| 138 | off = object_feature_flags.refusal( |
| 139 | env_name=object_mail.ENABLE_ENV, flag=object_mail.KILL_SWITCH_FLAG, base_dir=base) |
| 140 | notice = (f'<p class="error">Mail sync is {html.escape(off)}. Accounts can be set up, ' |
| 141 | f'but nothing is copied until it is on.</p>') if off else "" |
| 142 | cards = "".join(_card(account, object_mail.password_service(account["id"]) in services) |
| 143 | for account in accounts) |
| 144 | body = f""" |
| 145 | <div class="breadcrumb"><a href="/">Home</a> / <a href="/inbox">Inbox</a> / Mail accounts</div> |
| 146 | <div class="pagehead"><h1>Mail accounts</h1><button class="btn primary" id="addaccount">+ Add account</button></div> |
| 147 | <p class="hint">New mail in these mailboxes is copied into your <a href="/inbox">inbox</a> every few |
| 148 | minutes. Nothing is sent, deleted or marked read on the mail server. Passwords are kept where no page or |
| 149 | record can read them back; this page only knows whether one is set.</p> |
| 150 | {notice} |
| 151 | <div id="accountpanel" style="display:none; margin-bottom:1rem"> |
| 152 | <h2 id="paneltitle" style="font-size:1rem; margin:0 0 0.5rem">Add account</h2> |
| 153 | <div id="formmount"></div> |
| 154 | </div> |
| 155 | {cards or '<p class="hint">No mail accounts yet.</p>'} |
| 156 | """ |
| 157 | # The rows hold no secret: the password is not a field. |
| 158 | script = ( |
| 159 | f"<script>const OWNER_ID = {_js(str(user_id))};" |
| 160 | f"const ACCOUNTS = {_js(accounts)};</script>" |
| 161 | '<script src="/form"></script>' |
| 162 | f"<script>{_SCRIPT}</script>" |
| 163 | ) |
| 164 | |
| 165 | who = (f"signed in as <strong>{html.escape(str(user_id))}</strong>" if user_id |
| 166 | else '<a href="/login?next=/mail/accounts">sign in</a>') |
| 167 | page = f"""<!doctype html> |
| 168 | <html lang="en"> |
| 169 | <head> |
| 170 | <meta charset="utf-8"> |
| 171 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 172 | <title>Mail accounts</title> |
| 173 | <link rel="stylesheet" href="/style"> |
| 174 | </head> |
| 175 | <body> |
| 176 | <div class="wrap"> |
| 177 | <header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header> |
| 178 | {body} |
| 179 | </div> |
| 180 | {script} |
| 181 | <script src="/nav"></script> |
| 182 | </body> |
| 183 | </html>""" |
| 184 | return {"content_type": "text/html; charset=utf-8", "body": page} |