Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
3.6 kB
1
Indexable
Never
// Import necessary libraries
import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
import { toast } from "sonner"; // Assuming you're using Sonner for notifications

// Replace with your environment variables
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const SUPABASE_ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;

// Define protected paths requiring authentication
const protectedPaths = ["/dashboard", "/profile", "/mydata"]; // Replace with your specific paths

// Define authentication routes where logged-in users should be redirected
const authRoutes = ["/auth/login", "/auth/signup", "/auth/forgot-password"]; // Replace with your routes

// Replace with your default login redirect URL
const DEFAULT_LOGIN_REDIRECT = "/auth/login";

// Middleware function
export async function middleware(request: NextRequest) {
  let response = NextResponse.next({
    request: {
      headers: request.headers,
    },
  });

  const supabase = createServerClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
    cookies: {
      get(name: string) {
        return request.cookies.get(name)?.value;
      },
      set(name: string, value: string, options: CookieOptions) {
        request.cookies.set({
          name,
          value,
          ...options,
        });
        response = NextResponse.next({
          request: {
            headers: request.headers,
          },
        });
        response.cookies.set({
          name,
          value,
          ...options,
        });
      },
      remove(name: string, options: CookieOptions) {
        request.cookies.set({
          name,
          value: "",
          ...options,
        });
        response = NextResponse.next({
          request: {
            headers: request.headers,
          },
        });
        response.cookies.set({
          name,
          value: "",
          ...options,
        });
      },
    },
  });

  // Get session data
  const { data: sessionData } = await supabase.auth.getSession();
  const url = new URL(request.url);
  const isAuthRoute = authRoutes.includes(url.pathname);

  // Handle active user check and first-time user redirect
  if (sessionData?.session) {
    const { data, error } = await supabase
      .from("users")
      .select("active, first_time_login") 
      .eq("id", sessionData.session.user.id)
      .maybeSingle();

    if (error) {
      await supabase.auth.signOut();
    } else if (data?.active === false) {
      toast.error(
        "You don't have permission to access the app. Contact your administrator"
      );
      await supabase.auth.signOut();
      return NextResponse.redirect(new URL("/auth/login", request.url));
    } else {
      // User is active
      if (isAuthRoute) {
        return NextResponse.redirect(new URL("/dashboard", request.url));
      }

      // Check for first-time user
      if (data?.first_time_login) {
        return NextResponse.redirect(
          new URL("/dashboard/settings", request.url)
        );
      }
    }
  }

  // Handle unauthenticated users on protected paths
  if (
    !sessionData?.session &&
    protectedPaths.some((path) => url.pathname.startsWith(path))
  ) {
    return NextResponse.redirect(
      new URL(`/auth/login?next=${url.pathname}`, request.url)
    );
  }

  // Return modified response
  return response;
}

// Matcher configuration
export const config = {
  matcher: [
    "/((?!_next/static|_next/image|favicon.ico).*)",
    "/",
    "/(api|trpc)(.*)",
  ],
};
Leave a Comment