70 lines
1.9 KiB
JavaScript
Executable File
70 lines
1.9 KiB
JavaScript
Executable File
// assets/js/ui-auth.js
|
|
/**
|
|
* Bindet einen Logout-Button und leitet nach dem Logout weiter (default: /login.php).
|
|
* Usage:
|
|
* import { mountLogoutButton, ensureFloatingLogout } from './ui-auth.js';
|
|
* mountLogoutButton('#btn-logout', { redirect: '/login.php' });
|
|
*/
|
|
export function mountLogoutButton(selector = '#btn-logout', opts = {}) {
|
|
const { redirect = '/login.php' } = opts;
|
|
const btn = document.querySelector(selector);
|
|
if (!btn) return;
|
|
|
|
// Doppelte Bindings verhindern
|
|
if (btn.dataset.bound === '1') return;
|
|
|
|
btn.addEventListener('click', async (e) => {
|
|
e.preventDefault();
|
|
btn.disabled = true;
|
|
const oldText = btn.textContent;
|
|
btn.textContent = 'Abmelden…';
|
|
try {
|
|
await fetch('api.php?action=auth.logout', {
|
|
method: 'POST',
|
|
credentials: 'include',
|
|
headers: { 'Content-Type': 'application/json' }
|
|
});
|
|
} catch (err) {
|
|
console.error('Logout failed', err);
|
|
// Fallback: trotzdem auf Login
|
|
} finally {
|
|
window.location.href = redirect;
|
|
// Falls Redirect durch Policy o.ä. blockiert wäre:
|
|
setTimeout(() => {
|
|
btn.disabled = false;
|
|
btn.textContent = oldText;
|
|
}, 1500);
|
|
}
|
|
});
|
|
|
|
btn.dataset.bound = '1';
|
|
}
|
|
|
|
/**
|
|
* Erzeugt bei Bedarf automatisch einen Floating-Logout-Button (oben rechts)
|
|
* und bindet ihn (gut für Staging/Admin).
|
|
*/
|
|
export function ensureFloatingLogout(opts = {}) {
|
|
if (document.querySelector('#btn-logout')) {
|
|
mountLogoutButton('#btn-logout', opts);
|
|
return;
|
|
}
|
|
const btn = document.createElement('button');
|
|
btn.id = 'btn-logout';
|
|
btn.textContent = 'Logout';
|
|
Object.assign(btn.style, {
|
|
position: 'fixed',
|
|
right: '12px',
|
|
top: '12px',
|
|
zIndex: '10000',
|
|
padding: '8px 12px',
|
|
borderRadius: '8px',
|
|
border: '1px solid #ccc',
|
|
background: '#f5f5f5',
|
|
cursor: 'pointer'
|
|
});
|
|
document.body.appendChild(btn);
|
|
mountLogoutButton('#btn-logout', opts);
|
|
}
|
|
|