mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-21 07:11:11 -05:00
feat: Implement auth logging and session verification optimizations
This commit is contained in:
@@ -3,6 +3,7 @@ import type { User, Session } from '@supabase/supabase-js';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import type { Profile } from '@/types/database';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { authLog, authWarn, authError } from '@/lib/authLogger';
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
@@ -36,6 +37,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
const previousEmailRef = useRef<string | null>(null);
|
||||
const loadingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const loadingStateRef = useRef(loading);
|
||||
const lastVisibilityVerificationRef = useRef<number>(Date.now());
|
||||
|
||||
const fetchProfile = async (userId: string, retryCount = 0, onComplete?: () => void) => {
|
||||
try {
|
||||
@@ -46,12 +48,12 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
.maybeSingle();
|
||||
|
||||
if (error && error.code !== 'PGRST116') {
|
||||
console.error('[Auth] Error fetching profile:', error);
|
||||
authError('[Auth] Error fetching profile:', error);
|
||||
|
||||
// Retry up to 3 times with exponential backoff
|
||||
if (retryCount < 3 && isMountedRef.current) {
|
||||
const delay = Math.pow(2, retryCount) * 1000; // 1s, 2s, 4s
|
||||
console.log(`[Auth] Retrying profile fetch in ${delay}ms (attempt ${retryCount + 1}/3)`);
|
||||
authLog(`[Auth] Retrying profile fetch in ${delay}ms (attempt ${retryCount + 1}/3)`);
|
||||
setTimeout(() => {
|
||||
if (isMountedRef.current) {
|
||||
fetchProfile(userId, retryCount + 1, onComplete);
|
||||
@@ -62,7 +64,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
|
||||
// All retries exhausted - complete anyway
|
||||
if (isMountedRef.current) {
|
||||
console.warn('[Auth] Profile fetch failed after 3 retries');
|
||||
authWarn('[Auth] Profile fetch failed after 3 retries');
|
||||
setProfile(null);
|
||||
onComplete?.();
|
||||
}
|
||||
@@ -76,7 +78,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
onComplete?.();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Auth] Error fetching profile:', error);
|
||||
authError('[Auth] Error fetching profile:', error);
|
||||
|
||||
// Retry logic for network errors
|
||||
if (retryCount < 3 && isMountedRef.current) {
|
||||
@@ -112,7 +114,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
const { data: { session }, error } = await supabase.auth.getSession();
|
||||
|
||||
if (error) {
|
||||
console.error('[Auth] Session verification failed:', error);
|
||||
authError('[Auth] Session verification failed:', error);
|
||||
setSessionError(error.message);
|
||||
if (updateLoadingState && isMountedRef.current) {
|
||||
setLoading(false);
|
||||
@@ -121,14 +123,14 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
console.log('[Auth] No active session found');
|
||||
authLog('[Auth] No active session found');
|
||||
if (updateLoadingState && isMountedRef.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log('[Auth] Session verified:', session.user.email);
|
||||
authLog('[Auth] Session verified:', session.user.email);
|
||||
sessionVerifiedRef.current = true;
|
||||
|
||||
// Update state if session was found but not set
|
||||
@@ -142,7 +144,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('[Auth] Session verification error:', error);
|
||||
authError('[Auth] Session verification error:', error);
|
||||
if (updateLoadingState && isMountedRef.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -153,17 +155,17 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
// Keep loading state ref in sync
|
||||
useEffect(() => {
|
||||
loadingStateRef.current = loading;
|
||||
console.log('[Auth] Loading state changed:', loading);
|
||||
authLog('[Auth] Loading state changed:', loading);
|
||||
}, [loading]);
|
||||
|
||||
useEffect(() => {
|
||||
console.log('[Auth] Initializing auth provider');
|
||||
authLog('[Auth] Initializing auth provider');
|
||||
|
||||
// CRITICAL: Set up listener FIRST to catch all events
|
||||
const {
|
||||
data: { subscription },
|
||||
} = supabase.auth.onAuthStateChange((event, session) => {
|
||||
console.log('[Auth] State change:', event, 'User:', session?.user?.email || 'none', 'Has session:', !!session);
|
||||
authLog('[Auth] State change:', event, 'User:', session?.user?.email || 'none', 'Has session:', !!session);
|
||||
|
||||
// Extract email info early for cleanup
|
||||
const currentEmail = session?.user?.email;
|
||||
@@ -177,18 +179,18 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
|
||||
// Update session and user state based on event
|
||||
if (event === 'SIGNED_IN' && session) {
|
||||
console.log('[Auth] SIGNED_IN detected, setting session and user');
|
||||
authLog('[Auth] SIGNED_IN detected, setting session and user');
|
||||
setSession(session);
|
||||
setUser(session.user);
|
||||
sessionVerifiedRef.current = true;
|
||||
} else if (event === 'INITIAL_SESSION') {
|
||||
if (session?.user) {
|
||||
console.log('[Auth] INITIAL_SESSION with user, setting session');
|
||||
authLog('[Auth] INITIAL_SESSION with user, setting session');
|
||||
setSession(session);
|
||||
setUser(session.user);
|
||||
sessionVerifiedRef.current = true;
|
||||
} else {
|
||||
console.log('[Auth] INITIAL_SESSION with no user - setting loading to false');
|
||||
authLog('[Auth] INITIAL_SESSION with no user - setting loading to false');
|
||||
setSession(null);
|
||||
setUser(null);
|
||||
setProfile(null);
|
||||
@@ -198,7 +200,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
return; // Exit early, no need to fetch profile
|
||||
}
|
||||
} else if (event === 'SIGNED_OUT') {
|
||||
console.log('[Auth] SIGNED_OUT detected, clearing all state');
|
||||
authLog('[Auth] SIGNED_OUT detected, clearing all state');
|
||||
setSession(null);
|
||||
setUser(null);
|
||||
setProfile(null);
|
||||
@@ -261,7 +263,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating Novu after email confirmation:', error);
|
||||
authError('Error updating Novu after email confirmation:', error);
|
||||
} finally {
|
||||
novuUpdateTimeoutRef.current = null;
|
||||
}
|
||||
@@ -282,12 +284,12 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
|
||||
// Only wait for profile on initial auth events
|
||||
const shouldWaitForProfile = (event === 'SIGNED_IN' || event === 'INITIAL_SESSION');
|
||||
console.log('[Auth] Fetching profile, shouldWaitForProfile:', shouldWaitForProfile);
|
||||
authLog('[Auth] Fetching profile, shouldWaitForProfile:', shouldWaitForProfile);
|
||||
|
||||
profileFetchTimeoutRef.current = setTimeout(() => {
|
||||
fetchProfile(session.user.id, 0, () => {
|
||||
if (shouldWaitForProfile) {
|
||||
console.log('[Auth] Profile fetch complete, setting loading to false');
|
||||
authLog('[Auth] Profile fetch complete, setting loading to false');
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
@@ -296,7 +298,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
} else {
|
||||
// No session/user - clear profile and resolve loading
|
||||
setProfile(null);
|
||||
console.log('[Auth] No user, setting loading to false');
|
||||
authLog('[Auth] No user, setting loading to false');
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
@@ -304,7 +306,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
// THEN get initial session (this may trigger INITIAL_SESSION event)
|
||||
supabase.auth.getSession().then(({ data: { session }, error }) => {
|
||||
if (error) {
|
||||
console.error('[Auth] Initial session fetch error:', error);
|
||||
authError('[Auth] Initial session fetch error:', error);
|
||||
setSessionError(error.message);
|
||||
setLoading(false);
|
||||
return;
|
||||
@@ -312,13 +314,13 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
|
||||
// Note: onAuthStateChange will handle the INITIAL_SESSION event
|
||||
// This is just a backup in case the event doesn't fire
|
||||
console.log('[Auth] getSession completed, session exists:', !!session);
|
||||
authLog('[Auth] getSession completed, session exists:', !!session);
|
||||
});
|
||||
|
||||
// Add a STRONG safety timeout to force loading to resolve
|
||||
loadingTimeoutRef.current = setTimeout(() => {
|
||||
if (loadingStateRef.current) {
|
||||
console.warn('[Auth] ⚠️ SAFETY TIMEOUT: Forcing loading to false after 3 seconds');
|
||||
authWarn('[Auth] ⚠️ SAFETY TIMEOUT: Forcing loading to false after 3 seconds');
|
||||
setLoading(false);
|
||||
}
|
||||
}, 3000);
|
||||
@@ -326,23 +328,31 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
// Session verification fallback
|
||||
const verificationTimeout = setTimeout(() => {
|
||||
if (!sessionVerifiedRef.current) {
|
||||
console.log('[Auth] Session not verified after 2s, attempting manual verification');
|
||||
authLog('[Auth] Session not verified after 2s, attempting manual verification');
|
||||
verifySession();
|
||||
}
|
||||
}, 2000);
|
||||
|
||||
// Handle page visibility changes
|
||||
// Handle page visibility changes - only verify if inactive for >5 minutes
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
console.log('[Auth] Tab became visible, verifying session');
|
||||
verifySession();
|
||||
const timeSinceLastCheck = Date.now() - lastVisibilityVerificationRef.current;
|
||||
const FIVE_MINUTES = 5 * 60 * 1000;
|
||||
|
||||
if (timeSinceLastCheck > FIVE_MINUTES) {
|
||||
authLog('[Auth] Tab visible after 5+ minutes, verifying session');
|
||||
lastVisibilityVerificationRef.current = Date.now();
|
||||
verifySession();
|
||||
} else {
|
||||
authLog('[Auth] Tab visible, session recently verified, skipping');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
|
||||
return () => {
|
||||
console.log('[Auth] Cleaning up auth provider');
|
||||
authLog('[Auth] Cleaning up auth provider');
|
||||
isMountedRef.current = false;
|
||||
subscription.unsubscribe();
|
||||
clearTimeout(verificationTimeout);
|
||||
@@ -366,7 +376,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
||||
const signOut = async () => {
|
||||
const { error } = await supabase.auth.signOut();
|
||||
if (error) {
|
||||
console.error('Error signing out:', error);
|
||||
authError('Error signing out:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user