-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthContext.js
More file actions
163 lines (141 loc) · 4.24 KB
/
Copy pathAuthContext.js
File metadata and controls
163 lines (141 loc) · 4.24 KB
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
import React, { createContext, useContext, useEffect, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { supabase } from '@services/supabaseClient';
export const AuthContext = createContext(null);
const AUTH_BOOTSTRAP_TIMEOUT_MS = 3500;
function syncAutoRefresh(activeSession) {
if (activeSession) {
supabase.auth.startAutoRefresh();
} else {
supabase.auth.stopAutoRefresh();
}
}
function withTimeout(promise, timeoutMs, timeoutMessage) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(timeoutMessage));
}, timeoutMs);
promise
.then(value => {
clearTimeout(timer);
resolve(value);
})
.catch(error => {
clearTimeout(timer);
reject(error);
});
});
}
/**
* Clear all offline cache on logout
*/
async function clearOfflineCache() {
try {
// Clear function cache
await AsyncStorage.removeItem('functions_cache');
// Clear categories cache
await AsyncStorage.removeItem('categories_cache');
// Clear any other offline data
await AsyncStorage.removeItem('offline_queue');
console.log('[AuthContext] Offline cache cleared on logout');
} catch (err) {
console.error('[AuthContext] Failed to clear offline cache:', err);
}
}
export function AuthProvider({ children }) {
const [session, setSession] = useState(null);
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
// Initialize session on app load and subscribe to auth changes
useEffect(() => {
let authListener;
let isMounted = true;
const initAuth = async () => {
authListener = supabase.auth.onAuthStateChange((event, newSession) => {
console.log('[AuthContext] Auth state change event:', event);
// Handle password recovery event
if (event === 'PASSWORD_RECOVERY') {
console.log('[AuthContext] PASSWORD_RECOVERY event detected');
// Navigation to ResetPasswordScreen will be handled by ResetPasswordScreen component
// watching onAuthStateChange
}
syncAutoRefresh(newSession);
if (!isMounted) return;
setSession(newSession);
setUser(newSession?.user || null);
}).data?.subscription;
try {
const { data, error } = await withTimeout(
supabase.auth.getSession(),
AUTH_BOOTSTRAP_TIMEOUT_MS,
'Supabase auth bootstrap timeout'
);
if (error) throw error;
const currentSession = data?.session || null;
syncAutoRefresh(currentSession);
if (!isMounted) return;
setSession(currentSession);
setUser(currentSession?.user || null);
} catch (err) {
console.warn('Auth init fallback to guest:', err?.message || err);
syncAutoRefresh(null);
if (!isMounted) return;
setSession(null);
setUser(null);
} finally {
if (isMounted) {
setLoading(false);
}
}
};
initAuth();
return () => {
isMounted = false;
if (authListener) {
authListener.unsubscribe();
}
};
}, []);
const signIn = async (email, password) => {
const { data, error } = await supabase.auth.signInWithPassword({ email, password });
if (error) throw error;
syncAutoRefresh(data.session);
setSession(data.session);
setUser(data.session?.user || null);
return data;
};
const signUp = async (email, password) => {
const { data, error } = await supabase.auth.signUp({ email, password });
if (error) throw error;
syncAutoRefresh(data.session);
setSession(data.session);
setUser(data.session?.user || null);
return data;
};
const signOut = async () => {
const { error } = await supabase.auth.signOut();
if (error) throw error;
// Clear offline cache on logout
await clearOfflineCache();
syncAutoRefresh(null);
setSession(null);
setUser(null);
};
return (
<AuthContext.Provider
value={{
session,
user,
loading,
signIn,
signUp,
signOut,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
return useContext(AuthContext);
}