nuxt-supabase-team-auth
Version:
Drop-in Nuxt 3 module for team-based authentication with Supabase
30 lines (29 loc) • 1.34 kB
JavaScript
import { useTeamAuth } from "../composables/useTeamAuth.js";
import { navigateTo, defineNuxtRouteMiddleware, useRuntimeConfig } from "#imports";
export default defineNuxtRouteMiddleware(async (to) => {
const { currentUser, currentTeam, currentRole, isLoading } = useTeamAuth();
if (isLoading.value) {
let attempts = 0;
const maxAttempts = 20;
while (isLoading.value && attempts < maxAttempts) {
await new Promise((resolve) => setTimeout(resolve, 100));
attempts++;
if (currentUser.value !== void 0 && currentTeam.value !== void 0) {
break;
}
}
if (isLoading.value && attempts >= maxAttempts) {
console.warn("[Team Auth] Auth loading timeout in require-team middleware, proceeding anyway");
}
}
if (!currentUser.value) {
const redirectUrl = `${to.path}${to.search ? `?${new URLSearchParams(to.query).toString()}` : ""}`;
const config = useRuntimeConfig();
const loginPage = config.public.teamAuth?.loginPage || "/signin";
return navigateTo(`${loginPage}?redirect=${encodeURIComponent(redirectUrl)}`);
}
if (!currentTeam.value || !currentRole.value) {
console.error("[Team Auth] Authenticated user missing team/role - data integrity issue. User ID:", currentUser.value.id);
return navigateTo("/signin?error=account_misconfigured");
}
});