website cleanup
This commit is contained in:
@@ -11,10 +11,11 @@ import {
|
||||
} from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
import type { AuthSession } from './AuthService';
|
||||
import type { SessionViewModel } from '@/lib/view-models/SessionViewModel';
|
||||
import { useServices } from '@/lib/services/ServiceProvider';
|
||||
|
||||
type AuthContextValue = {
|
||||
session: AuthSession | null;
|
||||
session: SessionViewModel | null;
|
||||
loading: boolean;
|
||||
login: (returnTo?: string) => void;
|
||||
logout: () => Promise<void>;
|
||||
@@ -24,33 +25,24 @@ type AuthContextValue = {
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
|
||||
interface AuthProviderProps {
|
||||
initialSession?: AuthSession | null;
|
||||
initialSession?: SessionViewModel | null;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function AuthProvider({ initialSession = null, children }: AuthProviderProps) {
|
||||
const router = useRouter();
|
||||
const [session, setSession] = useState<AuthSession | null>(initialSession);
|
||||
const { sessionService, authService } = useServices();
|
||||
const [session, setSession] = useState<SessionViewModel | null>(initialSession);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const fetchSession = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/auth/session', {
|
||||
method: 'GET',
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
setSession(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = (await res.json()) as { session: AuthSession | null };
|
||||
setSession(data.session ?? null);
|
||||
const current = await sessionService.getSession();
|
||||
setSession(current);
|
||||
} catch {
|
||||
setSession(null);
|
||||
}
|
||||
}, []);
|
||||
}, [sessionService]);
|
||||
|
||||
const refreshSession = useCallback(async () => {
|
||||
await fetchSession();
|
||||
@@ -79,17 +71,14 @@ export function AuthProvider({ initialSession = null, children }: AuthProviderPr
|
||||
const logout = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await fetch('/api/auth/logout', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
});
|
||||
await authService.logout();
|
||||
setSession(null);
|
||||
router.push('/');
|
||||
router.refresh();
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [router]);
|
||||
}, [authService, router]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
@@ -111,4 +100,4 @@ export function useAuth(): AuthContextValue {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user