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
|
import { create } from 'zustand';
import type { Session, User, AuthChangeEvent } from '@supabase/supabase-js';
import { supabase } from '../lib/supabase';
import {
signIn as authSignIn,
signOut as authSignOut,
getSession,
refreshSession,
} from '../lib/auth';
/**
* Auth store state interface
*/
interface AuthState {
/** Current authenticated user */
user: User | null;
/** Current session */
session: Session | null;
/** Whether auth operations are in progress */
isLoading: boolean;
/** Whether the store has been initialized */
isInitialized: boolean;
/** Last auth error message */
error: string | null;
}
/**
* Auth store actions interface
*/
interface AuthActions {
/** Sign in with email and password */
signIn: (email: string, password: string) => Promise<boolean>;
/** Sign out the current user */
signOut: () => Promise<void>;
/** Initialize the auth store */
initialize: () => Promise<void>;
/** Refresh the current session */
refresh: () => Promise<void>;
/** Clear any auth errors */
clearError: () => void;
/** Set the auth state (for internal use) */
setAuth: (user: User | null, session: Session | null) => void;
}
/**
* Combined auth store type
*/
type AuthStore = AuthState & AuthActions;
/**
* Zustand store for authentication state management
*
* Usage:
* ```typescript
* import { useAuthStore } from './stores/authStore';
*
* // In component
* const { user, isLoading, signIn, signOut } = useAuthStore();
*
* // Or use selectors for performance
* const user = useAuthStore((state) => state.user);
* const signIn = useAuthStore((state) => state.signIn);
* ```
*/
export const useAuthStore = create<AuthStore>((set, get) => ({
// Initial state
user: null,
session: null,
isLoading: true,
isInitialized: false,
error: null,
/**
* Sign in with email and password
*/
signIn: async (email: string, password: string): Promise<boolean> => {
set({ isLoading: true, error: null });
const result = await authSignIn(email, password);
if (result.success && result.user && result.session) {
set({
user: result.user,
session: result.session,
isLoading: false,
error: null,
});
return true;
}
set({
isLoading: false,
error: result.error || 'Sign in failed',
});
return false;
},
/**
* Sign out the current user
*/
signOut: async (): Promise<void> => {
set({ isLoading: true, error: null });
const result = await authSignOut();
if (result.success) {
set({
user: null,
session: null,
isLoading: false,
error: null,
});
} else {
set({
isLoading: false,
error: result.error || 'Sign out failed',
});
}
},
/**
* Initialize the auth store by checking for existing session
*/
initialize: async (): Promise<void> => {
// Prevent re-initialization
if (get().isInitialized) {
return;
}
try {
const { session, error } = await getSession();
if (error) {
console.warn('Auth initialization warning:', error);
}
set({
user: session?.user ?? null,
session,
isLoading: false,
isInitialized: true,
error: null,
});
} catch (error) {
console.error('Auth initialization error:', error);
set({
user: null,
session: null,
isLoading: false,
isInitialized: true,
error: error instanceof Error ? error.message : 'Failed to initialize auth',
});
}
},
/**
* Refresh the current session
*/
refresh: async (): Promise<void> => {
const { session } = get();
if (!session) return;
try {
const result = await refreshSession();
if (result.session) {
set({
session: result.session,
user: result.session.user,
});
} else if (result.error) {
console.warn('Session refresh warning:', result.error);
}
} catch (error) {
console.error('Session refresh error:', error);
}
},
/**
* Clear any auth errors
*/
clearError: (): void => {
set({ error: null });
},
/**
* Set the auth state (for internal use by listeners)
*/
setAuth: (user: User | null, session: Session | null): void => {
set({ user, session, isLoading: false });
},
}));
/**
* Setup auth state listener
* Should be called once when the app initializes
*/
export function setupAuthListener(): () => void {
const {
data: { subscription },
} = supabase.auth.onAuthStateChange(
(event: AuthChangeEvent, session: Session | null) => {
console.log('Auth state changed:', event);
const { setAuth } = useAuthStore.getState();
switch (event) {
case 'SIGNED_IN':
case 'TOKEN_REFRESHED':
case 'USER_UPDATED':
setAuth(session?.user ?? null, session);
break;
case 'SIGNED_OUT':
setAuth(null, null);
break;
default:
break;
}
}
);
return () => {
subscription.unsubscribe();
};
}
/**
* Selector hooks for common auth state
*/
export const useUser = () => useAuthStore((state) => state.user);
export const useSession = () => useAuthStore((state) => state.session);
export const useIsLoading = () => useAuthStore((state) => state.isLoading);
export const useIsInitialized = () => useAuthStore((state) => state.isInitialized);
export const useAuthError = () => useAuthStore((state) => state.error);
export const useIsAuthenticated = () => useAuthStore((state) => state.session !== null);
|