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.

2.5 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 { carbon, respond } from "@carbon/api/carbon.server";
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
import { useCloseRoute } from "@carbon/react";
import { redirect } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import {
  apiKeyFields,
  apiKeyValidator
} from "~/modules/settings/settings.models";
import { getApiKey } from "~/modules/settings/settings.service";
import { ApiKeyForm } from "~/modules/settings/ui";
import { getParams, path } from "~/utils/path";

// The list holds only the rows scrolled so far, so the drawer reads its own key.
export async function loader({ request, params }: LoaderFunctionArgs) {
  const { client, companyId } = await requirePermissions(request, {
    update: "users"
  });

  const { id } = params;
  if (!id) throw new Error("Could not find id");

  const apiKey = await getApiKey(client, id, companyId);
  if (apiKey.error) {
    throw redirect(
      `${path.to.apiKeys}?${getParams(request)}`,
      await flash(request, error(apiKey.error, "Failed to load API key"))
    );
  }

  return { apiKey: apiKey.data, companyId };
}

export async function action(args: ActionFunctionArgs) {
  const input = await validator(apiKeyValidator).request(args, {
    params: ["id"]
  });
  if ("invalid" in input) return input.invalid;
  const api = await carbon(args.request);
  const result = await api.settings.updateApiKey({
    ...apiKeyFields(input.data),
    id: input.params.id
  });
  return respond(args.request, result).redirect(
    `${path.to.apiKeys}?${getParams(args.request)}`,
    { message: "Updated API key" }
  );
}

export default function EditApiKeyRoute() {
  const closeRoute = useCloseRoute();
  const { apiKey, companyId } = useLoaderData<typeof loader>();

  const initialValues = {
    id: apiKey.id,
    name: apiKey.name,
    expiresAt: apiKey.expiresAt ?? undefined
  };

  return (
    <ApiKeyForm
      key={initialValues.id}
      initialValues={initialValues}
      companyId={companyId}
      existingScopes={apiKey.scopes as Record<string, string[]> | null}
      onClose={() => closeRoute()}
    />
  );
}