From d2873bf9e0b130fac905a78e5ed86fad95265d70 Mon Sep 17 00:00:00 2001 From: Gros Frumos Date: Sat, 21 Mar 2026 08:13:14 +0200 Subject: [PATCH] kin: BATON-SEC-003-frontend_dev --- frontend/app.js | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/frontend/app.js b/frontend/app.js index 10c4b1b..e457ee7 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -56,9 +56,14 @@ function _getUserName() { return _storage.getItem('baton_user_name') || ''; } -function _saveRegistration(name) { +function _getApiKey() { + return _storage.getItem('baton_api_key') || ''; +} + +function _saveRegistration(name, apiKey) { _storage.setItem('baton_user_name', name); _storage.setItem('baton_registered', '1'); + if (apiKey) _storage.setItem('baton_api_key', apiKey); } function _getInitials(name) { @@ -102,15 +107,17 @@ function _updateUserAvatar() { // ========== API calls ========== -async function _apiPost(path, body) { +async function _apiPost(path, body, extraHeaders) { const res = await fetch(path, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'application/json', ...extraHeaders }, body: JSON.stringify(body), }); if (!res.ok) { const text = await res.text().catch(() => ''); - throw new Error('HTTP ' + res.status + (text ? ': ' + text : '')); + const err = new Error('HTTP ' + res.status + (text ? ': ' + text : '')); + err.status = res.status; + throw err; } return res.json(); } @@ -146,8 +153,8 @@ async function _handleRegister() { try { const uuid = _getOrCreateUserId(); - await _apiPost('/api/register', { uuid, name }); - _saveRegistration(name); + const data = await _apiPost('/api/register', { uuid, name }); + _saveRegistration(name, data.api_key); _updateUserAvatar(); _showMain(); } catch (_) { @@ -179,7 +186,9 @@ async function _handleSignal() { const body = { user_id: uuid, timestamp: Date.now() }; if (geo) body.geo = geo; - await _apiPost('/api/signal', body); + const apiKey = _getApiKey(); + const authHeaders = apiKey ? { Authorization: 'Bearer ' + apiKey } : {}; + await _apiPost('/api/signal', body, authHeaders); _setSosState('success'); _setStatus('Signal sent!', 'success'); @@ -187,9 +196,13 @@ async function _handleSignal() { _setSosState('default'); _setStatus('', ''); }, 2000); - } catch (_) { + } catch (err) { _setSosState('default'); - _setStatus('Error sending. Try again.', 'error'); + if (err && err.status === 401) { + _setStatus('Session expired or key is invalid. Please re-register.', 'error'); + } else { + _setStatus('Error sending. Try again.', 'error'); + } } }