Auth fix: apiPost/apiPut/apiDelete uses Bearer token

sport2.html:
- apiPost: localStorage pgz_access → Authorization: Bearer
- apiPut, apiDelete added
- Better error toast

Login redirect (multiple files):
- Wrap auto-redirect in __pgz_made_api_call check
- Don't redirect on initial page load if user has no API call yet
This commit is contained in:
2026-05-05 18:22:52 +02:00
parent 1bc30d7881
commit 7608839473
2 changed files with 37 additions and 5 deletions
+36 -4
View File
@@ -575,25 +575,57 @@ function txt(v, fb){
}
async function api(path){
try{
const r = await fetch(API+path);
const tok = localStorage.getItem('pgz_access') || sessionStorage.getItem('pgz_access') || localStorage.getItem('access_token') || '';
const headers = {};
if(tok) headers['Authorization'] = 'Bearer ' + tok;
const r = await fetch(API+path, {headers});
if(!r.ok) throw new Error('HTTP '+r.status);
return await r.json();
}catch(e){
console.error('API error', path, e);
console.error('API GET error', path, e);
return null;
}
}
async function apiPost(path, body){
try{
const r = await fetch(API+path, {method:'POST', headers:{'Content-Type':'application/json'}, body: body?JSON.stringify(body):'{}'});
if(!r.ok) throw new Error('HTTP '+r.status);
const tok = localStorage.getItem('pgz_access') || sessionStorage.getItem('pgz_access') || localStorage.getItem('access_token') || '';
const headers = {'Content-Type':'application/json'};
if(tok) headers['Authorization'] = 'Bearer ' + tok;
const r = await fetch(API+path, {method:'POST', headers, body: body?JSON.stringify(body):'{}'});
if(!r.ok){
const errText = await r.text().catch(()=>(''));
throw new Error('HTTP '+r.status+(errText? ': '+errText.slice(0,150):''));
}
return await r.json();
}catch(e){
console.error('API POST error', path, e);
if(typeof showToast === 'function') showToast('Greška: '+e.message, 'err');
return null;
}
}
async function apiPut(path, body){
try{
const tok = localStorage.getItem('pgz_access') || sessionStorage.getItem('pgz_access') || '';
const headers = {'Content-Type':'application/json'};
if(tok) headers['Authorization'] = 'Bearer ' + tok;
const r = await fetch(API+path, {method:'PUT', headers, body: JSON.stringify(body||{})});
if(!r.ok) throw new Error('HTTP '+r.status);
return await r.json();
}catch(e){ console.error('API PUT error', path, e); return null; }
}
async function apiDelete(path){
try{
const tok = localStorage.getItem('pgz_access') || sessionStorage.getItem('pgz_access') || '';
const headers = {};
if(tok) headers['Authorization'] = 'Bearer ' + tok;
const r = await fetch(API+path, {method:'DELETE', headers});
if(!r.ok) throw new Error('HTTP '+r.status);
return await r.json();
}catch(e){ console.error('API DELETE error', path, e); return null; }
}
// Cache the latest preview so /apply can pass back the same sources
window._enrichPreviews = window._enrichPreviews || {};