60 lines
1.9 KiB
JavaScript
60 lines
1.9 KiB
JavaScript
/**
|
||
* 認証・セッション管理
|
||
*/
|
||
|
||
// ──────────────────────────────────────
|
||
// ページ描画前に即座に認証確認(フラッシュ防止)
|
||
// ──────────────────────────────────────
|
||
(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();
|
||
}
|
||
});
|