homebox/frontend/middleware/auth.ts

25 lines
663 B
TypeScript
Raw Normal View History

export default defineNuxtRouteMiddleware(async () => {
const ctx = useAuthContext();
const api = useUserApi();
if (!ctx.isAuthorized()) {
2023-10-10 13:43:44 +00:00
if (window.location.pathname !== "/") {
console.debug("[middleware/auth] isAuthorized returned false, redirecting to /");
2023-10-10 13:43:44 +00:00
return navigateTo("/");
}
}
if (!ctx.user) {
console.log("Fetching user data");
const { data, error } = await api.user.self();
if (error) {
2023-10-10 13:43:44 +00:00
if (window.location.pathname !== "/") {
console.debug("[middleware/user] user is null and fetch failed, redirecting to /");
2023-10-10 13:43:44 +00:00
return navigateTo("/");
}
}
ctx.user = data.item;
}
});