Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

1.8 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { requirePermissions } from "@carbon/auth/auth.server";
import { Onshape } from "@carbon/ee";
import { beginOnshapeAuthorization } from "@carbon/ee/onshape.server";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
import { path } from "~/utils/path";

async function authorize(request: Request) {
  const { userId, companyId } = await requirePermissions(request, {
    update: "settings"
  });
  return beginOnshapeAuthorization(request, {
    integrationId: Onshape.id,
    userId,
    companyId
  });
}

export async function loader({ request }: LoaderFunctionArgs) {
  const started = await authorize(request);

  // `error` is an integration-errors code; the client sends it to the
  // integrations page, which renders the copy.
  if (!started.ok) {
    return data(
      { error: started.reason },
      { status: started.reason === "not-configured" ? 500 : 409 }
    );
  }

  return data(
    { url: started.url },
    { headers: { "Set-Cookie": started.cookie } }
  );
}

/**
 * The drawer's Reconnect action: the same authorization, answered as a
 * `redirectUrl`. With no popup opener the callback returns to the integrations
 * page, where a failure shows as the install-failure toast.
 */
export async function action({ request }: ActionFunctionArgs) {
  const started = await authorize(request);
  if (!started.ok) {
    return data({
      redirectUrl: `${path.to.integrations}?integration=${Onshape.id}&error=${started.reason}`
    });
  }
  return data(
    { redirectUrl: started.url },
    { headers: { "Set-Cookie": started.cookie } }
  );
}