// Accounts: the header "Sign in / account" entry, the auth modal, and the shared
// helpers other modules (cache.js, mappicker.js, subscriptions.js, compare.js,
// digest.js) use to talk to backend — API calls and page/asset links to
// backend-owned paths (the interactive tool pages, /alerts, /digest, …) alike.
//
// Auth is an HttpOnly cookie; credentials: "include" (not "same-origin") so it
// still rides along when this script itself is loaded cross-origin (repo-split
// Stage 5 — a frontend SSR service on a different origin than backend, proven
// via a genuinely cross-origin LAN-dev run). Loaded on every page the way
// units.js is (imported by each page's entry module).
let currentUser = null; // {id, email, display_name} or null
let discordEnabled = false; // is Discord linking configured on the server?
let discordChecked = false; // have we asked yet? (once per page load)
const authCbs = []; // notified on login/logout so pages can re-gate
// backend's own origin+base (e.g. "https://thermograph.org/thermograph", or
// "http://192.168.1.5:8137/thermograph" when frontend and backend are on
// genuinely different origins) — derived from this module's own URL, since
// account.js (like every other frontend/*.js file) is always served BY
// backend, never by the frontend SSR service. Keeping the full origin (not
// just the path, as this used to) is what makes fetch()/href targets built
// from it resolve to backend even when this script was loaded from a page on
// a different origin (a frontend_ssr-rendered page in the cross-origin case).
export const APP_BASE = new URL(".", import.meta.url).href.replace(/\/$/, "");
export const u = (path) => `${APP_BASE}/${String(path).replace(/^\//, "")}`;
// Single pin point for the backend content/data API version every fetch below
// targets — was ~30 hardcoded "api/v2/..." literals spread across ~10 files
// with no one place to bump. Bump only in lockstep with a verified backend
// /api/version check: this frontend and its backend now deploy asynchronously
// (repo-split), so an unverified bump here would just turn every API call
// into a 404 the moment it ships ahead of a backend that doesn't speak it yet.
export const API_VERSION = "v2"; // bump only in lockstep with a verified backend /api/version check
// Turns a bare resource path ("grade", "users/me") — or one a caller already
// prefixed with a (possibly stale) version ("api/v2/place") — into a full
// request URL pinned to API_VERSION. Accepting the already-prefixed form too
// means a copy-pasted literal from an old call site normalizes instead of
// silently double-prefixing.
export const uv = (path) =>
u(`api/${API_VERSION}/${String(path).replace(/^\/?(api\/v\d+\/)?/, "")}`);
// --- shared fetch helper -----------------------------------------------------
// `url` must already be a full request URL — build it with uv() so every call
// is pinned to API_VERSION. Cookie sent, and a constant X-TG-Auth header the
// server can require as cheap CSRF defense (still meaningful cross-origin:
// forging it needs a preflight-clearing request we never grant, same as
// same-origin).
export async function apiFetch(url, { method = "GET", json, form } = {}) {
const opts = { method, credentials: "include", headers: { "X-TG-Auth": "1" } };
if (json !== undefined) {
opts.headers["Content-Type"] = "application/json";
opts.body = JSON.stringify(json);
} else if (form !== undefined) {
opts.headers["Content-Type"] = "application/x-www-form-urlencoded";
opts.body = new URLSearchParams(form).toString();
}
return fetch(url, opts);
}
// Parse a JSON response, throwing a friendly Error on failure. fastapi-users
// returns machine codes ("LOGIN_BAD_CREDENTIALS") or {detail:{reason}} for
// password rejects; map the common ones to human text.
async function readJson(res) {
let data = null;
try { data = await res.json(); } catch (e) { /* empty body (e.g. 204) */ }
if (!res.ok) {
const detail = data && data.detail;
let msg;
if (detail && typeof detail === "object" && detail.reason) msg = detail.reason;
else if (detail === "LOGIN_BAD_CREDENTIALS") msg = "Wrong email or password.";
else if (detail === "REGISTER_USER_ALREADY_EXISTS") msg = "That email is already registered.";
else if (detail === "VERIFY_USER_BAD_TOKEN") msg = "That verification link is invalid or expired.";
else if (detail === "VERIFY_USER_ALREADY_VERIFIED") msg = "This account is already verified.";
else if (typeof detail === "string") msg = detail.replace(/_/g, " ").toLowerCase();
else msg = `Request failed (${res.status}).`;
throw new Error(msg);
}
return data;
}
export function getUser() { return currentUser; }
export function onAuthChange(cb) { authCbs.push(cb); }
function emitAuth() { authCbs.forEach((cb) => { try { cb(currentUser); } catch (e) {} }); }
async function refreshUser() {
try {
const res = await apiFetch(uv("users/me"));
currentUser = res.ok ? await res.json() : null;
} catch (e) { currentUser = null; }
// Learn once whether Discord linking is configured, so the account menu only
// offers "Link Discord" when it will actually work (checked lazily, and only
// for a signed-in user — the menu never shows it to anyone else).
if (currentUser && !discordChecked) {
discordChecked = true;
try {
const r = await apiFetch(uv("discord/config"));
if (r.ok) discordEnabled = (await r.json()).enabled === true;
} catch (e) { /* leave it hidden */ }
}
return currentUser;
}
// --- auth calls --------------------------------------------------------------
async function login(email, password) {
// fastapi-users login is an OAuth2 form: username=email, password.
const res = await apiFetch(uv("auth/login"), { method: "POST", form: { username: email, password } });
await readJson(res); // throws on bad creds; 204 body is empty
}
async function register(email, password) {
const res = await apiFetch(uv("auth/register"), { method: "POST", json: { email, password } });
await readJson(res);
}
async function verifyEmail(token) {
const res = await apiFetch(uv("auth/verify"), { method: "POST", json: { token } });
await readJson(res);
}
export async function logout() {
try { await apiFetch(uv("auth/logout"), { method: "POST" }); } catch (e) {}
currentUser = null;
renderHeader();
emitAuth();
}
// --- auth modal --------------------------------------------------------------
let modal = null, mode = "login";
function buildModal() {
modal = document.createElement("div");
modal.className = "mp-overlay acct-overlay";
modal.hidden = true;
modal.innerHTML = `
Sign in
`;
document.body.appendChild(modal);
modal.querySelector(".mp-close").onclick = closeAuth;
modal.addEventListener("pointerdown", (e) => { if (e.target === modal) closeAuth(); });
document.addEventListener("keydown", (e) => { if (!modal.hidden && e.key === "Escape") closeAuth(); });
const form = modal.querySelector(".acct-form");
form.addEventListener("submit", onSubmit);
modal.querySelector(".acct-switch").addEventListener("click", (e) => {
const b = e.target.closest("button");
if (b) setMode(mode === "login" ? "register" : "login");
});
setMode("login");
}
function setMode(m) {
mode = m;
const isLogin = m === "login";
modal.querySelector(".acct-title").textContent = isLogin ? "Sign in" : "Create account";
modal.querySelector(".acct-submit").textContent = isLogin ? "Sign in" : "Create account";
modal.querySelector('input[name="password"]').setAttribute(
"autocomplete", isLogin ? "current-password" : "new-password");
modal.querySelector(".acct-switch").innerHTML = isLogin
? 'Need an account? '
: 'Already have an account? ';
showError("");
}
function showError(msg) {
const el = modal.querySelector(".acct-error");
el.textContent = msg || "";
el.hidden = !msg;
}
async function onSubmit(e) {
e.preventDefault();
const email = modal.querySelector('input[name="email"]').value.trim();
const password = modal.querySelector('input[name="password"]').value;
const btn = modal.querySelector(".acct-submit");
btn.disabled = true;
showError("");
try {
if (mode === "register") { await register(email, password); }
await login(email, password); // register flow signs in right after
await refreshUser();
closeAuth();
renderHeader();
emitAuth();
} catch (err) {
showError(err.message || "Something went wrong.");
} finally {
btn.disabled = false;
}
}
export function openAuth(startMode = "login") {
if (!modal) buildModal();
setMode(startMode);
modal.querySelector('input[name="email"]').value = "";
modal.querySelector('input[name="password"]').value = "";
modal.hidden = false;
modal.querySelector('input[name="email"]').focus();
}
function closeAuth() { if (modal) modal.hidden = true; }
// --- notifications (header bell) ---------------------------------------------
const BELL_IC = ``;
let notifications = [];
let unreadCount = 0;
let notifTimer = null;
function timeAgo(sec) {
const d = Date.now() / 1000 - sec;
if (d < 60) return "just now";
if (d < 3600) return `${Math.floor(d / 60)}m ago`;
if (d < 86400) return `${Math.floor(d / 3600)}h ago`;
return `${Math.floor(d / 86400)}d ago`;
}
async function loadNotifications() {
try {
const res = await apiFetch(uv("notifications?limit=50"));
if (!res.ok) return;
const data = await res.json();
notifications = data.notifications || [];
unreadCount = data.unread_count || 0;
paintBadge();
paintNotifList();
} catch (e) { /* offline — leave prior state */ }
}
function paintBadge() {
if (!acctEl) return;
const badge = acctEl.querySelector(".notif-badge");
if (!badge) return;
badge.textContent = unreadCount > 99 ? "99+" : String(unreadCount);
badge.hidden = unreadCount === 0;
}
function paintNotifList() {
if (!acctEl) return;
const list = acctEl.querySelector(".notif-list");
if (!list) return;
if (!notifications.length) {
list.innerHTML = `
No alerts yet. Weather notifications will show up here.