Files
njts-accounting-core/frontend/js/auth.js
2026-05-22 23:05:25 +09:00

60 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 認証・セッション管理
*/
// ──────────────────────────────────────
// ページ描画前に即座に認証確認(フラッシュ防止)
// ──────────────────────────────────────
(function () {
if (!window.location.pathname.includes("login.html")) {
if (!localStorage.getItem("currentUser")) {
// ページが見えてしまわないよう即座に非表示にしてからリダイレクト
document.documentElement.style.visibility = "hidden";
window.location.replace("/login.html");
}
}
})();
// bfcache戻る/進むボタン)対応
// ブラウザがキャッシュからページを復元した場合も認証を再確認する
window.addEventListener("pageshow", function (event) {
if (!window.location.pathname.includes("login.html")) {
if (!localStorage.getItem("currentUser")) {
// bfcacheから復元されたページを即座に非表示にしてリダイレクト
document.documentElement.style.visibility = "hidden";
window.location.replace("/login.html");
}
}
});
function checkAuth() {
const user = localStorage.getItem("currentUser");
if (!user) {
window.location.replace("/login.html");
return false;
}
return true;
}
function getCurrentUser() {
const user = localStorage.getItem("currentUser");
return user ? JSON.parse(user) : null;
}
function setCurrentUser(userData) {
localStorage.setItem("currentUser", JSON.stringify(userData));
}
function logout() {
localStorage.removeItem("currentUser");
sessionStorage.clear();
// replace() を使うことでログイン前の履歴に戻れなくなる
window.location.replace("/login.html");
}
document.addEventListener("DOMContentLoaded", function () {
if (!window.location.pathname.includes("login.html")) {
checkAuth();
}
});