import { buildAccountDataExport } from "./dataExport.js"; export async function handleAuthRoute (req, res, url, { auth, stateDb }) { try { if (url.pathname === "/auth/status" && req.method === "GET") { const status = await auth.statusFromRequest(req, res); sendJson(res, 200, status); return true; } if (url.pathname === "/auth/login" && req.method === "GET") { if (typeof auth.beginLogin !== "function") { sendText(res, 501, "OAuth login is not configured."); return true; } auth.beginLogin(req, res, url.searchParams.get("return_to") ?? "/"); return true; } if (url.pathname === "/auth/callback" && req.method === "GET") { if (typeof auth.finishLogin !== "function") { sendText(res, 501, "OAuth login is not configured."); return true; } await auth.finishLogin(req, res); return true; } if (url.pathname === "/auth/logout" && (req.method === "GET" || req.method === "POST")) { const returnTo = url.searchParams.get("return_to") ?? "/"; if (typeof auth.logout === "function") { await auth.logout(req, res, returnTo); } else { res.writeHead(302, { Location: returnTo }); res.end(); } return true; } if (url.pathname === "/auth/error" && req.method === "GET") { const message = url.searchParams.get("message") ?? "Sign-in failed."; res.writeHead(200, { "content-type": "text/html; charset=utf-8" }); res.end(`Sign-in failed` + `

Sign-in failed

${escapeHtml(message)}

` + `

Try again

`); return true; } if (url.pathname === "/settings/export" && req.method === "GET") { const identity = await auth.authenticateRequest(req); if (!identity) { sendJson(res, 401, { error: "Sign in required." }); return true; } const account = stateDb.getAccountBySubject(identity.authSubject); if (!account) { sendJson(res, 404, { error: "Account not found." }); return true; } const payload = buildAccountDataExport({ stateDb }, account); res.writeHead(200, { "content-type": "application/json; charset=utf-8", "content-disposition": 'attachment; filename="questward-data-export.json"' }); res.end(JSON.stringify(payload, null, 2)); return true; } return false; } catch (error) { sendJson(res, 500, { error: error.message ?? "Auth route failed." }); return true; } } export async function resolveAccount (stateDb, identity) { return stateDb.resolveAccountFromAuth({ authSubject: identity.authSubject, email: identity.email ?? null, username: identity.username ?? null }); } function sendJson (res, status, body) { res.writeHead(status, { "content-type": "application/json; charset=utf-8" }); res.end(JSON.stringify(body)); } function sendText (res, status, text) { res.writeHead(status, { "content-type": "text/plain; charset=utf-8" }); res.end(text); } function escapeHtml (text) { return String(text) .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll("\"", """); }