({
requireAuth,
inputRef,
setInputFocused,
resetChatStore,
}: UseAuthStateOptions)
| 31 | } |
| 32 | |
| 33 | export const useAuthState = ({ |
| 34 | requireAuth, |
| 35 | inputRef, |
| 36 | setInputFocused, |
| 37 | resetChatStore, |
| 38 | }: UseAuthStateOptions) => { |
| 39 | const authQuery = useAuthQuery() |
| 40 | const logoutMutation = useLogoutMutation() |
| 41 | const { resetLoginState } = useLoginStore() |
| 42 | |
| 43 | const initialAuthState = requireAuth === null ? null : !requireAuth |
| 44 | const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>( |
| 45 | initialAuthState, |
| 46 | ) |
| 47 | const [user, setUser] = useState<User | null>(null) |
| 48 | |
| 49 | // Update authentication state when requireAuth changes |
| 50 | useEffect(() => { |
| 51 | if (requireAuth === null) { |
| 52 | return |
| 53 | } |
| 54 | setIsAuthenticated(!requireAuth) |
| 55 | }, [requireAuth]) |
| 56 | |
| 57 | // Update authentication state based on query results |
| 58 | useEffect(() => { |
| 59 | if (authQuery.isSuccess && authQuery.data) { |
| 60 | setIsAuthenticated(true) |
| 61 | if (!user) { |
| 62 | const userCredentials = getUserCredentials() |
| 63 | const userData: User = { |
| 64 | id: authQuery.data.id, |
| 65 | name: userCredentials?.name || '', |
| 66 | email: authQuery.data.email || '', |
| 67 | authToken: userCredentials?.authToken || '', |
| 68 | } |
| 69 | setUser(userData) |
| 70 | setAuthLoggerContext({ |
| 71 | userId: authQuery.data.id, |
| 72 | email: authQuery.data.email || '', |
| 73 | }) |
| 74 | } |
| 75 | } else if (authQuery.isError) { |
| 76 | setIsAuthenticated(false) |
| 77 | setUser(null) |
| 78 | clearAuthLoggerContext() |
| 79 | } |
| 80 | }, [authQuery.isSuccess, authQuery.isError, authQuery.data, user]) |
| 81 | |
| 82 | // Handle successful login |
| 83 | const handleLoginSuccess = useCallback( |
| 84 | (loggedInUser: User) => { |
| 85 | // Track successful login |
| 86 | trackEvent(AnalyticsEvent.LOGIN, { |
| 87 | userId: loggedInUser.id, |
| 88 | hasEmail: Boolean(loggedInUser.email), |
| 89 | hasName: Boolean(loggedInUser.name), |
| 90 | }) |
no test coverage detected