fixed
This commit is contained in:
1 parent
4194cef934
commit
363127fe9e
3350 files changed
+1284220
-1
No files matched your search
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Authentication helpers: login, logout, page guard and header profile.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
/** Redirect to the login page when no access token is stored. */
|
||||
function requireAuth() {
|
||||
if (!Api.tokens.access) {
|
||||
Api.redirectToLogin();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Sign in and store the token pair. */
|
||||
async function login(loginValue, password) {
|
||||
const pair = await Api.post("/v1/admin/login", {
|
||||
login: loginValue,
|
||||
password: password,
|
||||
});
|
||||
if (!pair || !pair.accessToken) {
|
||||
throw new Api.ApiError("Login failed. Please try again.", 500);
|
||||
}
|
||||
Api.tokens.set(pair);
|
||||
}
|
||||
|
||||
function logout() {
|
||||
Api.tokens.clear();
|
||||
window.location.href = "/admin/login";
|
||||
}
|
||||
|
||||
/** Load the admin profile and render it into the header. */
|
||||
async function loadProfile() {
|
||||
const nameEl = document.getElementById("profile-name");
|
||||
const avatarEl = document.getElementById("profile-avatar");
|
||||
const initialEl = document.getElementById("profile-initial");
|
||||
if (!nameEl) return;
|
||||
try {
|
||||
const profile = await Api.get("/v1/admin/get-profile");
|
||||
const fullName = (profile && profile.fullName) || "Admin";
|
||||
nameEl.textContent = fullName;
|
||||
if (avatarEl && profile && profile.avatar) {
|
||||
avatarEl.src = profile.avatar;
|
||||
avatarEl.alt = fullName;
|
||||
avatarEl.classList.remove("hidden");
|
||||
if (initialEl) initialEl.classList.add("hidden");
|
||||
} else if (initialEl) {
|
||||
initialEl.textContent = fullName.charAt(0).toUpperCase();
|
||||
}
|
||||
} catch (_) {
|
||||
/* profile is decorative; auth errors already redirect */
|
||||
}
|
||||
}
|
||||
|
||||
function bindLogoutButtons() {
|
||||
document.querySelectorAll("[data-logout]").forEach((button) => {
|
||||
button.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
logout();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
window.Auth = { requireAuth, login, logout, loadProfile, bindLogoutButtons };
|
||||
})();
|
||||
Reference in new issue
Block a user