passkey-login.js
| 1 | import { startAuthentication } from "/assets/simplewebauthn-browser.js"; |
| 2 | |
| 3 | const section = document.getElementById("passkey-section"); |
| 4 | const btn = document.getElementById("passkey-btn"); |
| 5 | const errEl = document.getElementById("passkey-error"); |
| 6 | |
| 7 | if (section) section.style.display = "block"; |
| 8 | |
| 9 | function showError(msg) { |
| 10 | if (!errEl) return; |
| 11 | errEl.textContent = msg; |
| 12 | errEl.className = msg ? "form-error" : ""; |
| 13 | errEl.style.display = msg ? "" : "none"; |
| 14 | } |
| 15 | |
| 16 | if (btn) { |
| 17 | const originalText = btn.textContent; |
| 18 | btn.addEventListener("click", async () => { |
| 19 | btn.disabled = true; |
| 20 | btn.textContent = "Waiting for authenticator…"; |
| 21 | showError(""); |
| 22 | try { |
| 23 | const optsResp = await fetch("/auth/passkey/login/options", { |
| 24 | method: "POST", |
| 25 | }); |
| 26 | if (!optsResp.ok) throw new Error("Failed to get options"); |
| 27 | const opts = await optsResp.json(); |
| 28 | const result = await startAuthentication({ optionsJSON: opts }); |
| 29 | const verResp = await fetch("/auth/passkey/login/verify", { |
| 30 | method: "POST", |
| 31 | headers: { "Content-Type": "application/json" }, |
| 32 | body: JSON.stringify(result), |
| 33 | }); |
| 34 | if (verResp.ok) { |
| 35 | window.location.href = "/"; |
| 36 | } else { |
| 37 | const err = await verResp.json().catch(() => ({})); |
| 38 | showError(err.error ?? "Passkey sign in failed"); |
| 39 | } |
| 40 | } catch (e) { |
| 41 | showError( |
| 42 | "Passkey sign in failed: " + |
| 43 | (e instanceof Error ? e.message : String(e)), |
| 44 | ); |
| 45 | } finally { |
| 46 | btn.disabled = false; |
| 47 | btn.textContent = originalText; |
| 48 | } |
| 49 | }); |
| 50 | } |
| 51 |