Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(frontend): handle cross-tab login/logout + auth architecture refactor (#10150)

Ubbefb18ddf95d16
diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
index b3bd78f3a7..54db111dfd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/callback/route.ts
@@ -1,4 +1,4 @@
-import getServerSupabase from "@/lib/supabase/getServerSupabase";
+import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import BackendAPI from "@/lib/autogpt-server-api";
import { NextResponse } from "next/server";
import { revalidatePath } from "next/cache";
diff --git a/autogpt_platform/frontend/src/app/(platform)/auth/confirm/route.ts b/autogpt_platform/frontend/src/app/(platform)/auth/confirm/route.ts
index a78efd20ff..a9b7c6f751 100644
--- a/autogpt_platform/frontend/src/app/(platform)/auth/confirm/route.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/auth/confirm/route.ts
@@ -2,7 +2,7 @@ import { type EmailOtpType } from "@supabase/supabase-js";
import { type NextRequest } from "next/server";
import { redirect } from "next/navigation";
-import getServerSupabase from "@/lib/supabase/getServerSupabase";
+import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
// Email confirmation route
export async function GET(request: NextRequest) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/login/actions.ts b/autogpt_platform/frontend/src/app/(platform)/login/actions.ts
index 69a1c0be95..ab84cc54f0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/login/actions.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/login/actions.ts
@@ -3,7 +3,7 @@ import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import * as Sentry from "@sentry/nextjs";
-import getServerSupabase from "@/lib/supabase/getServerSupabase";
+import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import BackendAPI from "@/lib/autogpt-server-api";
import { loginFormSchema, LoginProvider } from "@/types/auth";
import { verifyTurnstileToken } from "@/lib/turnstile";
diff --git a/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts b/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts
index 685db4e6e4..a394b6e8a4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/login/useLoginPage.ts
@@ -1,5 +1,5 @@
import { useTurnstile } from "@/hooks/useTurnstile";
-import useSupabase from "@/lib/supabase/useSupabase";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { loginFormSchema, LoginProvider } from "@/types/auth";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/agent/[creator]/[slug]/page.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/agent/[creator]/[slug]/page.tsx
index 2c10864f55..0bbc0b8c60 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/agent/[creator]/[slug]/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/agent/[creator]/[slug]/page.tsx
@@ -6,7 +6,7 @@ import { AgentsSection } from "@/components/agptui/composite/AgentsSection";
import { BecomeACreator } from "@/components/agptui/BecomeACreator";
import { Separator } from "@/components/ui/separator";
import { Metadata } from "next";
-import getServerUser from "@/lib/supabase/getServerUser";
+import { getServerUser } from "@/lib/supabase/server/getServerUser";
// Force dynamic rendering to avoid static generation issues with cookies
export const dynamic = "force-dynamic";
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/page.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/page.tsx
index 309a41cb7e..e2cface85c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/page.tsx
@@ -11,7 +11,7 @@ import {
StoreSubmissionsResponse,
StoreSubmissionRequest,
} from "@/lib/autogpt-server-api/types";
-import useSupabase from "@/lib/supabase/useSupabase";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
export default function Page({}: {}) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/integrations/page.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/integrations/page.tsx
index 3cceb3c6b3..7ffb97ca5e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/integrations/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/integrations/page.tsx
@@ -26,7 +26,7 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
-import useSupabase from "@/lib/supabase/useSupabase";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import LoadingBox from "@/components/ui/loading";
export default function UserIntegrationsPage() {
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/actions.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/actions.ts
index 88d996cf43..09fc2e26e0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/actions.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/actions.ts
@@ -1,7 +1,7 @@
"use server";
import { revalidatePath } from "next/cache";
-import getServerSupabase from "@/lib/supabase/getServerSupabase";
+import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import BackendApi from "@/lib/autogpt-server-api";
import { NotificationPreferenceDTO } from "@/lib/autogpt-server-api/types";
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/page.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/page.tsx
index 21898fe0ca..e000accbe1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/page.tsx
@@ -1,7 +1,7 @@
import * as React from "react";
import { Metadata } from "next";
import SettingsForm from "@/components/profile/settings/SettingsForm";
-import getServerUser from "@/lib/supabase/getServerUser";
+import { getServerUser } from "@/lib/supabase/server/getServerUser";
import { redirect } from "next/navigation";
import { getUserPreferences } from "./actions";
diff --git a/autogpt_platform/frontend/src/app/(platform)/reset_password/actions.ts b/autogpt_platform/frontend/src/app/(platform)/reset_password/actions.ts
index e1e8a17af6..7cc4da5189 100644
--- a/autogpt_platform/frontend/src/app/(platform)/reset_password/actions.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/reset_password/actions.ts
@@ -1,5 +1,5 @@
"use server";
-import getServerSupabase from "@/lib/supabase/getServerSupabase";
+import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import { redirect } from "next/navigation";
import * as Sentry from "@sentry/nextjs";
import { verifyTurnstileToken } from "@/lib/turnstile";
@@ -64,7 +64,7 @@ export async function changePassword(password: string, turnstileToken: string) {
return error.message;
}
- await supabase.auth.signOut();
+ await supabase.auth.signOut({ scope: "global" });
redirect("/login");
},
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsx b/autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsx
index 23e0e336e4..5a8e04290f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/reset_password/page.tsx
@@ -17,7 +17,7 @@ import {
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
-import useSupabase from "@/lib/supabase/useSupabase";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { sendEmailFormSchema, changePasswordFormSchema } from "@/types/auth";
import { zodResolver } from "@hookform/resolvers/zod";
import { useCallback, useState } from "react";
diff --git a/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts b/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts
index 3d3819e6d4..9fa41e4510 100644
--- a/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/signup/actions.ts
@@ -3,7 +3,7 @@ import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";
import * as Sentry from "@sentry/nextjs";
-import getServerSupabase from "@/lib/supabase/getServerSupabase";
+import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import { signupFormSchema } from "@/types/auth";
import BackendAPI from "@/lib/autogpt-server-api";
import { verifyTurnstileToken } from "@/lib/turnstile";
diff --git a/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts b/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts
index 6394c5cb71..bc3a64291a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/signup/useSignupPage.ts
@@ -1,5 +1,5 @@
import { useTurnstile } from "@/hooks/useTurnstile";
-import useSupabase from "@/lib/supabase/useSupabase";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { signupFormSchema, LoginProvider } from "@/types/auth";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
diff --git a/autogpt_platform/frontend/src/components/RoleBasedAccess.tsx b/autogpt_platform/frontend/src/components/RoleBasedAccess.tsx
index e5a4b98aa2..b31e4dd08b 100644
--- a/autogpt_platform/frontend/src/components/RoleBasedAccess.tsx
+++ b/autogpt_platform/frontend/src/components/RoleBasedAccess.tsx
@@ -1,5 +1,5 @@
// components/RoleBasedAccess.tsx
-import useSupabase from "@/lib/supabase/useSupabase";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import React from "react";
interface RoleBasedAccessProps {
diff --git a/autogpt_platform/frontend/src/components/agptui/Navbar.tsx b/autogpt_platform/frontend/src/components/agptui/Navbar.tsx
index ff188888e7..5e78a4dc31 100644
--- a/autogpt_platform/frontend/src/components/agptui/Navbar.tsx
+++ b/autogpt_platform/frontend/src/components/agptui/Navbar.tsx
@@ -7,8 +7,9 @@ import { Button } from "./Button";
import Wallet from "./Wallet";
import { ProfileDetails } from "@/lib/autogpt-server-api/types";
import { NavbarLink } from "./NavbarLink";
-import getServerUser from "@/lib/supabase/getServerUser";
+
import BackendAPI from "@/lib/autogpt-server-api";
+import { getServerUser } from "@/lib/supabase/server/getServerUser";
// Disable theme toggle for now
// import { ThemeToggle } from "./ThemeToggle";
diff --git a/autogpt_platform/frontend/src/components/agptui/ProfileInfoForm.tsx b/autogpt_platform/frontend/src/components/agptui/ProfileInfoForm.tsx
index c83945becc..ad45fd93b7 100644
--- a/autogpt_platform/frontend/src/components/agptui/ProfileInfoForm.tsx
+++ b/autogpt_platform/frontend/src/components/agptui/ProfileInfoForm.tsx
@@ -9,7 +9,7 @@ import { Button } from "./Button";
import { IconPersonFill } from "@/components/ui/icons";
import { ProfileDetails } from "@/lib/autogpt-server-api/types";
import { Separator } from "@/components/ui/separator";
-import useSupabase from "@/lib/supabase/useSupabase";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
export const ProfileInfoForm = ({ profile }: { profile: ProfileDetails }) => {
diff --git a/autogpt_platform/frontend/src/components/agptui/ProfilePopoutMenuLogoutButton.tsx b/autogpt_platform/frontend/src/components/agptui/ProfilePopoutMenuLogoutButton.tsx
index 18c30e1ad1..ea2b4473b9 100644
--- a/autogpt_platform/frontend/src/components/agptui/ProfilePopoutMenuLogoutButton.tsx
+++ b/autogpt_platform/frontend/src/components/agptui/ProfilePopoutMenuLogoutButton.tsx
@@ -1,5 +1,5 @@
"use client";
-import useSupabase from "@/lib/supabase/useSupabase";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { IconLogOut } from "@/components/ui/icons";
import { useTransition } from "react";
import { LoadingSpinner } from "../ui/loading";
@@ -16,7 +16,7 @@ export function ProfilePopoutMenuLogoutButton() {
function handleLogout() {
startTransition(async () => {
try {
- await supabase.logOut();
+ await supabase.logOut({ scope: "global" });
router.refresh();
} catch (e) {
Sentry.captureException(e);
diff --git a/autogpt_platform/frontend/src/components/agptui/composite/HeroSection.tsx b/autogpt_platform/frontend/src/components/agptui/composite/HeroSection.tsx
index e666d9f267..955ba1830c 100644
--- a/autogpt_platform/frontend/src/components/agptui/composite/HeroSection.tsx
+++ b/autogpt_platform/frontend/src/components/agptui/composite/HeroSection.tsx
@@ -5,6 +5,7 @@ import { SearchBar } from "@/components/agptui/SearchBar";
import { FilterChips } from "@/components/agptui/FilterChips";
import { useRouter } from "next/navigation";
import { useOnboarding } from "@/components/onboarding/onboarding-provider";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
export const HeroSection: React.FC = () => {
const router = useRouter();
diff --git a/autogpt_platform/frontend/src/components/integrations/credentials-provider.tsx b/autogpt_platform/frontend/src/components/integrations/credentials-provider.tsx
index f74fc3c7c5..26823d0177 100644
--- a/autogpt_platform/frontend/src/components/integrations/credentials-provider.tsx
+++ b/autogpt_platform/frontend/src/components/integrations/credentials-provider.tsx
@@ -1,5 +1,5 @@
import { createContext, useCallback, useEffect, useState } from "react";
-import useSupabase from "@/lib/supabase/useSupabase";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import {
APIKeyCredentials,
CredentialsDeleteNeedConfirmationResponse,
diff --git a/autogpt_platform/frontend/src/components/onboarding/onboarding-provider.tsx b/autogpt_platform/frontend/src/components/onboarding/onboarding-provider.tsx
index 61c2b64e8d..72589bc8d0 100644
--- a/autogpt_platform/frontend/src/components/onboarding/onboarding-provider.tsx
+++ b/autogpt_platform/frontend/src/components/onboarding/onboarding-provider.tsx
@@ -1,5 +1,5 @@
"use client";
-import useSupabase from "@/lib/supabase/useSupabase";
+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { OnboardingStep, UserOnboarding } from "@/lib/autogpt-server-api";
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
import { usePathname, useRouter } from "next/navigation";
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
index 043205ae84..1be9967957 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
@@ -1,4 +1,4 @@
-import getServerSupabase from "@/lib/supabase/getServerSupabase";
+import { getServerSupabase } from "@/lib/supabase/server/getServerSupabase";
import { createBrowserClient } from "@supabase/ssr";
import type { SupabaseClient } from "@supabase/supabase-js";
import type {
diff --git a/autogpt_platform/frontend/src/lib/supabase/helpers.ts b/autogpt_platform/frontend/src/lib/supabase/helpers.ts
new file mode 100644
index 0000000000..4d44c1ab07
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/supabase/helpers.ts
@@ -0,0 +1,83 @@
+// Session management constants and utilities
+
+export const PROTECTED_PAGES = [
+ "/monitor",
+ "/build",
+ "/onboarding",
+ "/profile",
+ "/library",
+ "/monitoring",
+] as const;
+
+export const ADMIN_PAGES = ["/admin"] as const;
+
+export const STORAGE_KEYS = {
+ LOGOUT: "supabase-logout",
+} as const;
+
+// Page protection utilities
+export function isProtectedPage(pathname: string): boolean {
+ return PROTECTED_PAGES.some((page) => pathname.startsWith(page));
+}
+
+export function isAdminPage(pathname: string): boolean {
+ return ADMIN_PAGES.some((page) => pathname.startsWith(page));
+}
+
+export function shouldRedirectOnLogout(pathname: string): boolean {
+ return isProtectedPage(pathname) || isAdminPage(pathname);
+}
+
+// Cross-tab logout utilities
+export function broadcastLogout(): void {
+ if (typeof window !== "undefined") {
+ window.localStorage.setItem(STORAGE_KEYS.LOGOUT, Date.now().toString());
+ }
+}
+
+export function isLogoutEvent(event: StorageEvent): boolean {
+ return event.key === STORAGE_KEYS.LOGOUT;
+}
+
+// Redirect utilities
+export function getRedirectPath(
+ pathname: string,
+ userRole?: string,
+): string | null {
+ if (shouldRedirectOnLogout(pathname)) {
+ return "/login";
+ }
+
+ if (isAdminPage(pathname) && userRole !== "admin") {
+ return "/marketplace";
+ }
+
+ return null;
+}
+
+// Event listener management
+export interface EventListeners {
+ cleanup: () => void;
+}
+
+export function setupSessionEventListeners(
+ onVisibilityChange: () => void,
+ onFocus: () => void,
+ onStorageChange: (e: StorageEvent) => void,
+): EventListeners {
+ if (typeof window === "undefined" || typeof document === "undefined") {
+ return { cleanup: () => {} };
+ }
+
+ document.addEventListener("visibilitychange", onVisibilityChange);
+ window.addEventListener("focus", onFocus);
+ window.addEventListener("storage", onStorageChange);
+
+ return {
+ cleanup: () => {
+ document.removeEventListener("visibilitychange", onVisibilityChange);
+ window.removeEventListener("focus", onFocus);
+ window.removeEventListener("storage", onStorageChange);
+ },
+ };
+}
diff --git a/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts b/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts
new file mode 100644
index 0000000000..df79d18373
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/supabase/hooks/useSupabase.ts
@@ -0,0 +1,158 @@
+"use client";
+import { useEffect, useMemo, useState, useRef } from "react";
+import { createBrowserClient } from "@supabase/ssr";
+import { SignOut, User } from "@supabase/supabase-js";
+import { useRouter } from "next/navigation";
+import {
+ broadcastLogout,
+ getRedirectPath,
+ isLogoutEvent,
+ setupSessionEventListeners,
+} from "../helpers";
+
+export function useSupabase() {
+ const router = useRouter();
+ const [user, setUser] = useState<User | null>(null);
+ const [isUserLoading, setIsUserLoading] = useState(true);
+ const lastValidationRef = useRef<number>(0);
+
+ const supabase = useMemo(() => {
+ try {
+ return createBrowserClient(
+ process.env.NEXT_PUBLIC_SUPABASE_URL!,
+ process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
+ { isSingleton: true },
+ );
+ } catch (error) {
+ console.error("Error creating Supabase client", error);
+ return null;
+ }
+ }, []);
+
+ async function logOut(options?: SignOut) {
+ if (!supabase) return;
+
+ broadcastLogout();
+
+ const { error } = await supabase.auth.signOut({
+ scope: "global",
+ });
+ if (error) console.error("Error logging out:", error);
+
+ router.push("/login");
+ }
+
+ async function validateSession() {
+ if (!supabase) return false;
+
+ // Simple debounce - only validate if 2 seconds have passed
+ const now = Date.now();
+ if (now - lastValidationRef.current < 2000) {
+ return true;
+ }
+ lastValidationRef.current = now;
+
+ try {
+ const {
+ data: { user: apiUser },
+ error,
+ } = await supabase.auth.getUser();
+
+ if (error || !apiUser) {
+ // Session is invalid, clear local state
+ setUser(null);
+ const redirectPath = getRedirectPath(window.location.pathname);
+ if (redirectPath) {
+ router.push(redirectPath);
+ }
+ return false;
+ }
+
+ // Update local state if we have a valid user but no local user
+ if (apiUser && !user) {
+ setUser(apiUser);
+ }
+
+ return true;
+ } catch (error) {
+ console.error("Session validation error:", error);
+ setUser(null);
+ const redirectPath = getRedirectPath(window.location.pathname);
+ if (redirectPath) {
+ router.push(redirectPath);
+ }
+ return false;
+ }
+ }
+
+ function handleCrossTabLogout(e: StorageEvent) {
+ if (!isLogoutEvent(e)) return;
+
+ // Clear the Supabase session first
+ if (supabase) {
+ supabase.auth.signOut({ scope: "global" }).catch(console.error);
+ }
+
+ // Clear local state immediately
+ setUser(null);
+ router.refresh();
+
+ const redirectPath = getRedirectPath(window.location.pathname);
+ if (redirectPath) {
+ router.push(redirectPath);
+ }
+ }
+
+ function handleVisibilityChange() {
+ if (document.visibilityState === "visible") {
+ validateSession();
+ }
+ }
+
+ function handleFocus() {
+ validateSession();
+ }
+
+ useEffect(() => {
+ if (!supabase) {
+ setIsUserLoading(false);
+ return;
+ }
+
+ const {
+ data: { subscription },
+ } = supabase.auth.onAuthStateChange((event, session) => {
+ const newUser = session?.user ?? null;
+
+ // Only update if user actually changed to prevent unnecessary re-renders
+ setUser((currentUser) => {
+ if (currentUser?.id !== newUser?.id) {
+ return newUser;
+ }
+ return currentUser;
+ });
+
+ setIsUserLoading(false);
+ });
+
+ const eventListeners = setupSessionEventListeners(
+ handleVisibilityChange,
+ handleFocus,
+ handleCrossTabLogout,
+ );
+
+ return () => {
+ subscription.unsubscribe();
+ eventListeners.cleanup();
+ };
+ }, [supabase]);
+
+ return {
+ supabase,
+ user,
+ isLoggedIn: !isUserLoading ? !!user : null,
+ isUserLoading,
+ logOut,
+ validateSession,
+ };
+}
diff --git a/autogpt_platform/frontend/src/lib/supabase/middleware.ts b/autogpt_platform/frontend/src/lib/supabase/middleware.ts
index 7680323558..da9ee26b20 100644
--- a/autogpt_platform/frontend/src/lib/supabase/middleware.ts
+++ b/autogpt_platform/frontend/src/lib/supabase/middleware.ts
@@ -1,16 +1,11 @@
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
-
-// TODO: Update the protected pages list
-const PROTECTED_PAGES = [
- "/monitor",
- "/build",
- "/onboarding",
- "/profile",
- "/library",
- "/monitoring",
-];
-const ADMIN_PAGES = ["/admin"];
+import {
+ PROTECTED_PAGES,
+ ADMIN_PAGES,
+ isProtectedPage,
+ isAdminPage,
+} from "./helpers";
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
@@ -59,41 +54,26 @@ export async function updateSession(request: NextRequest) {
error,
} = await supabase.auth.getUser();
- // Get the user role
const userRole = user?.role;
const url = request.nextUrl.clone();
+ const pathname = request.nextUrl.pathname;
+
// AUTH REDIRECTS
// 1. Check if user is not authenticated but trying to access protected content
if (!user) {
- // Check if the user is trying to access either a protected page or an admin page
- const isAttemptingProtectedPage = PROTECTED_PAGES.some((page) =>
- request.nextUrl.pathname.startsWith(page),
- );
-
- const isAttemptingAdminPage = ADMIN_PAGES.some((page) =>
- request.nextUrl.pathname.startsWith(page),
- );
+ const attemptingProtectedPage = isProtectedPage(pathname);
+ const attemptingAdminPage = isAdminPage(pathname);
- // If trying to access any protected content without being logged in,
- // redirect to login page
- if (isAttemptingProtectedPage || isAttemptingAdminPage) {
- url.pathname = `/login`;
+ if (attemptingProtectedPage || attemptingAdminPage) {
+ url.pathname = "/login";
return NextResponse.redirect(url);
}
}
// 2. Check if user is authenticated but lacks admin role when accessing admin pages
- if (user && userRole !== "admin") {
- const isAttemptingAdminPage = ADMIN_PAGES.some((page) =>
- request.nextUrl.pathname.startsWith(page),
- );
-
- // If a non-admin user is trying to access admin pages,
- // redirect to marketplace
- if (isAttemptingAdminPage) {
- url.pathname = `/marketplace`;
- return NextResponse.redirect(url);
- }
+ if (user && userRole !== "admin" && isAdminPage(pathname)) {
+ url.pathname = "/marketplace";
+ return NextResponse.redirect(url);
}
// IMPORTANT: You *must* return the supabaseResponse object as it is. If you're
diff --git a/autogpt_platform/frontend/src/lib/supabase/getServerSupabase.ts b/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts
similarity index 95%
rename from autogpt_platform/frontend/src/lib/supabase/getServerSupabase.ts
rename to autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts
index ffa61fe997..555d32982c 100644
--- a/autogpt_platform/frontend/src/lib/supabase/getServerSupabase.ts
+++ b/autogpt_platform/frontend/src/lib/supabase/server/getServerSupabase.ts
@@ -1,7 +1,7 @@
import type { UnsafeUnwrappedCookies } from "next/headers";
import { createServerClient } from "@supabase/ssr";
-export default async function getServerSupabase() {
+export async function getServerSupabase() {
// Need require here, so Next.js doesn't complain about importing this on client side
const { cookies } = require("next/headers");
const cookieStore = await cookies();
diff --git a/autogpt_platform/frontend/src/lib/supabase/getServerUser.ts b/autogpt_platform/frontend/src/lib/supabase/server/getServerUser.ts
similarity index 86%
rename from autogpt_platform/frontend/src/lib/supabase/getServerUser.ts
rename to autogpt_platform/frontend/src/lib/supabase/server/getServerUser.ts
index b456d768d9..2b8d57e2a0 100644
--- a/autogpt_platform/frontend/src/lib/supabase/getServerUser.ts
+++ b/autogpt_platform/frontend/src/lib/supabase/server/getServerUser.ts
@@ -1,6 +1,6 @@
-import getServerSupabase from "./getServerSupabase";
+import { getServerSupabase } from "./getServerSupabase";
-const getServerUser = async () => {
+export async function getServerUser() {
const supabase = await getServerSupabase();
if (!supabase) {
@@ -10,7 +10,7 @@ const getServerUser = async () => {
try {
const {
data: { user },
- error,
+ error: _,
} = await supabase.auth.getUser();
// if (error) {
// // FIX: Suppressing error for now. Need to stop the nav bar calling this all the time
@@ -30,6 +30,4 @@ const getServerUser = async () => {
error: `Unexpected error: ${(error as Error).message}`,
};
}
-};
-
-export default getServerUser;
+}
diff --git a/autogpt_platform/frontend/src/lib/supabase/useSupabase.ts b/autogpt_platform/frontend/src/lib/supabase/useSupabase.ts
deleted file mode 100644
index f450007267..0000000000
--- a/autogpt_platform/frontend/src/lib/supabase/useSupabase.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-"use client";
-import { useCallback, useEffect, useMemo, useState } from "react";
-import { createBrowserClient } from "@supabase/ssr";
-import { SignOut, User } from "@supabase/supabase-js";
-import { useRouter } from "next/navigation";
-
-export default function useSupabase() {
- const router = useRouter();
- const [user, setUser] = useState<User | null>(null);
- const [isUserLoading, setIsUserLoading] = useState(true);
-
- const supabase = useMemo(() => {
- try {
- return createBrowserClient(
- process.env.NEXT_PUBLIC_SUPABASE_URL!,
- process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
- { isSingleton: true },
- );
- } catch (error) {
- console.error("Error creating Supabase client", error);
- return null;
- }
- }, []);
-
- useEffect(() => {
- if (!supabase) {
- setIsUserLoading(false);
- return;
- }
-
- // Sync up the current state and listen for changes
- const {
- data: { subscription },
- } = supabase.auth.onAuthStateChange((_event, session) => {
- setUser(session?.user ?? null);
- setIsUserLoading(false);
- });
-
- return () => {
- subscription.unsubscribe();
- };
- }, [supabase]);
-
- const logOut = useCallback(
- async (options?: SignOut) => {
- if (!supabase) return;
-
- const { error } = await supabase.auth.signOut({
- scope: options?.scope ?? "local",
- });
- if (error) console.error("Error logging out:", error);
-
- router.push("/login");
- },
- [router, supabase],
- );
-
- if (!supabase || isUserLoading) {
- return { supabase, user: null, isLoggedIn: null, isUserLoading, logOut };
- }
- if (!user) {
- return { supabase, user, isLoggedIn: false, isUserLoading, logOut };
- }
- return { supabase, user, isLoggedIn: true, isUserLoading, logOut };
-}
diff --git a/autogpt_platform/frontend/src/lib/withRoleAccess.ts b/autogpt_platform/frontend/src/lib/withRoleAccess.ts
index 685e9aa9f5..7b63253c56 100644
--- a/autogpt_platform/frontend/src/lib/withRoleAccess.ts
+++ b/autogpt_platform/frontend/src/lib/withRoleAccess.ts
@@ -1,7 +1,7 @@
import React from "react";
import * as Sentry from "@sentry/nextjs";
import { redirect } from "next/navigation";
-import getServerUser from "./supabase/getServerUser";
+import { getServerUser } from "./supabase/server/getServerUser";
export async function withRoleAccess(allowedRoles: string[]) {
"use server";