Files
console-dev/app/plugins/03-session.client.js
T
2026-11-06 00:04:38 +08:00

38 lines
1.2 KiB
JavaScript

import { defineNuxtPlugin } from "#app";
import { useAuth, isValidJwt } from "~/lib/auth.js";
import { r as safeRedirect } from "~/lib/auth-redirect.js";
import { isPublicRoute } from "~/utils/access.js";
export default defineNuxtPlugin({
name: "console-session-sync",
dependsOn: ["console-ui"],
setup(app) {
const auth = useAuth();
const router = app.$router;
function reconcileSession(event) {
if (
event.storageArea !== localStorage ||
(event.key !== null && event.key !== "jwt")
)
return;
// Read the latest value: several storage events may already be queued.
const persisted = localStorage.getItem("jwt");
if (persisted === auth.token) return;
if (isValidJwt(persisted)) auth.loginWithJwt(persisted);
else auth.clear();
const route = router.currentRoute.value;
if (!auth.isLoggedIn && !isPublicRoute(route)) {
const redirect = safeRedirect(route.fullPath);
void router.replace({
path: "/login",
query: redirect === "/" ? {} : { redirect },
});
}
}
window.addEventListener("storage", reconcileSession);
app.vueApp.onUnmount(() =>
window.removeEventListener("storage", reconcileSession),
);
},
});