Browse Source

fix: resolve login redirect issue by using Supabase SDK for session validation

The login was failing because AuthContext was trying to call a non-existent
/auth/check Edge Function endpoint. This caused check_auth to fail and
redirect users back to the home page after login.

Changes:
- Replace custom /auth/check API calls with Supabase SDK getSession()
- Update check_auth to use supabase.auth.getSession() for validation
- Update periodic session check to use Supabase SDK
- Remove unused API_URL import
- Fix TypeScript type for check_auth to accept null target_path

This fixes the authentication flow:
1. User logs in → session stored
2. check_auth validates session via Supabase SDK
3. User successfully navigates to dashboard

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Fszontagh 4 months ago
parent
commit
40dbbb2ba6
1 changed files with 41 additions and 76 deletions
  1. 41 76
      shopcall.ai-main/src/components/context/AuthContext.tsx

+ 41 - 76
shopcall.ai-main/src/components/context/AuthContext.tsx

@@ -3,9 +3,6 @@ import { useEffect } from 'react';
 import { useNavigate } from "react-router-dom";
 import { supabase } from '@/lib/supabase';
 
-// Get API URL from environment variables (for backward compatibility)
-const API_URL = import.meta.env.VITE_API_URL || 'https://ztklqodcdjeqpsvhlpud.supabase.co/functions/v1';
-
 interface User {
     email: string;
     password: string;
@@ -16,7 +13,7 @@ interface AuthContextType {
     loading: boolean;
     login: (user_login_data: User) => void;
     logout: () => void;
-    check_auth: (target_path: string) => void;
+    check_auth: (target_path: string | null) => void;
     authStep: string;
 }
 
@@ -38,34 +35,11 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
                 return;
             }
 
-            const session_data = localStorage.getItem("session_data");
-
-            if (!session_data) {
-                // Session data missing, force logout
-                handleSessionExpired();
-                return;
-            }
-
             try {
-                const readable_session_data = JSON.parse(session_data);
-
-                if (!readable_session_data.success || !readable_session_data.session?.access_token) {
-                    handleSessionExpired();
-                    return;
-                }
-
-                // Validate token with backend
-                const check_auth_response = await fetch(`${API_URL}/auth/check`, {
-                    method: "GET",
-                    headers: {
-                        "Content-Type": "application/json",
-                        "Authorization": `Bearer ${readable_session_data.session.access_token}`,
-                    }
-                });
-
-                const check_auth_response_json = await check_auth_response.json();
+                // Use Supabase SDK to validate session
+                const { data: { session }, error } = await supabase.auth.getSession();
 
-                if (!check_auth_response_json.success) {
+                if (error || !session) {
                     // Session expired or invalid
                     handleSessionExpired();
                 }
@@ -99,63 +73,54 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
         };
     }, [isAuthenticated]);
     
-    const check_auth = async(target_path: string) => {
+    const check_auth = async(target_path: string | null) => {
         setLoading(true);
         setAuthStep("Checking session");
-        
-        const session_data = localStorage.getItem("session_data");
-        
-        if (session_data) {
-            const readable_session_data = JSON.parse(session_data);
-            if (readable_session_data.success) {
-                try {
-                    setAuthStep("Validating token");
-                    const check_auth_response = await fetch(`${API_URL}/auth/check`, {
-                        method: "GET",
-                        headers: {
-                            "Content-Type": "application/json",
-                            "Authorization": `Bearer ${readable_session_data.session.access_token}`,
-                        }
-                    });
-                    const check_auth_response_json = await check_auth_response.json();
-                    // console.log(check_auth_response_json.success);
-                    if (check_auth_response_json.success) {
-                        setAuthStep("Authentication successful");
-                        setIsAuthenticated(true);
-                        localStorage.setItem('IsAuthenticated', 'true');
-                        if (target_path) {
-                            navigate(target_path);
-                        }
-                    } else {
-                        // Session expired - clear state and redirect to landing page with full refresh
-                        setAuthStep("Session expired");
-                        localStorage.removeItem("session_data");
-                        localStorage.setItem('IsAuthenticated', 'false');
-                        setIsAuthenticated(false);
-                        window.location.href = '/';
-                    }
-                } catch (error) {
-                    console.error("Auth check failed:", error);
-                    setAuthStep("Connection failed");
-                    localStorage.removeItem("session_data");
-                    localStorage.setItem('IsAuthenticated', 'false');
-                    setIsAuthenticated(false);
-                    window.location.href = '/';
+
+        try {
+            // Use Supabase SDK to check session validity
+            setAuthStep("Validating token");
+            const { data: { session }, error } = await supabase.auth.getSession();
+
+            if (error) {
+                console.error("Session check error:", error);
+                throw error;
+            }
+
+            if (session) {
+                // Session is valid
+                setAuthStep("Authentication successful");
+                setIsAuthenticated(true);
+                localStorage.setItem('IsAuthenticated', 'true');
+
+                // Store session data in expected format
+                const session_data = {
+                    success: true,
+                    user: session.user,
+                    session: session
+                };
+                localStorage.setItem("session_data", JSON.stringify(session_data));
+
+                if (target_path) {
+                    navigate(target_path);
                 }
             } else {
-                setAuthStep("Invalid session");
+                // No valid session - redirect to login
+                setAuthStep("No session found");
                 localStorage.removeItem("session_data");
                 localStorage.setItem('IsAuthenticated', 'false');
                 setIsAuthenticated(false);
-                window.location.href = '/';
+                navigate("/login");
             }
-        } else {
-            setAuthStep("No session found");
-            setIsAuthenticated(false);
+        } catch (error) {
+            console.error("Auth check failed:", error);
+            setAuthStep("Connection failed");
+            localStorage.removeItem("session_data");
             localStorage.setItem('IsAuthenticated', 'false');
+            setIsAuthenticated(false);
             navigate("/login");
         }
-        
+
         setLoading(false);
     }