feat: implement auth flow and app initialization
This commit is contained in:
55
src/providers/AppInitializer.tsx
Normal file
55
src/providers/AppInitializer.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client';
|
||||
|
||||
import { initializeAuthenticatedApp } from '@/services/initializer.service';
|
||||
import { useAppStore } from '@/store/app.store';
|
||||
import { useAuthStore } from '@/store/auth.store';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function AppInitializer({ children }: { children: ReactNode }) {
|
||||
const accessToken = useAuthStore((state) => state.accessToken);
|
||||
const logout = useAuthStore((state) => state.logout);
|
||||
const user = useAppStore((state) => state.user);
|
||||
const setLoading = useAppStore((state) => state.setLoading);
|
||||
const setLoaded = useAppStore((state) => state.setLoaded);
|
||||
const setLoadError = useAppStore((state) => state.setLoadError);
|
||||
const clearApp = useAppStore((state) => state.clear);
|
||||
|
||||
useEffect(() => {
|
||||
let isActive = true;
|
||||
|
||||
const initialize = async () => {
|
||||
if (!accessToken || user) {
|
||||
console.debug('[auth] app-init:skip', {
|
||||
hasToken: !!accessToken,
|
||||
hasUser: !!user,
|
||||
});
|
||||
setLoaded();
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading();
|
||||
console.debug('[auth] app-init:start');
|
||||
|
||||
try {
|
||||
await initializeAuthenticatedApp();
|
||||
console.debug('[auth] app-init:success');
|
||||
} catch {
|
||||
if (isActive) {
|
||||
console.debug('[auth] app-init:failed, logging out');
|
||||
logout();
|
||||
clearApp();
|
||||
setLoadError();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
initialize();
|
||||
|
||||
return () => {
|
||||
isActive = false;
|
||||
};
|
||||
}, [accessToken, clearApp, logout, setLoaded, setLoadError, setLoading, user]);
|
||||
|
||||
return children;
|
||||
}
|
||||
Reference in New Issue
Block a user