summaryrefslogtreecommitdiff
path: root/apps/mobile/contexts/AuthContext.tsx
blob: 6102433b9bf6539285d34b9f6e3e6cc7242c28c0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  useCallback,
  useMemo,
  type ReactNode,
} from 'react';
import { AppState, type AppStateStatus } from 'react-native';
import type { Session, User, AuthChangeEvent } from '@supabase/supabase-js';
import { supabase } from '../lib/supabase';
import { signIn as authSignIn, signOut as authSignOut, getSession } from '../lib/auth';

/**
 * Auth context state interface
 */
interface AuthState {
  user: User | null;
  session: Session | null;
  isLoading: boolean;
  isInitialized: boolean;
  error: string | null;
}

/**
 * Auth context actions interface
 */
interface AuthActions {
  signIn: (email: string, password: string) => Promise<boolean>;
  signOut: () => Promise<void>;
  clearError: () => void;
}

/**
 * Combined auth context type
 */
type AuthContextType = AuthState & AuthActions;

/**
 * Default auth state
 */
const defaultAuthState: AuthState = {
  user: null,
  session: null,
  isLoading: true,
  isInitialized: false,
  error: null,
};

/**
 * Auth context with default values
 */
const AuthContext = createContext<AuthContextType | undefined>(undefined);

/**
 * Props for AuthProvider component
 */
interface AuthProviderProps {
  children: ReactNode;
}

/**
 * AuthProvider component that manages authentication state
 * - Initializes auth state on mount
 * - Listens to auth state changes
 * - Auto-refreshes session when app comes to foreground
 * - Provides auth actions via context
 */
export function AuthProvider({ children }: AuthProviderProps) {
  const [state, setState] = useState<AuthState>(defaultAuthState);

  /**
   * Update auth state with partial updates
   */
  const updateState = useCallback((updates: Partial<AuthState>) => {
    setState((prev) => ({ ...prev, ...updates }));
  }, []);

  /**
   * Initialize auth state by checking for existing session
   */
  const initialize = useCallback(async () => {
    try {
      const { session, error } = await getSession();

      if (error) {
        console.warn('Auth initialization warning:', error);
      }

      updateState({
        user: session?.user ?? null,
        session,
        isLoading: false,
        isInitialized: true,
        error: null,
      });
    } catch (error) {
      console.error('Auth initialization error:', error);
      updateState({
        user: null,
        session: null,
        isLoading: false,
        isInitialized: true,
        error: error instanceof Error ? error.message : 'Failed to initialize auth',
      });
    }
  }, [updateState]);

  /**
   * Sign in with email and password
   */
  const signIn = useCallback(
    async (email: string, password: string): Promise<boolean> => {
      updateState({ isLoading: true, error: null });

      const result = await authSignIn(email, password);

      if (result.success && result.user && result.session) {
        updateState({
          user: result.user,
          session: result.session,
          isLoading: false,
          error: null,
        });
        return true;
      }

      updateState({
        isLoading: false,
        error: result.error || 'Sign in failed',
      });
      return false;
    },
    [updateState]
  );

  /**
   * Sign out the current user
   */
  const signOut = useCallback(async () => {
    updateState({ isLoading: true, error: null });

    const result = await authSignOut();

    if (result.success) {
      updateState({
        user: null,
        session: null,
        isLoading: false,
        error: null,
      });
    } else {
      updateState({
        isLoading: false,
        error: result.error || 'Sign out failed',
      });
    }
  }, [updateState]);

  /**
   * Clear any auth errors
   */
  const clearError = useCallback(() => {
    updateState({ error: null });
  }, [updateState]);

  /**
   * Handle app state changes (foreground/background)
   * Refresh session when app comes to foreground
   */
  useEffect(() => {
    const handleAppStateChange = async (nextAppState: AppStateStatus) => {
      if (nextAppState === 'active' && state.session) {
        // App came to foreground, refresh the session
        try {
          const { data, error } = await supabase.auth.refreshSession();
          if (error) {
            console.warn('Session refresh warning:', error.message);
          } else if (data.session) {
            updateState({
              session: data.session,
              user: data.session.user,
            });
          }
        } catch (error) {
          console.error('Session refresh error:', error);
        }
      }
    };

    const subscription = AppState.addEventListener('change', handleAppStateChange);

    return () => {
      subscription.remove();
    };
  }, [state.session, updateState]);

  /**
   * Listen to Supabase auth state changes
   */
  useEffect(() => {
    const {
      data: { subscription },
    } = supabase.auth.onAuthStateChange(
      (event: AuthChangeEvent, session: Session | null) => {
        console.log('Auth state changed:', event);

        switch (event) {
          case 'SIGNED_IN':
            updateState({
              user: session?.user ?? null,
              session,
              isLoading: false,
              error: null,
            });
            break;
          case 'SIGNED_OUT':
            updateState({
              user: null,
              session: null,
              isLoading: false,
              error: null,
            });
            break;
          case 'TOKEN_REFRESHED':
            updateState({
              session,
              user: session?.user ?? null,
            });
            break;
          case 'USER_UPDATED':
            updateState({
              user: session?.user ?? null,
            });
            break;
          case 'PASSWORD_RECOVERY':
          case 'MFA_CHALLENGE_VERIFIED':
            // Handle other events as needed
            break;
          default:
            // INITIAL_SESSION and other events
            break;
        }
      }
    );

    return () => {
      subscription.unsubscribe();
    };
  }, [updateState]);

  /**
   * Initialize auth on mount
   */
  useEffect(() => {
    initialize();
  }, [initialize]);

  /**
   * Memoized context value
   */
  const value = useMemo<AuthContextType>(
    () => ({
      ...state,
      signIn,
      signOut,
      clearError,
    }),
    [state, signIn, signOut, clearError]
  );

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

/**
 * Hook to access auth context
 * Must be used within an AuthProvider
 */
export function useAuth(): AuthContextType {
  const context = useContext(AuthContext);

  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }

  return context;
}

/**
 * Hook to check if user is authenticated
 */
export function useIsAuthenticated(): boolean {
  const { session } = useAuth();
  return session !== null;
}

export type { AuthContextType, AuthState, AuthActions };