149 lines
6.5 KiB
TypeScript
149 lines
6.5 KiB
TypeScript
import { Form, type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, redirect, useLoaderData, useNavigation } from "react-router";
|
|
import { useTranslation } from "react-i18next";
|
|
|
|
import { AuthShell } from "~/components/auth/AuthShell";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { TELEPHONY_PERMISSIONS, loadTelephonyContext, requireTelephonyPermission } from "~/modules/telephony/routes/telephonyAccess.server";
|
|
import { telephonyNotFoundResponse, telephonySettingsPath } from "~/modules/telephony/routes/telephonyRoutePaths";
|
|
import { AircallConnectError, buildAircallInstallUrl } from "~/modules/telephony/services/AircallConnectionService.server";
|
|
import { Button } from "~/ui/components/Button";
|
|
import { LinkButton } from "~/ui/components/LinkButton";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import { getMyTenants } from "~/utils/db/tenants.db.server";
|
|
import { ProviderOAuthCallbackAccessError, runAuthenticatedProviderOAuthCallback } from "~/utils/integrations/providerOAuthCallbackAccess.server";
|
|
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
|
|
|
const AIRCALL_INSTALL_PATH = "/integrations/aircall/oauth/install";
|
|
|
|
type LoaderData =
|
|
| { readonly mode: "confirm"; readonly tenantSlug: string; readonly settingsHref: string; readonly title: string }
|
|
| {
|
|
readonly mode: "entry";
|
|
readonly authenticated: boolean;
|
|
readonly loginHref: string;
|
|
readonly tenants: readonly { readonly id: string; readonly name: string; readonly slug: string }[];
|
|
readonly title: string;
|
|
};
|
|
|
|
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
|
const { t } = await getTranslations(request);
|
|
const tenantSlug = new URL(request.url).searchParams.get("tenant")?.trim() ?? "";
|
|
if (!tenantSlug) {
|
|
const session = await getUserInfo(request);
|
|
const tenants = session.userId ? (await getMyTenants(session.userId)).map((tenant) => ({ id: tenant.id, name: tenant.name, slug: tenant.slug })) : [];
|
|
return Response.json({
|
|
mode: "entry",
|
|
authenticated: Boolean(session.userId),
|
|
loginHref: `/login?redirectTo=${encodeURIComponent(AIRCALL_INSTALL_PATH)}`,
|
|
tenants,
|
|
title: `${t("telephony.oauth.install.title")} | ${process.env.APP_NAME}`,
|
|
} satisfies LoaderData);
|
|
}
|
|
if (tenantSlug.length > 256) throw telephonyNotFoundResponse();
|
|
|
|
const ctx = await loadTelephonyContext({
|
|
request,
|
|
params: { tenant: tenantSlug },
|
|
requireModule: true,
|
|
});
|
|
requireTelephonyPermission(ctx, TELEPHONY_PERMISSIONS.manage);
|
|
return Response.json({
|
|
mode: "confirm",
|
|
tenantSlug,
|
|
settingsHref: telephonySettingsPath(tenantSlug),
|
|
title: `${t("telephony.oauth.install.title")} | ${process.env.APP_NAME}`,
|
|
} satisfies LoaderData);
|
|
};
|
|
|
|
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
|
|
|
export const action = async ({ request }: ActionFunctionArgs) => {
|
|
const form = await request.formData();
|
|
await validateCSRFToken(request, { formData: form });
|
|
if (form.get("intent") !== "connect") throw telephonyNotFoundResponse();
|
|
|
|
const tenantSlug = (new URL(request.url).searchParams.get("tenant") ?? form.get("tenant")?.toString() ?? "").trim();
|
|
if (!tenantSlug || tenantSlug.length > 256) throw telephonyNotFoundResponse();
|
|
|
|
const ctx = await loadTelephonyContext({
|
|
request,
|
|
params: { tenant: tenantSlug },
|
|
requireModule: true,
|
|
});
|
|
requireTelephonyPermission(ctx, TELEPHONY_PERMISSIONS.manage);
|
|
|
|
try {
|
|
const authorizationUrl = await runAuthenticatedProviderOAuthCallback({
|
|
request,
|
|
tenantId: ctx.tenantId,
|
|
userId: ctx.userId,
|
|
callback: () => buildAircallInstallUrl({ tenantId: ctx.tenantId, tenantSlug, userId: ctx.userId }),
|
|
});
|
|
return redirect(authorizationUrl);
|
|
} catch (error) {
|
|
if (error instanceof ProviderOAuthCallbackAccessError) throw telephonyNotFoundResponse();
|
|
if (error instanceof AircallConnectError) {
|
|
return redirect(`${telephonySettingsPath(tenantSlug)}?aircall=error`);
|
|
}
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
export default function AircallOAuthInstallRoute() {
|
|
const data = useLoaderData<LoaderData>();
|
|
const { csrf } = useRootData();
|
|
const { t } = useTranslation();
|
|
const navigation = useNavigation();
|
|
|
|
if (data.mode === "entry") {
|
|
if (!data.authenticated) {
|
|
return (
|
|
<AuthShell title={t("telephony.oauth.install.title")} subtitle={t("telephony.oauth.install.loginBody")} dataUiId="ui.telephony.oauth.install">
|
|
<Button onClick={() => window.location.assign(data.loginHref)}>{t("telephony.oauth.install.login")}</Button>
|
|
</AuthShell>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<AuthShell title={t("telephony.oauth.install.title")} subtitle={t("telephony.oauth.install.selectTenantBody")} dataUiId="ui.telephony.oauth.install">
|
|
{data.tenants.length > 0 ? (
|
|
<div className="flex w-full flex-col gap-2" data-ui-id="ui.telephony.oauth.install.tenants">
|
|
{data.tenants.map((tenant) => (
|
|
<Form method="post" key={tenant.id} className="w-full">
|
|
<input type="hidden" name="csrf" value={csrf ?? ""} readOnly />
|
|
<input type="hidden" name="intent" value="connect" readOnly />
|
|
<input type="hidden" name="tenant" value={tenant.slug} readOnly />
|
|
<Button type="submit" variant="secondary" className="w-full" loading={navigation.state !== "idle"} disabled={navigation.state !== "idle"}>
|
|
{tenant.name}
|
|
</Button>
|
|
</Form>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
|
|
{t("telephony.oauth.install.noTenants")}
|
|
</span>
|
|
)}
|
|
</AuthShell>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<AuthShell title={t("telephony.oauth.install.title")} subtitle={t("telephony.oauth.install.confirmBody")} dataUiId="ui.telephony.oauth.install">
|
|
<Form method="post" className="flex w-full flex-col gap-3">
|
|
<input type="hidden" name="csrf" value={csrf ?? ""} readOnly />
|
|
<input type="hidden" name="intent" value="connect" readOnly />
|
|
<Button type="submit" loading={navigation.state !== "idle"} disabled={navigation.state !== "idle"}>
|
|
{t("telephony.oauth.install.continue")}
|
|
</Button>
|
|
</Form>
|
|
<LinkButton onClick={() => window.location.assign(data.settingsHref)}>{t("telephony.actions.cancel")}</LinkButton>
|
|
</AuthShell>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|