forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAuth.ts
More file actions
92 lines (82 loc) · 2.37 KB
/
Copy pathuseAuth.ts
File metadata and controls
92 lines (82 loc) · 2.37 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
'use client';
import { useEffect, useState } from 'react';
import { User } from 'firebase/auth';
import { onAuthStateChange, signInWithGoogle, signOutUser } from '../lib/firebase';
interface UseAuthReturn {
user: User | null;
loading: boolean;
signIn: () => Promise<User | null>;
signOut: () => Promise<void>;
isAuthenticated: boolean;
authError: string | null;
}
export const useAuth = (): UseAuthReturn => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [authError, setAuthError] = useState<string | null>(null);
useEffect(() => {
console.log('🔧 Setting up auth state listener...');
let unsubscribe: (() => void) | null = null;
try {
unsubscribe = onAuthStateChange((user: User | null) => {
setUser(user);
setLoading(false);
setAuthError(null); // Clear any previous errors
});
} catch (error) {
const e = error as Error;
console.error('❌ Firebase auth initialization failed:', e.message);
setAuthError(e.message);
setLoading(false);
// Don't crash the app - just set user to null and continue
setUser(null);
}
return () => {
console.log('🧹 Cleaning up auth state listener...');
try {
if (unsubscribe) {
unsubscribe();
}
} catch (error) {
console.error('❌ Error cleaning up auth listener:', (error as Error).message);
}
};
}, []);
const signIn = async (): Promise<User | null> => {
try {
setLoading(true);
setAuthError(null);
const user = await signInWithGoogle();
return user;
} catch (error) {
const e = error as Error;
console.error('❌ Sign in failed:', e);
setAuthError(e.message || 'Sign in failed');
return null; // Don't throw - return null instead
} finally {
setLoading(false);
}
};
const signOut = async (): Promise<void> => {
try {
setLoading(true);
setAuthError(null);
await signOutUser();
} catch (error) {
const e = error as Error;
console.error('❌ Sign out failed:', e);
setAuthError(e.message || 'Sign out failed');
// Don't throw - just log the error
} finally {
setLoading(false);
}
};
return {
user,
loading,
signIn,
signOut,
isAuthenticated: !!user,
authError,
};
};