Files

65 lines
2.6 KiB
JavaScript
Raw Permalink Normal View History

// web/view-claim.mjs -- the invite claim and the token paste: the
// only public screen. A single-use invite code is exchanged for a
// persistent token; the display name is a freeform label, collisions
// allowed. The paste path takes a token straight into the store --
// the debug token's way in, and the only browser-migration path for
// a saved token (tokens are returned once, never listed).
import { $ } from './dom.mjs';
import { api, setToken, clearToken } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { logEvent } from './log.mjs';
import { navigate } from './router.mjs';
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) {
/** @type {HTMLInputElement} */ ($('claim-code')).value = '';
/** @type {HTMLInputElement} */ ($('claim-name')).value = '';
/** @type {HTMLInputElement} */ ($('token-paste')).value = '';
let fresh = false;
let debug = false;
try { ({ fresh = false, debug = false } = await api('/session')); } catch { /* public: works signed out; a dead server shows the plain hint */ }
if (seq !== state.seq) return;
/** @type {string} */
let hint;
if (debug) hint = 'debug server -- paste the token the server printed at boot';
else hint = fresh
? 'this deployment has no users yet -- the superuser invite is in state/bootstrap-invite.txt on the server'
: 'a single-use invite code, from the operator';
$('claim-hint').textContent = hint;
/** @type {HTMLInputElement} */ ($('claim-code')).focus();
}
$('claim-form').addEventListener('submit', async (e) => {
e.preventDefault();
try {
const r = await api('/claim', { method: 'POST', body: { code: /** @type {HTMLInputElement} */ ($('claim-code')).value.trim(), name: /** @type {HTMLInputElement} */ ($('claim-name')).value.trim() } });
setToken(r.token);
state.me = r.user;
logEvent('nav', `claimed: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`);
navigate('/');
} catch (err) {
banner(err.message);
}
});
// the paste path: store the token, then verify it the same way the
// app boot does -- the public /session resolves it to a user or null
$('token-form').addEventListener('submit', async (e) => {
e.preventDefault();
const t = /** @type {HTMLInputElement} */ ($('token-paste')).value.trim();
if (!t) return;
try {
setToken(t);
const r = await api('/session');
if (!r.user) { clearToken(); banner('token rejected'); return; }
state.me = r.user;
logEvent('nav', `signed in: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`);
navigate('/');
} catch (err) {
clearToken();
banner(err.message);
}
});