Skip to content

Automate browser based workflows with AI

5.9 KB
Raw Blame
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo } from "react";
import { getClient } from "@/api/AxiosClient";
import { useCredentialGetter } from "./useCredentialGetter";
import {
  CustomCredentialServiceConfigResponse,
  CustomCredentialServiceOrganizationAuthToken,
  CreateCustomCredentialServiceConfigRequest,
  CustomCredentialServiceConfig,
} from "@/api/types";
import { useToast } from "@/components/ui/use-toast";
import { useHasCapability } from "@/store/PageSlots";
import { useClearOrganizationAuthToken } from "./useClearOrganizationAuthToken";

export function useCustomCredentialServiceConfig() {
  const credentialGetter = useCredentialGetter();
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const canReadConfig = useHasCapability("vault_provider.read");
  const canUpdateConfig = useHasCapability("vault_provider.update");

  const { data: storedCustomCredentialServiceAuthToken, isLoading } =
    useQuery<CustomCredentialServiceOrganizationAuthToken | null>({
      queryKey: ["customCredentialServiceAuthToken"],
      enabled: canReadConfig,
      queryFn: async () => {
        const client = await getClient(credentialGetter, "sans-api-v1");
        return await client
          .get("/credentials/custom_credential/get")
          .then((response) => response.data.token)
          .catch((error) => {
            // 404 likely means not configured yet - return null silently
            if (error?.response?.status === 404) {
              return null;
            }
            // Log other errors for debugging but still return null
            console.warn(
              "Failed to fetch custom credential service config:",
              error,
            );
            return null;
          });
      },
    });
  // Member-readable and secret-free, so credential flows can offer the service without vault_provider.read.
  const { data: status } = useQuery<{ configured: boolean }>({
    queryKey: ["customCredentialServiceAuthToken", "status"],
    queryFn: async () => {
      const client = await getClient(credentialGetter, "sans-api-v1");
      return (await client.get("/credentials/custom_credential/status")).data;
    },
  });
  const customCredentialServiceAuthToken = canReadConfig
    ? storedCustomCredentialServiceAuthToken
    : undefined;

  // Parse the configuration from the stored token
  const parsedConfig: CustomCredentialServiceConfig | null = useMemo(() => {
    if (!customCredentialServiceAuthToken?.token) return null;

    try {
      return JSON.parse(customCredentialServiceAuthToken.token);
    } catch {
      return null;
    }
  }, [customCredentialServiceAuthToken?.token]);

  const createOrUpdateConfigMutation = useMutation({
    mutationFn: async (data: CreateCustomCredentialServiceConfigRequest) => {
      if (!canUpdateConfig) {
        throw new Error(
          "Organization admin access is required for this action.",
        );
      }
      const client = await getClient(credentialGetter, "sans-api-v1");
      return await client
        .post("/credentials/custom_credential/create", data)
        .then(
          (response) => response.data as CustomCredentialServiceConfigResponse,
        );
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["customCredentialServiceAuthToken"],
      });
      toast({
        title: "Success",
        description:
          "Custom credential service configuration updated successfully",
      });
    },
    onError: (error: unknown) => {
      const message =
        (error as { response?: { data?: { detail?: string } } })?.response?.data
          ?.detail ||
        (error as Error)?.message ||
        "Failed to update custom credential service configuration";
      toast({
        title: "Error",
        description: message,
        variant: "destructive",
      });
    },
  });

  const clearConfigMutation = useClearOrganizationAuthToken({
    providerPath: "custom_credential",
    queryKey: "customCredentialServiceAuthToken",
    successDescription:
      "Custom credential service configuration cleared successfully",
    errorDescription: "Failed to clear custom credential service configuration",
  });

  const testConnectionMutation = useMutation({
    mutationFn: async (data: CreateCustomCredentialServiceConfigRequest) => {
      if (!canUpdateConfig) {
        throw new Error(
          "Organization admin access is required for this action.",
        );
      }
      const client = await getClient(credentialGetter, "sans-api-v1");
      return await client
        .post("/credentials/custom_credential/test_connection", data)
        .then((response) => response.data as { success: boolean });
    },
    onSuccess: () => {
      toast({
        title: "Success",
        description: "Connection successful",
        variant: "success",
      });
    },
    onError: (error: unknown) => {
      const resp = (error as { response?: { data?: { detail?: unknown } } })
        ?.response;
      const detail = resp?.data?.detail;
      let message: string;
      if (typeof detail === "string") {
        message = detail;
      } else if (Array.isArray(detail)) {
        message = detail.map((d) => d.msg ?? JSON.stringify(d)).join("; ");
      } else {
        message = (error as Error)?.message || "Connection test failed";
      }
      toast({
        title: "Error",
        description: message,
        variant: "destructive",
      });
    },
  });

  return {
    customCredentialServiceAuthToken,
    parsedConfig,
    isConfigured: status?.configured ?? parsedConfig !== null,
    isLoading: canReadConfig && isLoading,
    canReadConfig,
    createOrUpdateConfig: createOrUpdateConfigMutation.mutate,
    isUpdating: createOrUpdateConfigMutation.isPending,
    clearConfig: clearConfigMutation.mutate,
    isClearing: clearConfigMutation.isPending,
    testConnection: testConnectionMutation.mutate,
    isTesting: testConnectionMutation.isPending,
  };
}