feat: support for platform wide webhooks (#14092)
* db migration * adjusted ui to include `platform` in dropdown for admin webhooks * adjusted webhook/create.handler for platform * adjusted `edit.handler` so that only ADMIN can update `platform` webhooks * update `getWebhooks` for platform wide webhooks * list platform webhooks if admin * createFunction refactor * update subscriberUrlReserved for platform webhooks * fix delete webhook handler * fix: added readOnly to WebhookListItem * fix: admin cannot delete its own webhooks * fix: ts error --------- Co-authored-by: Joe Au-Yeung <[email protected]>
This commit is contained in:
1 parent
9e17042a72
commit
7e557889b6
17 files changed
+123
-29
No files matched your search
@@ -17,6 +17,9 @@ const getWebhooks = async (options: GetSubscriberOptions, prisma: PrismaClient =
|
||||
const allWebhooks = await prisma.webhook.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
platform: true,
|
||||
},
|
||||
{
|
||||
userId,
|
||||
},
|
||||
|
||||
@@ -7,6 +7,7 @@ interface Params {
|
||||
teamId?: number;
|
||||
userId?: number;
|
||||
eventTypeId?: number;
|
||||
platform?: boolean;
|
||||
}
|
||||
|
||||
export const subscriberUrlReserved = ({
|
||||
@@ -16,9 +17,10 @@ export const subscriberUrlReserved = ({
|
||||
teamId,
|
||||
userId,
|
||||
eventTypeId,
|
||||
platform,
|
||||
}: Params): boolean => {
|
||||
if (!teamId && !userId && !eventTypeId) {
|
||||
throw new Error("Either teamId, userId, or eventTypeId must be provided.");
|
||||
if (!teamId && !userId && !eventTypeId && !platform) {
|
||||
throw new Error("Either teamId, userId, eventTypeId or platform must be provided.");
|
||||
}
|
||||
|
||||
const findMatchingWebhook = (condition: (webhook: Webhook) => void) => {
|
||||
@@ -33,5 +35,8 @@ export const subscriberUrlReserved = ({
|
||||
if (eventTypeId) {
|
||||
return findMatchingWebhook((webhook: Webhook) => webhook.eventTypeId === eventTypeId);
|
||||
}
|
||||
if (platform) {
|
||||
return findMatchingWebhook((webhook: Webhook) => webhook.platform === true);
|
||||
}
|
||||
return findMatchingWebhook((webhook: Webhook) => webhook.userId === userId);
|
||||
};
|
||||
@@ -75,6 +75,7 @@ function Component({ webhookId }: { webhookId: string }) {
|
||||
webhooks,
|
||||
teamId: webhook.teamId ?? undefined,
|
||||
userId: webhook.userId ?? undefined,
|
||||
platform: webhook.platform ?? undefined,
|
||||
})
|
||||
) {
|
||||
showToast(t("webhook_subscriber_url_reserved"), "error");
|
||||
|
||||
@@ -31,6 +31,7 @@ const NewWebhookView = () => {
|
||||
const session = useSession();
|
||||
|
||||
const teamId = searchParams?.get("teamId") ? Number(searchParams.get("teamId")) : undefined;
|
||||
const platform = searchParams?.get("platform") ? Boolean(searchParams.get("platform")) : false;
|
||||
|
||||
const { data: installedApps, isPending } = trpc.viewer.integrations.useQuery(
|
||||
{ variant: "other", onlyInstalled: true },
|
||||
@@ -63,6 +64,7 @@ const NewWebhookView = () => {
|
||||
webhooks,
|
||||
teamId,
|
||||
userId: session.data?.user.id,
|
||||
platform,
|
||||
})
|
||||
) {
|
||||
showToast(t("webhook_subscriber_url_reserved"), "error");
|
||||
@@ -80,6 +82,7 @@ const NewWebhookView = () => {
|
||||
payloadTemplate: values.payloadTemplate,
|
||||
secret: values.secret,
|
||||
teamId,
|
||||
platform,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import classNames from "@calcom/lib/classNames";
|
||||
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useBookerUrl } from "@calcom/lib/hooks/useBookerUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { UserPermissionRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { WebhooksByViewer } from "@calcom/trpc/server/routers/viewer/webhook/getByViewer.handler";
|
||||
import {
|
||||
@@ -44,11 +45,19 @@ const WebhooksView = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const session = useSession();
|
||||
const isAdmin = session.data?.user.role === UserPermissionRole.ADMIN;
|
||||
|
||||
const { data, isPending } = trpc.viewer.webhook.getByViewer.useQuery(undefined, {
|
||||
enabled: session.status === "authenticated",
|
||||
});
|
||||
|
||||
const createFunction = (teamId?: number, platform?: boolean) => {
|
||||
if (platform) {
|
||||
router.push(`webhooks/new${platform ? `?platform=${platform}` : ""}`);
|
||||
} else {
|
||||
router.push(`webhooks/new${teamId ? `?teamId=${teamId}` : ""}`);
|
||||
}
|
||||
};
|
||||
if (isPending || !data) {
|
||||
return (
|
||||
<SkeletonLoader
|
||||
@@ -69,9 +78,8 @@ const WebhooksView = () => {
|
||||
<CreateButtonWithTeamsList
|
||||
color="secondary"
|
||||
subtitle={t("create_for").toUpperCase()}
|
||||
createFunction={(teamId?: number) => {
|
||||
router.push(`webhooks/new${teamId ? `?teamId=${teamId}` : ""}`);
|
||||
}}
|
||||
isAdmin={isAdmin}
|
||||
createFunction={createFunction}
|
||||
data-testid="new_webhook"
|
||||
/>
|
||||
) : (
|
||||
@@ -81,13 +89,21 @@ const WebhooksView = () => {
|
||||
borderInShellHeader={(data && data.profiles.length === 1) || !data?.webhookGroups?.length}
|
||||
/>
|
||||
<div>
|
||||
<WebhooksList webhooksByViewer={data} />
|
||||
<WebhooksList webhooksByViewer={data} isAdmin={isAdmin} createFunction={createFunction} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const WebhooksList = ({ webhooksByViewer }: { webhooksByViewer: WebhooksByViewer }) => {
|
||||
const WebhooksList = ({
|
||||
webhooksByViewer,
|
||||
isAdmin,
|
||||
createFunction,
|
||||
}: {
|
||||
webhooksByViewer: WebhooksByViewer;
|
||||
isAdmin: boolean;
|
||||
createFunction: (teamId?: number, platform?: boolean) => void;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
@@ -149,9 +165,8 @@ const WebhooksList = ({ webhooksByViewer }: { webhooksByViewer: WebhooksByViewer
|
||||
buttonRaw={
|
||||
<CreateButtonWithTeamsList
|
||||
subtitle={t("create_for").toUpperCase()}
|
||||
createFunction={(teamId?: number) => {
|
||||
router.push(`webhooks/new${teamId ? `?teamId=${teamId}` : ""}`);
|
||||
}}
|
||||
isAdmin={isAdmin}
|
||||
createFunction={createFunction}
|
||||
data-testid="new_webhook"
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -136,6 +136,7 @@ export const buildWebhook = (webhook?: Partial<Webhook>): Webhook => {
|
||||
eventTriggers: [],
|
||||
teamId: null,
|
||||
...webhook,
|
||||
platform: false,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Webhook" ADD COLUMN "platform" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -686,6 +686,7 @@ model Webhook {
|
||||
app App? @relation(fields: [appId], references: [slug], onDelete: Cascade)
|
||||
appId String?
|
||||
secret String?
|
||||
platform Boolean @default(false)
|
||||
|
||||
@@unique([userId, subscriberUrl], name: "courseIdentifier")
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ export const _WebhookModel = z.object({
|
||||
eventTriggers: z.nativeEnum(WebhookTriggerEvents).array(),
|
||||
appId: z.string().nullish(),
|
||||
secret: z.string().nullish(),
|
||||
platform: z.boolean(),
|
||||
})
|
||||
|
||||
export interface CompleteWebhook extends z.infer<typeof _WebhookModel> {
|
||||
|
||||
@@ -3,6 +3,8 @@ import { v4 } from "uuid";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TCreateInputSchema } from "./create.schema";
|
||||
|
||||
type CreateOptions = {
|
||||
@@ -13,6 +15,18 @@ type CreateOptions = {
|
||||
};
|
||||
|
||||
export const createHandler = async ({ ctx, input }: CreateOptions) => {
|
||||
if (input.platform) {
|
||||
const { user } = ctx;
|
||||
if (user?.role !== "ADMIN") {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
return await prisma.webhook.create({
|
||||
data: {
|
||||
id: v4(),
|
||||
...input,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (input.eventTypeId || input.teamId) {
|
||||
return await prisma.webhook.create({
|
||||
data: {
|
||||
|
||||
@@ -13,6 +13,7 @@ export const ZCreateInputSchema = webhookIdAndEventTypeIdSchema.extend({
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
teamId: z.number().optional(),
|
||||
platform: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type TCreateInputSchema = z.infer<typeof ZCreateInputSchema>;
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
@@ -13,22 +15,22 @@ type DeleteOptions = {
|
||||
export const deleteHandler = async ({ ctx, input }: DeleteOptions) => {
|
||||
const { id } = input;
|
||||
|
||||
const andCondition: Partial<{ id: string; eventTypeId: number; teamId: number; userId: number }>[] = [
|
||||
{ id: id },
|
||||
];
|
||||
const where: Prisma.WebhookWhereInput = { AND: [{ id: id }] };
|
||||
|
||||
if (input.eventTypeId) {
|
||||
andCondition.push({ eventTypeId: input.eventTypeId });
|
||||
} else if (input.teamId) {
|
||||
andCondition.push({ teamId: input.teamId });
|
||||
} else {
|
||||
andCondition.push({ userId: ctx.user.id });
|
||||
if (Array.isArray(where.AND)) {
|
||||
if (input.eventTypeId) {
|
||||
where.AND.push({ eventTypeId: input.eventTypeId });
|
||||
} else if (input.teamId) {
|
||||
where.AND.push({ teamId: input.teamId });
|
||||
} else if (ctx.user.role == "ADMIN") {
|
||||
where.AND.push({ OR: [{ platform: true }, { userId: ctx.user.id }] });
|
||||
} else {
|
||||
where.AND.push({ userId: ctx.user.id });
|
||||
}
|
||||
}
|
||||
|
||||
const webhookToDelete = await prisma.webhook.findFirst({
|
||||
where: {
|
||||
AND: andCondition,
|
||||
},
|
||||
where,
|
||||
});
|
||||
|
||||
if (webhookToDelete) {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TEditInputSchema } from "./edit.schema";
|
||||
|
||||
type EditOptions = {
|
||||
@@ -10,7 +12,7 @@ type EditOptions = {
|
||||
input: TEditInputSchema;
|
||||
};
|
||||
|
||||
export const editHandler = async ({ input }: EditOptions) => {
|
||||
export const editHandler = async ({ input, ctx }: EditOptions) => {
|
||||
const { id, ...data } = input;
|
||||
|
||||
const webhook = await prisma.webhook.findFirst({
|
||||
@@ -22,6 +24,14 @@ export const editHandler = async ({ input }: EditOptions) => {
|
||||
if (!webhook) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (webhook.platform) {
|
||||
const { user } = ctx;
|
||||
if (user?.role !== "ADMIN") {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
}
|
||||
|
||||
return await prisma.webhook.update({
|
||||
where: {
|
||||
id,
|
||||
|
||||
@@ -24,6 +24,7 @@ export const getHandler = async ({ ctx: _ctx, input }: GetOptions) => {
|
||||
secret: true,
|
||||
teamId: true,
|
||||
userId: true,
|
||||
platform: true,
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -146,6 +146,24 @@ export const getByViewerHandler = async ({ ctx }: GetByViewerOptions) => {
|
||||
|
||||
webhookGroups = webhookGroups.concat(teamWebhookGroups);
|
||||
|
||||
if (ctx.user.role === "ADMIN") {
|
||||
const platformWebhooks = await prisma.webhook.findMany({
|
||||
where: { platform: true },
|
||||
});
|
||||
webhookGroups.push({
|
||||
teamId: null,
|
||||
profile: {
|
||||
slug: "Platform",
|
||||
name: "Platform",
|
||||
image,
|
||||
},
|
||||
webhooks: platformWebhooks,
|
||||
metadata: {
|
||||
readOnly: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
webhookGroups: webhookGroups.filter((groupBy) => !!groupBy.webhooks?.length),
|
||||
profiles: webhookGroups.map((group) => ({
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { Plus } from "@calcom/ui/components/icon";
|
||||
|
||||
export interface Option {
|
||||
platform?: boolean;
|
||||
teamId: number | null | undefined; // if undefined, then it's a profile
|
||||
label: string | null;
|
||||
image: string | null;
|
||||
@@ -25,7 +26,7 @@ export interface Option {
|
||||
export type CreateBtnProps = {
|
||||
options: Option[];
|
||||
createDialog?: () => JSX.Element;
|
||||
createFunction?: (teamId?: number) => void;
|
||||
createFunction?: (teamId?: number, platform?: boolean) => void;
|
||||
subtitle?: string;
|
||||
buttonText?: string;
|
||||
isPending?: boolean;
|
||||
@@ -56,6 +57,7 @@ export function CreateButton(props: CreateBtnProps) {
|
||||
const CreateDialog = createDialog ? createDialog() : null;
|
||||
|
||||
const hasTeams = !!options.find((option) => option.teamId);
|
||||
const platform = !!options.find((option) => option.platform);
|
||||
|
||||
// inject selection data into url for correct router history
|
||||
const openModal = (option: Option) => {
|
||||
@@ -74,7 +76,7 @@ export function CreateButton(props: CreateBtnProps) {
|
||||
|
||||
return (
|
||||
<>
|
||||
{!hasTeams ? (
|
||||
{!hasTeams && !platform ? (
|
||||
<Button
|
||||
onClick={() =>
|
||||
!!CreateDialog
|
||||
@@ -118,7 +120,7 @@ export function CreateButton(props: CreateBtnProps) {
|
||||
!!CreateDialog
|
||||
? openModal(option)
|
||||
: createFunction
|
||||
? createFunction(option.teamId || undefined)
|
||||
? createFunction(option.teamId || undefined, option.platform)
|
||||
: null
|
||||
}>
|
||||
{" "}
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import type { CreateBtnProps } from "./CreateButton";
|
||||
import type { CreateBtnProps, Option } from "./CreateButton";
|
||||
import { CreateButton } from "./CreateButton";
|
||||
|
||||
export function CreateButtonWithTeamsList(
|
||||
props: Omit<CreateBtnProps, "options"> & { onlyShowWithTeams?: boolean; onlyShowWithNoTeams?: boolean }
|
||||
props: Omit<CreateBtnProps, "options"> & {
|
||||
onlyShowWithTeams?: boolean;
|
||||
onlyShowWithNoTeams?: boolean;
|
||||
isAdmin?: boolean;
|
||||
}
|
||||
) {
|
||||
const query = trpc.viewer.teamsAndUserProfilesQuery.useQuery();
|
||||
if (!query.data) return null;
|
||||
|
||||
const teamsAndUserProfiles = query.data
|
||||
const teamsAndUserProfiles: Option[] = query.data
|
||||
.filter((profile) => !profile.readOnly)
|
||||
.map((profile) => {
|
||||
return {
|
||||
@@ -20,6 +24,16 @@ export function CreateButtonWithTeamsList(
|
||||
};
|
||||
});
|
||||
|
||||
if (props.isAdmin) {
|
||||
teamsAndUserProfiles.push({
|
||||
platform: true,
|
||||
label: "Platform",
|
||||
image: null,
|
||||
slug: null,
|
||||
teamId: null,
|
||||
});
|
||||
}
|
||||
|
||||
if (props.onlyShowWithTeams && teamsAndUserProfiles.length < 2) return null;
|
||||
|
||||
if (props.onlyShowWithNoTeams && teamsAndUserProfiles.length > 1) return null;
|
||||
|
||||
Reference in new issue
Block a user