feat(auth): enforce login route with global middleware

This commit is contained in:
Ruslan Bakiev
2026-02-23 12:01:03 +07:00
parent 5918a0593d
commit 43960d0374
4 changed files with 109 additions and 54 deletions

View File

@@ -0,0 +1,20 @@
export default defineNuxtRouteMiddleware(async (to) => {
const isLoginRoute = to.path === "/login";
const fetcher = import.meta.server ? useRequestFetch() : $fetch;
let authenticated = false;
try {
await fetcher("/api/auth/session", { method: "GET" });
authenticated = true;
} catch {
authenticated = false;
}
if (!authenticated && !isLoginRoute) {
return navigateTo("/login");
}
if (authenticated && isLoginRoute) {
return navigateTo("/");
}
});