Moved authentification code into js/auth.js
This commit is contained in:
8 files changed
+330
-364
No files matched your search
+67
@@ -0,0 +1,67 @@
|
||||
const API_BASE = "http://127.0.0.1:5000/api";
|
||||
let currentUser = null;
|
||||
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/me`, { credentials: "include" });
|
||||
if (res.ok) {
|
||||
currentUser = await res.json();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function checkAuthAndRedirect() {
|
||||
const ok = await checkAuth();
|
||||
if (!ok) {
|
||||
window.location.href = "login.html";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function updateUserMenu() {
|
||||
const container = document.getElementById("user-menu");
|
||||
if (!container) return;
|
||||
if (currentUser) {
|
||||
container.innerHTML = `
|
||||
<span class="username"><i class="fas fa-user"></i> ${escapeHtml(currentUser.username)}</span>
|
||||
<button id="logout-btn" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</button>
|
||||
`;
|
||||
document.getElementById("logout-btn")?.addEventListener("click", logout);
|
||||
} else {
|
||||
container.innerHTML = `<button id="login-open-btn" class="login-btn"><i class="fas fa-sign-in-alt"></i> Login</button>`;
|
||||
document.getElementById("login-open-btn")?.addEventListener("click", () => {
|
||||
window.location.href = "login.html";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
await fetch(`${API_BASE}/logout`, { method: "POST", credentials: "include" });
|
||||
window.location.href = "login.html";
|
||||
}
|
||||
|
||||
function escapeHtml(str) {
|
||||
if (!str) return "";
|
||||
return str.replace(/[&<>]/g, function (m) {
|
||||
if (m === "&") return "&";
|
||||
if (m === "<") return "<";
|
||||
if (m === ">") return ">";
|
||||
return m;
|
||||
});
|
||||
}
|
||||
|
||||
function showToast(msg, isError = false) {
|
||||
const toast = document.getElementById("toast");
|
||||
if (!toast) return;
|
||||
toast.textContent = msg;
|
||||
toast.style.backgroundColor = isError ? "var(--red-7)" : "var(--green-7)";
|
||||
toast.style.display = "block";
|
||||
setTimeout(() => {
|
||||
toast.style.display = "none";
|
||||
}, 3000);
|
||||
}
|
||||
Reference in new issue
Block a user