Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/integrations.google.oauth.callback.tsx
T
2026-07-08 16:15:37 +02:00

55 lines
2.5 KiB
TypeScript

// AK-P16a · Google OAuth callback (M25 Block C). NOT tenant-scoped — EXT-10
// registered exactly this URI; the tenant + user travel in the signed `state`.
// Exchanges the code, seals the tokens, upserts the per-user connection, then
// redirects back to the tenant's calendar settings. CSRF/replay is bounded by the
// HMAC-signed, 10-minute state token (verified inside completeOAuthCallback).
import { type LoaderFunctionArgs, redirect } from "react-router";
import { completeOAuthCallback } from "~/modules/calendar/services/CalendarConnectionService.server";
import { syncConnection } from "~/modules/calendar/services/CalendarSyncService.server";
import { verifyCalendarOAuthState } from "~/modules/calendar/services/oauthState.server";
import { calendarConnectionsPath } from "~/modules/calendar/routes/calendarRoutePaths";
import ServerError from "~/components/ui/errors/ServerError";
function settingsRedirect(state: string | null, flag: "connected" | "error"): Response {
// Best-effort: recover the tenant slug from the (verified) state so the user
// lands back on their own settings page even on the error path.
if (state) {
const verified = verifyCalendarOAuthState(state);
if (verified.ok) {
return redirect(`${calendarConnectionsPath(verified.payload.tenantSlug)}?calendar=${flag}`);
}
}
return redirect(`/?calendar=${flag}`);
}
export const loader = async ({ request }: LoaderFunctionArgs) => {
const url = new URL(request.url);
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const providerError = url.searchParams.get("error");
if (providerError || !code || !state) {
return settingsRedirect(state, "error");
}
try {
const { tenantSlug, tenantId, connectionId } = await completeOAuthCallback({ code, state });
// Best-effort initial pull so the calendar is populated right after connect
// (M25 "Initial-Sync läuft"). A failure here must not break the connect — the
// webhook + cron will catch up; the connection is already persisted.
await syncConnection(tenantId, connectionId).catch(() => undefined);
return redirect(`${calendarConnectionsPath(tenantSlug)}?calendar=connected`);
} catch {
return settingsRedirect(state, "error");
}
};
export default function GoogleOAuthCallbackRoute() {
// The loader always redirects; this renders only if navigated to without flow.
return <main data-ui-id="ui.calendar.oauth.callback" />;
}
export function ErrorBoundary() {
return <ServerError />;
}