kin: BATON-SEC-003-frontend_dev
This commit is contained in:
parent
abae67d75a
commit
d2873bf9e0
1 changed files with 22 additions and 9 deletions
|
|
@ -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,10 +196,14 @@ async function _handleSignal() {
|
|||
_setSosState('default');
|
||||
_setStatus('', '');
|
||||
}, 2000);
|
||||
} catch (_) {
|
||||
} catch (err) {
|
||||
_setSosState('default');
|
||||
if (err && err.status === 401) {
|
||||
_setStatus('Session expired or key is invalid. Please re-register.', 'error');
|
||||
} else {
|
||||
_setStatus('Error sending. Try again.', 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========== Screens ==========
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue