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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: crud for api keys
Brad Barbin9ce74a4b36b0
diff --git a/apps/carbon/app/modules/settings/settings.models.ts b/apps/carbon/app/modules/settings/settings.models.tsindex 21279685f6..39a9d6f800 100644--- a/apps/carbon/app/modules/settings/settings.models.ts+++ b/apps/carbon/app/modules/settings/settings.models.ts@@ -18,6 +18,11 @@ export const modulesType = ["Users",] as const;+export const apiKeyValidator = z.object({+ id: zfd.text(z.string().optional()),+ name: z.string().min(1, { message: "Name is required" }),+});+const company = {name: z.string().min(1, { message: "Name is required" }),taxId: zfd.text(z.string().optional()),diff --git a/apps/carbon/app/modules/settings/settings.service.ts b/apps/carbon/app/modules/settings/settings.service.tsindex de56bbbb18..a16e571054 100644--- a/apps/carbon/app/modules/settings/settings.service.ts+++ b/apps/carbon/app/modules/settings/settings.service.ts@@ -1,12 +1,49 @@import type { Database, Json } from "@carbon/database";import type { SupabaseClient } from "@supabase/supabase-js";+import { nanoid } from "nanoid";import type { z } from "zod";import { SUPABASE_API_URL } from "~/config/env";import type { GenericQueryFilters } from "~/utils/query";import { setGenericQueryFilters } from "~/utils/query";import { interpolateSequenceDate } from "~/utils/string";import { sanitize } from "~/utils/supabase";-import type { companyValidator, sequenceValidator } from "./settings.models";+import type {+ apiKeyValidator,+ companyValidator,+ sequenceValidator,+} from "./settings.models";++export async function deleteApiKey(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("apiKey").delete().eq("id", id);+}++export async function getApiKeys(+ client: SupabaseClient<Database>,+ companyId: string,+ args?: GenericQueryFilters & { search: string | null }+) {+ let query = client+ .from("apiKey")+ .select("*", {+ count: "exact",+ })+ .eq("companyId", companyId);++ if (args?.search) {+ query = query.ilike("name", `%${args.search}%`);+ }++ if (args) {+ query = setGenericQueryFilters(query, args, [+ { column: "createdAt", ascending: true },+ ]);+ }++ return query;+}export async function getCompanies(client: SupabaseClient<Database>,@@ -290,6 +327,28 @@ export async function updateCompany(return client.from("company").update(sanitize(company)).eq("id", companyId);}+export async function upsertApiKey(+ client: SupabaseClient<Database>,+ apiKey:+ | (Omit<z.infer<typeof apiKeyValidator>, "id"> & {+ createdBy: string;+ companyId: string;+ })+ | (Omit<z.infer<typeof apiKeyValidator>, "id"> & {+ id: string;+ })+) {+ if ("createdBy" in apiKey) {+ const key = `crbn_${nanoid()}`;+ return client+ .from("apiKey")+ .insert({ ...apiKey, key })+ .select("key")+ .single();+ }+ return client.from("apiKey").update(sanitize(apiKey)).eq("id", apiKey.id);+}+export async function upsertIntegration(client: SupabaseClient<Database>,update: {diff --git a/apps/carbon/app/modules/settings/types.ts b/apps/carbon/app/modules/settings/types.tsindex 2c6e7cf8fb..b5b7aecbef 100644--- a/apps/carbon/app/modules/settings/types.ts+++ b/apps/carbon/app/modules/settings/types.ts@@ -1,4 +1,5 @@import type {+ getApiKeys,getCompanies,getCustomField,getCustomFieldsTables,@@ -6,6 +7,10 @@ import type {getSequences,} from "./settings.service";+export type ApiKey = NonNullable<+ Awaited<ReturnType<typeof getApiKeys>>["data"]+>[number];+export type Company = NonNullable<Awaited<ReturnType<typeof getCompanies>>["data"]>[number];diff --git a/apps/carbon/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx b/apps/carbon/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsxnew file mode 100644index 0000000000..503bd829e9--- /dev/null+++ b/apps/carbon/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx@@ -0,0 +1,152 @@+import {+ Alert,+ AlertTitle,+ Button,+ HStack,+ IconButton,+ Input as InputBase,+ InputGroup,+ InputRightElement,+ Modal,+ ModalBody,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ VStack,+} from "@carbon/react";+import { ValidatedForm } from "@carbon/remix-validated-form";+import { useFetcher } from "@remix-run/react";+import { useEffect, useState } from "react";+import { LuCheck, LuClipboard, LuLock } from "react-icons/lu";+import type { z } from "zod";+import { Hidden, Input, Submit } from "~/components/Form";+import { usePermissions } from "~/hooks";+import { apiKeyValidator } from "~/modules/settings";+import { path } from "~/utils/path";++type ApiKeyFormProps = {+ initialValues: z.infer<typeof apiKeyValidator>;+ onClose: () => void;+};++const ApiKeyForm = ({ initialValues, onClose }: ApiKeyFormProps) => {+ const permissions = usePermissions();+ const fetcher = useFetcher<{ key: string }>();++ const isEditing = initialValues.id !== undefined;+ const isDisabled = !permissions.can("update", "users");++ const [key, setKey] = useState<string | null>(null);++ useEffect(() => {+ if (fetcher.data?.key) {+ setKey(fetcher.data.key);+ }+ }, [fetcher.data, fetcher.state, onClose]);++ return (+ <>+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) onClose?.();+ }}+ >+ <ModalContent>+ <ValidatedForm+ validator={apiKeyValidator}+ method="post"+ action={+ isEditing ? path.to.apiKey(initialValues.id!) : path.to.newApiKey+ }+ defaultValues={initialValues}+ fetcher={fetcher}+ className="flex flex-col h-full"+ >+ <ModalHeader>+ <ModalTitle>{isEditing ? "Edit" : "New"} API Key</ModalTitle>+ </ModalHeader>+ <ModalBody>+ <Hidden name="id" />+ <VStack spacing={4}>+ <Input name="name" label="Name" />+ </VStack>+ </ModalBody>+ <ModalFooter>+ <HStack>+ <Submit isDisabled={isDisabled}>Save</Submit>+ <Button size="md" variant="solid" onClick={() => onClose()}>+ Cancel+ </Button>+ </HStack>+ </ModalFooter>+ </ValidatedForm>+ </ModalContent>+ </Modal>+ {key && <ApiKeyView apiKey={key} onClose={onClose} />}+ </>+ );+};++export default ApiKeyForm;++type ApiKeyViewProps = {+ apiKey: string;+ onClose: () => void;+};++function ApiKeyView({ apiKey, onClose }: ApiKeyViewProps) {+ const [copied, setCopied] = useState(false);+ return (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <ModalContent>+ <ModalHeader>+ <ModalTitle>API Key</ModalTitle>+ </ModalHeader>+ <ModalBody>+ <VStack spacing={4}>+ <Alert variant="warning">+ <LuLock className="w-4 h-4" />+ <AlertTitle>+ You can only see this key once. Store it safely.+ </AlertTitle>+ </Alert>+ <InputGroup>+ <InputBase value={apiKey} />+ <InputRightElement className="w-[2.75rem]">+ <IconButton+ aria-label="Copy"+ icon={copied ? <LuCheck /> : <LuClipboard />}+ variant="ghost"+ onClick={() => {+ navigator.clipboard.writeText(apiKey);+ setCopied(true);+ }}+ />+ </InputRightElement>+ </InputGroup>+ </VStack>+ </ModalBody>+ <ModalFooter>+ <HStack>+ <Button+ size="md"+ variant="solid"+ onClick={() => {+ onClose();+ }}+ >+ Close+ </Button>+ </HStack>+ </ModalFooter>+ </ModalContent>+ </Modal>+ );+}diff --git a/apps/carbon/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx b/apps/carbon/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsxnew file mode 100644index 0000000000..dc213a12fd--- /dev/null+++ b/apps/carbon/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx@@ -0,0 +1,115 @@+import { Badge, MenuIcon, MenuItem } from "@carbon/react";+import { formatDate } from "@carbon/utils";+import { Outlet, useNavigate } from "@remix-run/react";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo } from "react";+import { LuPencil, LuTrash } from "react-icons/lu";+import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";+import { usePermissions, useUrlParams } from "~/hooks";+import { type ApiKey } from "~/modules/settings";+import { usePeople } from "~/stores";+import { path } from "~/utils/path";++type ApiKeysTableProps = {+ data: ApiKey[];+ count: number;+};++const ApiKeysTable = memo(({ data, count }: ApiKeysTableProps) => {+ const navigate = useNavigate();+ const [params] = useUrlParams();+ const permissions = usePermissions();+ const [people] = usePeople();++ const columns = useMemo<ColumnDef<ApiKey>[]>(() => {+ return [+ {+ accessorKey: "name",+ header: "Name",+ cell: ({ row }) => (+ <Hyperlink to={row.original.id!}>{row.original.name}</Hyperlink>+ ),+ },+ {+ accessorKey: "key",+ header: "Key",+ cell: (item) => (+ <Badge variant="secondary">{item.getValue<string>()}</Badge>+ ),+ },+ {+ id: "createdBy",+ header: "Created By",+ cell: ({ row }) => (+ <EmployeeAvatar employeeId={row.original.createdBy} />+ ),+ meta: {+ filter: {+ type: "static",+ options: people.map((employee) => ({+ value: employee.id,+ label: employee.name,+ })),+ },+ },+ },+ {+ accessorKey: "createdAt",+ header: "Created At",+ cell: (item) => formatDate(item.getValue<string>()),+ },+ ];+ }, [people]);++ const renderContextMenu = useCallback(+ (row: (typeof data)[number]) => {+ return (+ <>+ <MenuItem+ onClick={() => {+ navigate(`${path.to.apiKey(row.id!)}?${params?.toString()}`);+ }}+ >+ <MenuIcon icon={<LuPencil />} />+ Edit API Key+ </MenuItem>+ <MenuItem+ onClick={() => {+ navigate(+ `${path.to.deleteApiKey(row.id!)}?${params?.toString()}`+ );+ }}+ >+ <MenuIcon icon={<LuTrash />} />+ Delete API Key+ </MenuItem>+ </>+ );+ },+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [navigate, params, permissions]+ );++ return (+ <>+ <Table<ApiKey>+ data={data}+ columns={columns}+ count={count ?? 0}+ primaryAction={+ permissions.can("update", "users") && (+ <New+ label="API Key"+ to={`${path.to.newApiKey}?${params.toString()}`}+ />+ )+ }+ renderContextMenu={renderContextMenu}+ />+ <Outlet />+ </>+ );+});++ApiKeysTable.displayName = "ApiKeysTable";+export default ApiKeysTable;diff --git a/apps/carbon/app/modules/settings/ui/ApiKeys/index.ts b/apps/carbon/app/modules/settings/ui/ApiKeys/index.tsnew file mode 100644index 0000000000..1403686af2--- /dev/null+++ b/apps/carbon/app/modules/settings/ui/ApiKeys/index.ts@@ -0,0 +1,4 @@+import ApiKeyForm from "./ApiKeysForm";+import ApiKeysTable from "./ApiKeysTable";++export { ApiKeyForm, ApiKeysTable };diff --git a/apps/carbon/app/modules/settings/ui/index.ts b/apps/carbon/app/modules/settings/ui/index.tsindex 905b2bcca0..9c1f883969 100644--- a/apps/carbon/app/modules/settings/ui/index.ts+++ b/apps/carbon/app/modules/settings/ui/index.ts@@ -1,5 +1,6 @@import useSettingsSubmodules from "./useSettingsSubmodules";+export * from "./ApiKeys";export * from "./Company";export * from "./CustomFields";export * from "./Integrations";diff --git a/apps/carbon/app/root.tsx b/apps/carbon/app/root.tsxindex addf9a4024..6b5e452530 100644--- a/apps/carbon/app/root.tsx+++ b/apps/carbon/app/root.tsx@@ -109,7 +109,7 @@ function Document({<title>{title}</title><Links /></head>- <body className="h-full bg-background">+ <body className="h-full bg-background antialiased selection:bg-[#00cc9937] selection:text-[#007763fd] dark:selection:bg-[#00fff61d] dark:selection:text-[#67ffded2]">{children}<ScrollRestoration />diff --git a/apps/carbon/app/routes/x+/settings+/_layout.tsx b/apps/carbon/app/routes/x+/settings+/_layout.tsxindex b5c7147a92..5b4139f217 100644--- a/apps/carbon/app/routes/x+/settings+/_layout.tsx+++ b/apps/carbon/app/routes/x+/settings+/_layout.tsx@@ -1,7 +1,9 @@import { VStack } from "@carbon/react";import type { MetaFunction } from "@remix-run/node";import { Outlet } from "@remix-run/react";+import { LuKey } from "react-icons/lu";import { GroupedContentSidebar } from "~/components/Layout";+import { usePermissions } from "~/hooks";import { useSettingsSubmodules } from "~/modules/settings";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -17,8 +19,18 @@ export const handle: Handle = {};export default function SettingsRoute() {+ const permissions = usePermissions();const { groups } = useSettingsSubmodules();+ if (permissions.can("update", "users") && permissions.is("employee")) {+ groups?.[1]?.routes.unshift({+ name: "API Keys",+ to: path.to.apiKeys,+ role: "employee",+ icon: <LuKey />,+ });+ }+return (<div className="grid grid-cols-[auto_1fr] w-full h-full"><GroupedContentSidebar groups={groups} />diff --git a/apps/carbon/app/routes/x+/settings+/api-keys.$id.tsx b/apps/carbon/app/routes/x+/settings+/api-keys.$id.tsxnew file mode 100644index 0000000000..a8d68baa83--- /dev/null+++ b/apps/carbon/app/routes/x+/settings+/api-keys.$id.tsx@@ -0,0 +1,71 @@+import { validationError, validator } from "@carbon/remix-validated-form";+import type { ActionFunctionArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { useNavigate, useParams } from "@remix-run/react";+import { useRouteData } from "~/hooks";+import type { ApiKey } from "~/modules/settings";+import { ApiKeyForm, apiKeyValidator, upsertApiKey } from "~/modules/settings";+import { requirePermissions } from "~/services/auth/auth.server";+import { flash } from "~/services/session.server";+import { assertIsPost } from "~/utils/http";+import { getParams, path } from "~/utils/path";+import { error, success } from "~/utils/result";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client } = await requirePermissions(request, {+ update: "users",+ });++ const { id } = params;+ if (!id) throw new Error("Could not find id");++ const formData = await request.formData();+ const validation = await validator(apiKeyValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const updateApiKey = await upsertApiKey(client, {+ id,+ ...validation.data,+ });++ if (updateApiKey.error) {+ return json(+ {},+ await flash(+ request,+ error(updateApiKey.error, "Failed to update API key")+ )+ );+ }++ throw redirect(+ `${path.to.apiKeys}?${getParams(request)}`,+ await flash(request, success("Updated API key"))+ );+}++export default function EditApiKeyRoute() {+ const navigate = useNavigate();+ const params = useParams();+ const routeData = useRouteData<{ apiKeys: ApiKey[] }>(path.to.apiKeys);++ const apiKey = routeData?.apiKeys.find((apiKey) => apiKey.id === params.id);+ if (!apiKey) throw new Error("API key not found");++ const initialValues = {+ id: apiKey?.id ?? undefined,+ name: apiKey?.name ?? "",+ };++ return (+ <ApiKeyForm+ key={initialValues.id}+ initialValues={initialValues}+ onClose={() => navigate(-1)}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/settings+/api-keys.delete.$id.tsx b/apps/carbon/app/routes/x+/settings+/api-keys.delete.$id.tsxnew file mode 100644index 0000000000..6c5f89a7a7--- /dev/null+++ b/apps/carbon/app/routes/x+/settings+/api-keys.delete.$id.tsx@@ -0,0 +1,59 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { useNavigate, useParams } from "@remix-run/react";+import { ConfirmDelete } from "~/components/Modals";+import { useRouteData } from "~/hooks";+import type { ApiKey } from "~/modules/settings";+import { deleteApiKey } from "~/modules/settings";+import { requirePermissions } from "~/services/auth/auth.server";+import { flash } from "~/services/session.server";+import { getParams, path } from "~/utils/path";+import { error, success } from "~/utils/result";++export async function action({ request, params }: ActionFunctionArgs) {+ const { client } = await requirePermissions(request, {+ update: "users",+ });++ const { id } = params;+ if (!id) {+ throw redirect(+ path.to.itemPostingGroups,+ await flash(request, error(params, "Failed to get an id"))+ );+ }++ const { error: deleteApiKeyError } = await deleteApiKey(client, id);+ if (deleteApiKeyError) {+ throw redirect(+ `${path.to.apiKeys}?${getParams(request)}`,+ await flash(request, error(deleteApiKeyError, "Failed to delete API key"))+ );+ }++ throw redirect(+ `${path.to.apiKeys}?${getParams(request)}`,+ await flash(request, success("Successfully deleted API key"))+ );+}++export default function DeleteApiKeyRoute() {+ const { id } = useParams();+ if (!id) throw new Error("Could not find id");+ const routeData = useRouteData<{ apiKeys: ApiKey[] }>(path.to.apiKeys);+ const navigate = useNavigate();++ const apiKey = routeData?.apiKeys.find((apiKey) => apiKey.id === id);+ if (!apiKey) return null;++ const onCancel = () => navigate(-1);++ return (+ <ConfirmDelete+ action={path.to.deleteApiKey(id)}+ name={apiKey.name}+ text={`Are you sure you want to delete the API key: ${apiKey.name}? This cannot be undone.`}+ onCancel={onCancel}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/settings+/api-keys.new.tsx b/apps/carbon/app/routes/x+/settings+/api-keys.new.tsxnew file mode 100644index 0000000000..3d983a1852--- /dev/null+++ b/apps/carbon/app/routes/x+/settings+/api-keys.new.tsx@@ -0,0 +1,69 @@+import { validationError, validator } from "@carbon/remix-validated-form";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";+import { json } from "@remix-run/node";+import { useNavigate } from "@remix-run/react";+import { ApiKeyForm, apiKeyValidator, upsertApiKey } from "~/modules/settings";+import { requirePermissions } from "~/services/auth/auth.server";+import { flash } from "~/services/session.server";+import { assertIsPost } from "~/utils/http";+import { error } from "~/utils/result";++export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, {+ update: "users",+ });++ return null;+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "users",+ });++ const formData = await request.formData();+ const validation = await validator(apiKeyValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;++ const insertApiKey = await upsertApiKey(client, {+ ...data,+ companyId,+ createdBy: userId,+ });+ if (insertApiKey.error) {+ return json(+ {},+ await flash(+ request,+ error(insertApiKey.error, "Failed to create API key")+ )+ );+ }++ const key = insertApiKey.data?.key;+ if (!key) {+ return json(+ {},+ await flash(request, error(insertApiKey, "Failed to create API key"))+ );+ }++ return json({ key }, { status: 201 });+}++export default function NewApiKeyRoute() {+ const navigate = useNavigate();+ const initialValues = {+ name: "",+ };++ return (+ <ApiKeyForm onClose={() => navigate(-1)} initialValues={initialValues} />+ );+}diff --git a/apps/carbon/app/routes/x+/settings+/api-keys.tsx b/apps/carbon/app/routes/x+/settings+/api-keys.tsxnew file mode 100644index 0000000000..eee71daf69--- /dev/null+++ b/apps/carbon/app/routes/x+/settings+/api-keys.tsx@@ -0,0 +1,59 @@+import { json, redirect, type LoaderFunctionArgs } from "@remix-run/node";+import { Outlet, useLoaderData } from "@remix-run/react";+import { ApiKeysTable, getApiKeys } from "~/modules/settings";+import { requirePermissions } from "~/services/auth/auth.server";+import { flash } from "~/services/session.server";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";+import { error } from "~/utils/result";++export const handle: Handle = {+ breadcrumb: "API Keys",+ to: path.to.apiKeys,+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ update: "users",+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const search = searchParams.get("search");+ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ const apiKeys = await getApiKeys(client, companyId, {+ limit,+ offset,+ sorts,+ search,+ filters,+ });+ if (apiKeys.error) {+ throw redirect(+ path.to.settings,+ await flash(request, error(apiKeys.error, "Failed to load api keys"))+ );+ }++ return json({+ apiKeys:+ apiKeys.data?.map((apiKey) => ({+ ...apiKey,+ key: apiKey.key.substring(0, 12) + "…",+ })) ?? [],+ count: apiKeys.count ?? 0,+ });+}++export default function ApiKeysRoute() {+ const { apiKeys, count } = useLoaderData<typeof loader>();+ return (+ <>+ <ApiKeysTable count={count} data={apiKeys} />+ <Outlet />+ </>+ );+}diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex 126cc7ed8f..dc6d5d920a 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -99,6 +99,8 @@ export const path = {generatePath(`${x}/accounting/subcategory/${id}`),attribute: (id: string) => generatePath(`${x}/people/attribute/${id}`),attributes: `${x}/people/attributes`,+ apiKey: (id: string) => generatePath(`${x}/settings/api-keys/${id}`),+ apiKeys: `${x}/settings/api-keys`,attributeCategory: (id: string) =>generatePath(`${x}/people/attributes/${id}`),attributeCategoryList: (id: string) =>@@ -182,6 +184,8 @@ export const path = {generatePath(`${x}/accounting/subcategory/delete/${id}`),deleteAccountingCharts: (id: string) =>generatePath(`${x}/accounting/charts/delete/${id}`),+ deleteApiKey: (id: string) =>+ generatePath(`${x}/settings/api-keys/delete/${id}`),deleteAttribute: (id: string) =>generatePath(`${x}/people/attribute/delete/${id}`),deleteAttributeCategory: (id: string) =>@@ -384,6 +388,7 @@ export const path = {newAccountingCategory: `${x}/accounting/categories/new`,newAccountingSubcategory: (id: string) =>generatePath(`${x}/accounting/categories/list/${id}/new`),+ newApiKey: `${x}/settings/api-keys/new`,newAttribute: `${x}/people/attribute/new`,newAttributeCategory: `${x}/people/attributes/new`,newAttributeForCategory: (id: string) =>diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 5a0250ac81..89a5d55d1a 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -1589,6 +1589,97 @@ export type Database = {},]}+ apiKey: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ id: string+ key: string+ name: string+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ id?: string+ key: string+ name: string+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ id?: string+ key?: string+ name?: string+ }+ Relationships: [+ {+ foreignKeyName: "apiKey_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "apiKey_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "apiKey_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }attributeDataType: {Row: {id: number@@ -26500,6 +26591,10 @@ export type Database = {}Returns: Json}+ get_company_id_from_api_key: {+ Args: Record<PropertyKey, never>+ Returns: string+ }get_company_id_from_foreign_key: {Args: {foreign_key: string@@ -26635,6 +26730,12 @@ export type Database = {}Returns: boolean}+ has_valid_api_key_for_company: {+ Args: {+ company: string+ }+ Returns: boolean+ }is_claims_admin: {Args: Record<PropertyKey, never>Returns: booleandiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 5a0250ac81..89a5d55d1a 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -1589,6 +1589,97 @@ export type Database = {},]}+ apiKey: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ id: string+ key: string+ name: string+ }+ Insert: {+ companyId: string+ createdAt?: string+ createdBy: string+ id?: string+ key: string+ name: string+ }+ Update: {+ companyId?: string+ createdAt?: string+ createdBy?: string+ id?: string+ key?: string+ name?: string+ }+ Relationships: [+ {+ foreignKeyName: "apiKey_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "apiKey_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "apiKey_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "apiKey_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }attributeDataType: {Row: {id: number@@ -26500,6 +26591,10 @@ export type Database = {}Returns: Json}+ get_company_id_from_api_key: {+ Args: Record<PropertyKey, never>+ Returns: string+ }get_company_id_from_foreign_key: {Args: {foreign_key: string@@ -26635,6 +26730,12 @@ export type Database = {}Returns: boolean}+ has_valid_api_key_for_company: {+ Args: {+ company: string+ }+ Returns: boolean+ }is_claims_admin: {Args: Record<PropertyKey, never>Returns: booleandiff --git a/packages/database/supabase/migrations/20240728004118_api-keys.sql b/packages/database/supabase/migrations/20240728004118_api-keys.sqlnew file mode 100644index 0000000000..0bf50c2455--- /dev/null+++ b/packages/database/supabase/migrations/20240728004118_api-keys.sql@@ -0,0 +1,129 @@+CREATE TABLE "apiKey" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "name" TEXT NOT NULL,+ "key" TEXT NOT NULL,+ "companyId" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),++ CONSTRAINT "apiKey_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "apiKey_key_key" UNIQUE ("key"),+ CONSTRAINT "apiKey_name_companyId_key" UNIQUE ("name", "companyId"),+ CONSTRAINT "apiKey_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,+ CONSTRAINT "apiKey_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE+);++ALTER TABLE "apiKey" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with users_update can create/modify API keys" ON "apiKey"+FOR ALL USING (+ has_role('employee', "companyId") AND+ has_company_permission('users_update', "companyId")+);++CREATE OR REPLACE FUNCTION has_valid_api_key_for_company(company TEXT) RETURNS "bool"+ LANGUAGE "plpgsql" SECURITY DEFINER+ AS $$+ DECLARE+ has_valid_key boolean;+ BEGIN+ SELECT EXISTS(SELECT 1 FROM "apiKey" WHERE "key" = ((current_setting('request.headers'::text, true))::json ->> 'api-key'::text) AND "companyId" = company) INTO has_valid_key;+ RETURN has_valid_key;+ END;+$$;++CREATE OR REPLACE FUNCTION get_company_id_from_api_key() RETURNS TEXT+ LANGUAGE "plpgsql" SECURITY DEFINER+ AS $$+ DECLARE+ company_id TEXT;+ BEGIN+ SELECT "companyId" INTO company_id FROM "apiKey" WHERE "key" = ((current_setting('request.headers'::text, true))::json ->> 'api-key'::text);+ RETURN company_id;+ END;+$$;++NOTIFY pgrst, 'reload schema';++CREATE POLICY "Requests with an API key can access abilities" ON "ability"+FOR ALL USING (+ has_valid_api_key_for_company("companyId")+);++CREATE POLICY "Requests with an API key can access accounts" ON "account"+FOR ALL USING (+ has_valid_api_key_for_company("companyId")+);++CREATE POLICY "Requests with an API key can access account categories" ON "accountCategory"+FOR ALL USING (+ has_valid_api_key_for_company("companyId")+);+++CREATE POLICY "Requests with an API key can access account default" ON "accountDefault"+FOR ALL USING (+ has_valid_api_key_for_company("companyId")+);++CREATE POLICY "Requests with an API can access account subcategories" ON "accountSubcategory"+FOR ALL USING (+ has_valid_api_key_for_company(get_company_id_from_foreign_key("accountCategoryId", 'accountCategory'))+);++-- Forgot to add these earlier+ALTER TABLE "accountingPeriod" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view accounting periods" ON "accountingPeriod"+FOR SELECT USING (+ has_role('employee', "companyId") AND+ has_company_permission('accounting_view', "companyId")+);++CREATE POLICY "Employees with accounting_create can create accounting periods" ON "accountingPeriod"+FOR INSERT WITH CHECK (+ has_role('employee', "companyId") AND+ has_company_permission('accounting_create', "companyId")+);++CREATE POLICY "Employees with accounting_update can create accounting periods" ON "accountingPeriod"+FOR UPDATE USING (+ has_role('employee', "companyId") AND+ has_company_permission('accounting_update', "companyId")+);++CREATE POLICY "Employees with accounting_delete can create accounting periods" ON "accountingPeriod"+FOR DELETE USING (+ has_role('employee', "companyId") AND+ has_company_permission('accounting_delete', "companyId")+);++CREATE POLICY "Requests with an API key can access accounting periods" ON "accountingPeriod"+FOR ALL USING (+ has_valid_api_key_for_company("companyId")+);++CREATE POLICY "Requests with an API key can access buy methods" ON "buyMethod"+FOR ALL USING (+ has_valid_api_key_for_company("companyId")+);++CREATE POLICY "Requests with an API key can access companies" ON "company"+FOR ALL USING (+ has_valid_api_key_for_company("id")+);++CREATE POLICY "Requests with an API key can access company integrations" ON "companyIntegration"+FOR ALL USING (+ has_valid_api_key_for_company("companyId")+);++CREATE POLICY "Requests with an API key can access consumables" ON "consumable"+FOR ALL USING (+ has_valid_api_key_for_company("companyId")+);++CREATE POLICY "Requests with an API key can view customer contacts" ON "contact"+FOR ALL USING (+ has_valid_api_key_for_company("companyId")+);\ No newline at end of file