feat: Domain-wide delegation for Google Calendar and Google Meet (#16622)

* Add endpoints for testing the flow

* Add MVP

* new route

* Fixes

* Fixes

* Remove enable toggle support from domainWideDelegation

* Fixes

* Revert "Remove enable toggle support from domainWideDelegation"

This reverts commit c29e729206cd1fa063f9c9ce0cf148ef1577d60b.

* Revert yarn.lock

* More fixes

* Fix new workspace platform add

* refactor: improvements

* refactor: bug fixes and improvements

* fix: type errors

* fix: conflicts

* chore: update test

* fix: logic

* chore: improvements

* fix: toglle

* fix: bugs

* fix: type err

* chore: check number type

* fix: after conflicts

* chore: fix type err

* fix: type errors and tests

* fix: tets

* test

* chore: remove unused

* fix: google meet url on booking page and secondary calendar

* fix: add property

* fix: type err

* fix: re assingment bug

* fix: use getAllCredentials

* chore: fix import

* fix: installed count

* fix: pass event type

* fix: import

* fix: [Stacked PR] Review fixes (#17958)

* Review fixes

* fix: destination calendar bug

---------

Co-authored-by: Udit Takkar <[email protected]>

* refactor: use repository

* chore: remove duplicate

* fix: More review fixes for domain wide delegation (#17969)

* Reuse buildCredentialPayloadForCalendar

* fixes

---------

Co-authored-by: Udit Takkar <[email protected]>

* fix ts error

* Fix getSchedule not using dwd credentials (#17995)

* fix: Remove direct DWD table access from google-calendar and remove delegatedToId column from Credential (#18015)

* Remove fn rename to reduce number of files changed

* chore: check feature globally

* test: add unit tests

* chore: move function

* test: add booking test

* wip

* Remove domain-wide-delegation team feature flag

* Make sure duplicate calendars are not shown due to DWD. Show DWD when there is conflict

* Fix tests and their ts errors

* Fix more tests

* Move findUsersForAvailabilityCheck to separate file as it has AppStore dependency causing problem with Routing Forms. Build crashes

* fix: Multiple calendar connections from Google not showing up in apps/installed

* DestinationCalendar must have either credentialId or domainWideDeelgationId. Also handle the case when DWD is disabled and there was a non-dwd credential that could be used

* Disable deletetion of DWD as it is destructive and prefer disabling instead

* Show DWD credential calendars at the top

* Fixed tests

* Calendar Cache DWD support

* Self-Review: Verify email required and add more selectedCalendar tests

* Self Review: shorten names

* Self ReviewL Dead code removal

* Revert "Calendar Cache DWD support"

This reverts commit 009f236470fa21eba5986117d4f6e4d4c5e38c34.

* Some misc fixes

* fixes

* Performance improvememt in slots loading and booking

* More cases for handling dwd credentials

* simplify the logic. Ensure that EventManager and the modules below it in the flow have CredentialForCalendarService available

* Fix tests

* Fix installed/conferencing not showing gogole meet

* Shorten name

* Fix ApI v2 tests

* Add some more tests

* add getSchedule tests

* Improve tests

* Make Google Meet default when DWD for google is enabled

* Enable feature flagging for DWD

* chore: bump libraries

* Encrypt serviceaccount private key

* Fix ts errors

* bump platform libraries

* org add dwd

* org add dwd

* bump platform libraries

* fix selected calendars

* fix remove selected dwd calendar

* remove oauthclient id aliad in authedCalendar

* remove oauthclient id aliad in authedCalendar

* refactor: OrganizationsDwdController

* chore: export toggleDwdEnabled from platform-libraries

* feat: v2 update (enable / disable) dwd

* refactor: SelectedCalendarsController check if user belongs to dwd org & for not dwd use previous logic

* wip: DestinationCalendar send domainWideDelegationCredentialId from frontend to api

* try fix set destination calendar api v2

* fixup! try fix set destination calendar api v2

* setting google meet as default location working for dwd

* bump platform libraries version

* allow office 365 workspace slug

* allow office 365 workspace slug

* chore: v2 create dwd MS and Google service keys input

* fix: CreateDwdInput serviceAccountKey

* fix: CredentialForCalendarService type

* fix: check workspace slug

* feat: update serviceAccessKey of DWD

* testing

* fixup! testing

* fix: getAuthUtl bug

* fix: unit tests

* fix: type err and unit test

* fix: e2e test

* fix: credentials bug and failing unit tests

* Update CalendarService.ts

* chore: refactor office365 calendar service and add testDomainWideDelegationSetup

* fix: office365Calendar use correct clientId/Secret for DWD

* fix: office365Calendar dwd no need refresh token

* test: add unit test for outlook dwd and setup

* feat: added dwd support for office365 calendar

* feat: added dwd support for office365 video

* test: finish test for outlook dwd

* fix: create dialog bug

* chore: remove console logs

* fix: refreshToken bug

* bump version libraries

* refactor: fetch dwd credentials only in findQualifiedHosts

* fixup! refactor: fetch dwd credentials only in findQualifiedHosts

* fix: type err

* fix: type err

* fix: getUserDisplayName

* fix: unit test

* chore: bump platform lib

---------

Co-authored-by: Syed Ali Shahbaz <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Morgan Vernay <[email protected]>
Co-authored-by: supalarry <[email protected]>
Co-authored-by: Somay Chauhan <[email protected]>
Co-authored-by: Morgan <[email protected]>
This commit is contained in:
173 files changed
+12277 -1137

No files matched your search

@@ -1,3 +1,4 @@
import { getAllDwdCredentialsForUserByAppType } from "@calcom/lib/domainWideDelegation/server";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -43,10 +44,15 @@ export const appCredentialsByTypeHandler = async ({ ctx, input }: AppCredentials
},
});
const dwdCredentials = await getAllDwdCredentialsForUserByAppType({
user: { id: user.id, email: user.email },
appType: input.appType,
});
// For app pages need to return which teams the user can install the app on
// return user.credentials.filter((app) => app.type == input.appType).map((credential) => credential.id);
return {
credentials,
credentials: [...dwdCredentials, ...credentials],
userAdminTeams: userAdminTeamsIds,
};
};
@@ -1,4 +1,5 @@
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
import { buildNonDwdCredentials } from "@calcom/lib/domainWideDelegation/server";
import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -23,7 +24,8 @@ const checkInvalidGoogleCalendarCredentials = async ({ ctx }: Props) => {
select: credentialForCalendarServiceSelect,
});
const calendarCredentials = getCalendarCredentials(userCredentials);
// TODO: Call top buildNonDwdCredentials here can be avoided by moving credential prisma query to repository.
const calendarCredentials = getCalendarCredentials(buildNonDwdCredentials(userCredentials));
const { connectedCalendars } = await getConnectedCalendars(
calendarCredentials,
@@ -10,6 +10,7 @@ export const ZIntegrationsInputSchema = z.object({
extendsFeature: z.literal("EventType").optional(),
teamId: z.union([z.number(), z.null()]).optional(),
sortByMostPopular: z.boolean().optional(),
sortByInstalledFirst: z.boolean().optional(),
categories: z.nativeEnum(AppCategories).array().optional(),
appId: z.string().optional(),
});
@@ -0,0 +1,208 @@
import prisma from "../../../../../tests/libs/__mocks__/prisma";
import {
createBookingScenario,
TestData,
getOrganizer,
getScenarioData,
createOrganization,
createDwdCredential,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
import { describe, it, vi, expect } from "vitest";
import { getConnectedCalendars } from "@calcom/core/CalendarManager";
import { SchedulingType, MembershipRole } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../trpc";
import { setDestinationCalendarHandler } from "./setDestinationCalendar.handler";
vi.mock("@calcom/core/CalendarManager", () => ({
getConnectedCalendars: vi.fn(),
getCalendarCredentials: vi.fn().mockImplementation((creds) => creds),
}));
describe("setDestinationCalendarHandler", () => {
setupAndTeardown();
it("should successfully set destination calendar with DWD credentials", async () => {
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
});
const childTeam = {
id: 202,
name: "Team 1",
slug: "team-1",
parentId: org.id,
};
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
teams: [
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: org.id,
name: "Test Org",
slug: "testorg",
},
},
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: childTeam.id,
name: "Team 1",
slug: "team-1",
parentId: org.id,
},
},
],
});
const dwd = await createDwdCredential(org.id);
const dwdCredentialId = dwd.id;
const testExternalId = "[email protected]";
// Mock the getConnectedCalendars response
(getConnectedCalendars as jest.Mock).mockResolvedValue({
connectedCalendars: [
{
calendars: [
{
externalId: organizer.email,
integration: "google_calendar",
readOnly: false,
primary: true,
email: organizer.email,
credentialId: -1,
domainWideDelegationCredentialId: dwdCredentialId,
},
{
externalId: testExternalId,
integration: "google_calendar",
readOnly: false,
primary: null,
email: organizer.email,
credentialId: -1,
domainWideDelegationCredentialId: dwdCredentialId,
},
],
},
],
});
await createBookingScenario(
getScenarioData(
{
organizer,
eventTypes: [
{
id: 1,
teamId: childTeam.id,
schedulingType: SchedulingType.ROUND_ROBIN,
length: 30,
hosts: [
{
userId: 101,
isFixed: false,
},
],
},
],
selectedCalendars: [
{
integration: "google_calendar",
externalId: testExternalId,
credentialId: null,
domainWideDelegationCredentialId: dwdCredentialId,
},
],
},
org
)
);
const ctx = {
user: {
id: organizer.id,
email: organizer.email,
selectedCalendars: [
{
integration: "google_calendar",
externalId: testExternalId,
credentialId: null,
domainWideDelegationCredentialId: dwdCredentialId,
},
],
} as NonNullable<TrpcSessionUser>,
};
await setDestinationCalendarHandler({
ctx,
input: {
integration: "google_calendar",
externalId: testExternalId,
},
});
// Verify the destination calendar was set correctly
const destinationCalendar = await prisma.destinationCalendar.findFirst({
where: {
userId: organizer.id,
},
});
expect(destinationCalendar).toEqual(
expect.objectContaining({
integration: "google_calendar",
externalId: testExternalId,
credentialId: null,
domainWideDelegationCredentialId: dwdCredentialId,
})
);
});
it("should throw error when calendar is not found", async () => {
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
});
const ctx = {
user: {
id: organizer.id,
email: organizer.email,
selectedCalendars: [],
} as NonNullable<TrpcSessionUser>,
};
await expect(
setDestinationCalendarHandler({
ctx,
input: {
integration: "google_calendar",
externalId: "non-existent-calendar",
eventTypeId: null,
},
})
).rejects.toThrow(
new TRPCError({ code: "BAD_REQUEST", message: "Could not find calendar non-existent-calendar" })
);
});
});
@@ -1,5 +1,6 @@
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
import { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
import { DestinationCalendarRepository } from "@calcom/lib/server/repository/destinationCalendar";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -10,6 +11,7 @@ import type { TSetDestinationCalendarInputSchema } from "./setDestinationCalenda
type SessionUser = NonNullable<TrpcSessionUser>;
type User = {
id: SessionUser["id"];
email: SessionUser["email"];
userLevelSelectedCalendars: SessionUser["userLevelSelectedCalendars"];
};
@@ -20,6 +22,35 @@ type SetDestinationCalendarOptions = {
input: TSetDestinationCalendarInputSchema;
};
type ConnectedCalendar = Awaited<ReturnType<typeof getConnectedCalendars>>["connectedCalendars"][number];
type ConnectedCalendarCalendar = NonNullable<ConnectedCalendar["calendars"]>[number];
export const getFirstConnectedCalendar = ({
connectedCalendars,
matcher,
}: {
connectedCalendars: ConnectedCalendar[];
matcher: (calendar: ConnectedCalendarCalendar) => boolean;
}) => {
const calendars = connectedCalendars.flatMap((c) => c.calendars ?? []);
const matchingCalendars = calendars.filter(matcher);
const dwdCredentialCalendar = matchingCalendars.find((cal) => !!cal.domainWideDelegationCredentialId);
// Prefer DWD credential calendar as there could be other one due to existing connections even after DWD is enabled.
if (dwdCredentialCalendar) {
return dwdCredentialCalendar;
} else {
return matchingCalendars[0];
}
};
/**
* It identifies the destination calendar by externalId, integration and eventTypeId and doesn't consider the `credentialId` or destinationCalendar.id
* Also, DestinationCalendar doesn't have unique constraint on externalId, integration and eventTypeId, so there could be multiple destinationCalendars with same externalId, integration and eventTypeId in DB.
* So, it could update any of the destinationCalendar when there are duplicates in DB. Ideally we should have unique constraint on externalId, integration and eventTypeId.
*
* With the addition of DWD credential, it adds another dimension to the problem.
* A user could have DWD and non-DWD credential for the same calendar and he might be selecting DWD credential connected calendar but it could still be set with nullish destinationCalendar.domainWideDelegationCredentialId.
*/
export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinationCalendarOptions) => {
const { user } = ctx;
const { integration, externalId, eventTypeId } = input;
@@ -29,19 +60,30 @@ export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinati
calendarCredentials,
user.userLevelSelectedCalendars
);
const allCals = connectedCalendars.map((cal) => cal.calendars ?? []).flat();
const credentialId = allCals.find(
(cal) => cal.externalId === externalId && cal.integration === integration && cal.readOnly === false
)?.credentialId;
const firstConnectedCalendar = getFirstConnectedCalendar({
connectedCalendars,
matcher: (cal) =>
cal.externalId === externalId && cal.integration === integration && cal.readOnly === false,
});
if (!credentialId) {
const { credentialId, domainWideDelegationCredentialId } = firstConnectedCalendar || {};
let where;
if (!credentialId && !domainWideDelegationCredentialId) {
throw new TRPCError({ code: "BAD_REQUEST", message: `Could not find calendar ${input.externalId}` });
}
const primaryEmail = allCals.find((cal) => cal.primary && cal.credentialId === credentialId)?.email ?? null;
let where;
const primaryEmail =
allCals.find(
(cal) =>
cal.primary &&
(cal.credentialId === credentialId ||
cal.domainWideDelegationCredentialId === domainWideDelegationCredentialId)
)?.email ?? null;
if (eventTypeId) {
if (
@@ -61,20 +103,22 @@ export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinati
where = { eventTypeId };
} else where = { userId: user.id };
await prisma.destinationCalendar.upsert({
await DestinationCalendarRepository.upsert({
where,
update: {
integration,
externalId,
credentialId,
primaryEmail,
credentialId,
domainWideDelegationCredentialId,
},
create: {
...where,
integration,
externalId,
credentialId,
primaryEmail,
credentialId,
domainWideDelegationCredentialId,
},
});
};
@@ -10,9 +10,9 @@ import { getFeatureFlag } from "@calcom/features/flags/server/utils";
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { uploadAvatar } from "@calcom/lib/server/avatar";
import { checkUsername } from "@calcom/lib/server/checkUsername";
import { getTranslation } from "@calcom/lib/server/i18n";
import { updateNewTeamMemberEventTypes } from "@calcom/lib/server/queries";
import { resizeBase64Image } from "@calcom/lib/server/resizeBase64Image";
import slugify from "@calcom/lib/slugify";
@@ -6,7 +6,7 @@ export const workspacePlatformCreateSchema = z.object({
slug: z.string().min(1),
name: z.string().min(1),
description: z.string().min(1),
defaultServiceAccountKey: serviceAccountKeySchema,
defaultServiceAccountKey: serviceAccountKeySchema.optional(),
enabled: z.boolean().optional().default(true),
});
@@ -1,4 +1,5 @@
import { getAppFromSlug } from "@calcom/app-store/utils";
import { getAllDwdCredentialsForUserByAppSlug } from "@calcom/lib/domainWideDelegation/server";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "../../../trpc";
@@ -18,14 +19,21 @@ export const queryForDependenciesHandler = async ({ ctx, input }: QueryForDepend
await Promise.all(
input.map(async (dependency) => {
const appInstalled = await prisma.credential.findFirst({
const appId = dependency;
const dbCredential = await prisma.credential.findFirst({
where: {
appId: dependency,
appId,
userId: ctx.user.id,
},
});
const app = await getAppFromSlug(dependency);
const dwdCredentials = await getAllDwdCredentialsForUserByAppSlug({
user: ctx.user,
appSlug: appId,
});
const appInstalled = !!dbCredential || !!dwdCredentials.length;
const app = getAppFromSlug(dependency);
dependencyData.push({ name: app?.name || dependency, slug: dependency, installed: !!appInstalled });
})
@@ -1,5 +1,6 @@
import { getBusyCalendarTimes } from "@calcom/core/CalendarManager";
import dayjs from "@calcom/dayjs";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { prisma } from "@calcom/prisma";
import type { EventBusyDate } from "@calcom/types/Calendar";
@@ -29,7 +30,7 @@ export const calendarOverlayHandler = async ({ ctx, input }: ListOptions) => {
// To call getCalendar we need
// Ensure that the user has access to all of the credentialIds
const credentials = await prisma.credential.findMany({
const nonDwdCredentials = await prisma.credential.findMany({
where: {
id: {
in: uniqueCredentialIds,
@@ -52,6 +53,13 @@ export const calendarOverlayHandler = async ({ ctx, input }: ListOptions) => {
},
});
const { credentials } = await enrichUserWithDwdCredentialsWithoutOrgId({
user: {
...user,
credentials: nonDwdCredentials,
},
});
if (credentials.length !== uniqueCredentialIds.length) {
throw new TRPCError({
code: "UNAUTHORIZED",
@@ -2,8 +2,8 @@ import EventManager from "@calcom/core/EventManager";
import dayjs from "@calcom/dayjs";
import { sendAddGuestsEmails } from "@calcom/emails";
import { parseRecurringEvent } from "@calcom/lib";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
import { getTranslation } from "@calcom/lib/server/i18n";
import { isTeamAdmin, isTeamOwner } from "@calcom/lib/server/queries/teams";
import { prisma } from "@calcom/prisma";
import type { CalendarEvent } from "@calcom/types/Calendar";
@@ -15,8 +15,8 @@ import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
import { processPaymentRefund } from "@calcom/lib/payment/processPaymentRefund";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import { prisma } from "@calcom/prisma";
import {
@@ -17,7 +17,6 @@ import type { Booking, BookingReference } from "@calcom/prisma/client";
import type { userMetadata } from "@calcom/prisma/zod-utils";
import type { EventTypeMetadata } from "@calcom/prisma/zod-utils";
import type { AdditionalInformation, CalendarEvent } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { PartialReference } from "@calcom/types/EventManager";
import type { Ensure } from "@calcom/types/utils";
@@ -126,12 +125,12 @@ async function getAllCredentials({
user,
conferenceCredentialId,
}: {
user: { id: number };
user: { id: number; email: string };
conferenceCredentialId: number | null;
}) {
const credentials = await getUsersCredentials(user);
let conferenceCredential: CredentialPayload | null = null;
let conferenceCredential;
if (conferenceCredentialId) {
conferenceCredential = await CredentialRepository.findFirstByIdWithKeyAndUser({
@@ -12,6 +12,7 @@ import getWebhooks from "@calcom/features/webhooks/lib/getWebhooks";
import { deleteWebhookScheduledTriggers } from "@calcom/features/webhooks/lib/scheduleTrigger";
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import { isPrismaObjOrUndefined } from "@calcom/lib";
import { getDwdOrRegularCredential } from "@calcom/lib/domainWideDelegation/server";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
@@ -239,12 +240,24 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
if (bookingRef.type.endsWith("_calendar")) {
const calendar = await getCalendar(
credentials.find((cred) => cred.id === bookingRef?.credentialId) || null
getDwdOrRegularCredential({
credentials,
id: {
credentialId: bookingRef?.credentialId,
dwdId: bookingRef?.domainWideDelegationCredentialId,
},
})
);
return calendar?.deleteEvent(bookingRef.uid, builder.calendarEvent, bookingRef.externalCalendarId);
} else if (bookingRef.type.endsWith("_video")) {
return deleteMeeting(
credentials.find((cred) => cred?.id === bookingRef?.credentialId) || null,
getDwdOrRegularCredential({
credentials,
id: {
credentialId: bookingRef?.credentialId,
dwdId: bookingRef?.domainWideDelegationCredentialId,
},
}),
bookingRef.uid
);
}
@@ -1,3 +1,8 @@
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { getTranslation } from "@calcom/lib/server/i18n";
import { TRPCError } from "@trpc/server";
import authedProcedure, { authedOrgAdminProcedure } from "../../../procedures/authedProcedure";
import { router, importHandler } from "../../../trpc";
import {
@@ -10,20 +15,58 @@ import {
const NAMESPACE = "domainWideDelegation";
const namespaced = (s: string) => `${NAMESPACE}.${s}`;
const checkDomainWideDelegationFeature = async ({
ctx,
next,
}: {
ctx: { user: { id: number; locale?: string; organizationId: number | null } };
next: () => Promise<any>;
}) => {
const user = ctx.user;
const t = await getTranslation(user.locale ?? "en", "common");
const featureRepo = new FeaturesRepository();
if (!user.organizationId) {
throw new TRPCError({
code: "FORBIDDEN",
message: t("no_organization_found"),
});
}
const hasDomainWideDelegation = await featureRepo.checkIfTeamHasFeature(
user.organizationId,
"domain-wide-delegation"
);
if (!hasDomainWideDelegation) {
throw new TRPCError({
code: "FORBIDDEN",
message: t("domain_wide_delegation_feature_not_enabled"),
});
}
return next();
};
export const domainWideDelegationRouter = router({
list: authedOrgAdminProcedure.query(async (opts) => {
list: authedOrgAdminProcedure.use(checkDomainWideDelegationFeature).query(async (opts) => {
const handler = await importHandler(namespaced("list"), () => import("./list.handler"));
return handler(opts);
}),
update: authedOrgAdminProcedure.input(DomainWideDelegationUpdateSchema).mutation(async (opts) => {
const handler = await importHandler(namespaced("update"), () => import("./update.handler"));
return handler(opts);
}),
add: authedOrgAdminProcedure.input(DomainWideDelegationCreateSchema).mutation(async (opts) => {
const handler = await importHandler(namespaced("add"), () => import("./add.handler"));
return handler(opts);
}),
update: authedOrgAdminProcedure
.use(checkDomainWideDelegationFeature)
.input(DomainWideDelegationUpdateSchema)
.mutation(async (opts) => {
const handler = await importHandler(namespaced("update"), () => import("./update.handler"));
return handler(opts);
}),
add: authedOrgAdminProcedure
.use(checkDomainWideDelegationFeature)
.input(DomainWideDelegationCreateSchema)
.mutation(async (opts) => {
const handler = await importHandler(namespaced("add"), () => import("./add.handler"));
return handler(opts);
}),
toggleEnabled: authedOrgAdminProcedure
.use(checkDomainWideDelegationFeature)
.input(DomainWideDelegationToggleEnabledSchema)
.mutation(async (opts) => {
const handler = await importHandler(
@@ -32,11 +75,14 @@ export const domainWideDelegationRouter = router({
);
return handler(opts);
}),
delete: authedOrgAdminProcedure.input(DomainWideDelegationDeleteSchema).mutation(async (opts) => {
const handler = await importHandler(namespaced("delete"), () => import("./delete.handler"));
return handler(opts);
}),
listWorkspacePlatforms: authedProcedure.query(async () => {
delete: authedOrgAdminProcedure
.use(checkDomainWideDelegationFeature)
.input(DomainWideDelegationDeleteSchema)
.mutation(async (opts) => {
const handler = await importHandler(namespaced("delete"), () => import("./delete.handler"));
return handler(opts);
}),
listWorkspacePlatforms: authedProcedure.use(checkDomainWideDelegationFeature).query(async () => {
const handler = await importHandler(
namespaced("listWorkspacePlatforms"),
() => import("./listWorkspacePlatforms.handler")
@@ -1,6 +1,6 @@
import type { z } from "zod";
import { DomainWideDelegation } from "@calcom/features/domain-wide-delegation/domain-wide-delegation";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform";
import { TRPCError } from "@trpc/server";
@@ -19,7 +19,7 @@ export default async function handler({
input: z.infer<typeof DomainWideDelegationCreateSchema>;
ctx: { user: { id: number; organizationId: number | null } };
}) {
const { workspacePlatformSlug, domain } = input;
const { workspacePlatformSlug, domain, serviceAccountKey } = input;
const { user } = ctx;
const { organizationId } = user;
@@ -31,7 +31,7 @@ export default async function handler({
}
try {
const workspacePlatform = await WorkspacePlatformRepository.findBySlugIncludeSensitiveServiceAccountKey({
const workspacePlatform = await WorkspacePlatformRepository.findBySlug({
slug: workspacePlatformSlug,
});
@@ -48,15 +48,13 @@ export default async function handler({
dwdBeingUpdatedId: null,
});
const domainWideDelegationRepository = await DomainWideDelegation.init(user.id, organizationId);
const createdDelegation = await domainWideDelegationRepository.create({
const createdDelegation = await DomainWideDelegationRepository.create({
workspacePlatformId: workspacePlatform.id,
domain,
// We don't want to enable by default because enabling requires some checks to be completed and it has a separate flow.
enabled: false,
organizationId,
serviceAccountKey: workspacePlatform.defaultServiceAccountKey,
serviceAccountKey,
});
return ensureNoServiceAccountKey(createdDelegation);
@@ -1,23 +1,21 @@
import type z from "zod";
import { DomainWideDelegation } from "@calcom/features/domain-wide-delegation/domain-wide-delegation";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import { TRPCError } from "@trpc/server";
import type { DomainWideDelegationDeleteSchema } from "./schema";
export default async function handler({
ctx,
input,
}: {
input: z.infer<typeof DomainWideDelegationDeleteSchema>;
ctx: { user: { id: number; organizationId: number | null } };
}) {
const { id } = input;
const domainWideDelegationRepository = await DomainWideDelegation.init(
ctx.user.id,
ctx.user.organizationId
);
await domainWideDelegationRepository.deleteById({ id });
// We might want to consider allowing this in the future. Right now, toggling off DWD achieves similar but non-destructive effect
throw new TRPCError({ code: "BAD_REQUEST", message: "Not allowed" });
await DomainWideDelegationRepository.deleteById({ id });
return { id };
}
@@ -1,6 +1,6 @@
import { DomainWideDelegation } from "@calcom/features/domain-wide-delegation/domain-wide-delegation";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import { encryptedServiceAccountKeySchema } from "@calcom/lib/server/serviceAccountKey";
import type { PrismaClient } from "@calcom/prisma";
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
import { ensureNoServiceAccountKey } from "./utils";
@@ -16,15 +16,14 @@ export default async function handler({
if (!organizationId) {
throw new Error("You must be in an organization to list domain wide delegations");
}
const domainWideDelegationRepository = await DomainWideDelegation.init(user.id, organizationId);
const domainWideDelegations = await domainWideDelegationRepository.findDelegationsWithServiceAccount({
organizationId,
});
const domainWideDelegations =
await DomainWideDelegationRepository.findByOrgIdIncludeSensitiveServiceAccountKey({
organizationId,
});
return domainWideDelegations.map((delegation) => {
// Let's not parse the service account key here, we should be able to fix the item with the problem, so we always try to return the complete list
const serviceAccountKey = serviceAccountKeySchema.safeParse(delegation.serviceAccountKey);
const serviceAccountKey = encryptedServiceAccountKeySchema.safeParse(delegation.serviceAccountKey);
return ensureNoServiceAccountKey({
...delegation,
@@ -1,8 +1,11 @@
import { z } from "zod";
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
export const DomainWideDelegationCreateSchema = z.object({
workspacePlatformSlug: z.string(),
domain: z.string(),
serviceAccountKey: serviceAccountKeySchema,
});
export const DomainWideDelegationUpdateSchema = z.object({
@@ -1,54 +1,52 @@
import type { z } from "zod";
import { DomainWideDelegation } from "@calcom/features/domain-wide-delegation/domain-wide-delegation";
import { checkIfSuccessfullyConfiguredInWorkspace } from "@calcom/lib/domainWideDelegation/server";
import { getTranslation } from "@calcom/lib/server/i18n";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import type { ServiceAccountKey } from "@calcom/lib/server/repository/domainWideDelegation";
// import { checkIfSuccessfullyConfiguredInWorkspace } from "@calcom/lib/domainWideDelegation/server";
import type { DomainWideDelegationToggleEnabledSchema } from "./schema";
import { ensureNoServiceAccountKey } from "./utils";
const assertWorkspaceConfigured = async ({
domainWideDelegationId,
user,
}: {
domainWideDelegationId: string;
user: { id: number; email: string; organizationId: number | null };
}) => {
const domainWideDelegationRepository = await DomainWideDelegation.init(user.id, user.organizationId);
const domainWideDelegation = await domainWideDelegationRepository.findById({ id: domainWideDelegationId });
if (!domainWideDelegation) {
throw new Error("Domain wide delegation not found");
}
// TODO: Uncomment later
// const isSuccessfullyConfigured = await checkIfSuccessfullyConfiguredInWorkspace({
// domainWideDelegation,
// user,
// });
// if (!isSuccessfullyConfigured) {
// throw new Error("Workspace not successfully configured");
// }
type LoggedInUser = {
id: number;
email: string;
locale: string;
emailVerified: Date | null;
organizationId: number | null;
};
export default async function toggleEnabledHandler({
ctx,
input,
}: {
ctx: { user: { id: number; email: string; organizationId: number | null } };
ctx: {
user: LoggedInUser;
};
input: z.infer<typeof DomainWideDelegationToggleEnabledSchema>;
}) {
const { user: loggedInUser } = ctx;
const t = await getTranslation(ctx.user.locale ?? "en", "common");
if (input.enabled) {
await assertWorkspaceConfigured({ domainWideDelegationId: input.id, user: loggedInUser });
if (!loggedInUser.emailVerified) {
throw new Error(t("verify_your_email"));
}
const domainWideDelegationRepository = await DomainWideDelegation.init(
loggedInUser.id,
loggedInUser.organizationId
);
return toggleDwdEnabled(loggedInUser, input);
}
const updatedDomainWideDelegation = await domainWideDelegationRepository.updateById({
export async function toggleDwdEnabled(
loggedInUser: Omit<LoggedInUser, "locale" | "emailVerified">,
input: z.infer<typeof DomainWideDelegationToggleEnabledSchema>
) {
if (input.enabled) {
await assertWorkspaceConfigured({
domainWideDelegationId: input.id,
user: loggedInUser,
});
}
const updatedDomainWideDelegation = await DomainWideDelegationRepository.updateById({
id: input.id,
data: {
enabled: input.enabled,
@@ -57,3 +55,38 @@ export default async function toggleEnabledHandler({
return ensureNoServiceAccountKey(updatedDomainWideDelegation);
}
const assertWorkspaceConfigured = async ({
domainWideDelegationId,
user,
}: {
domainWideDelegationId: string;
user: { id: number; email: string; organizationId: number | null };
}) => {
const dwd = await DomainWideDelegationRepository.findByIdIncludeSensitiveServiceAccountKey({
id: domainWideDelegationId,
});
if (!dwd) {
throw new Error("Domain wide delegation not found");
}
if (!hasServiceAccountKey(dwd)) {
throw new Error("Domain wide delegation doesn't have service account key");
}
const isSuccessfullyConfigured = await checkIfSuccessfullyConfiguredInWorkspace({
dwd,
user,
});
if (!isSuccessfullyConfigured) {
throw new Error("Workspace not successfully configured");
}
};
function hasServiceAccountKey<T extends { serviceAccountKey: ServiceAccountKey | null }>(
domainWideDelegation: T
): domainWideDelegation is T & { serviceAccountKey: ServiceAccountKey } {
return domainWideDelegation.serviceAccountKey !== null;
}
@@ -1,6 +1,6 @@
import type { z } from "zod";
import { DomainWideDelegation } from "@calcom/features/domain-wide-delegation/domain-wide-delegation";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform";
import { TRPCError } from "@calcom/trpc/server";
@@ -47,9 +47,7 @@ export default async function handler({
});
}
const domainWideDelegationRepository = await DomainWideDelegation.init(user.id, organizationId);
const updatedDelegation = await domainWideDelegationRepository.updateById({
const updatedDelegation = await DomainWideDelegationRepository.updateById({
id,
data: {
workspacePlatformId: workspacePlatform.id,
@@ -24,6 +24,7 @@ type User = {
id: SessionUser["id"] | null;
};
metadata: SessionUser["metadata"];
email: SessionUser["email"];
};
type CreateOptions = {
@@ -38,6 +38,7 @@ type User = {
};
userLevelSelectedCalendars: SessionUser["userLevelSelectedCalendars"];
organizationId: number | null;
email: SessionUser["email"];
locale: string;
};
@@ -1,3 +1,4 @@
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -13,12 +14,30 @@ type ListHandlerInput = {
export const listHandler = async ({ ctx }: ListHandlerInput) => {
const organizationId = ctx.user.organization?.id ?? ctx.user.profiles[0]?.organizationId;
if (!organizationId) {
throw new TRPCError({ code: "BAD_REQUEST", message: "You do not belong to an organization" });
throw new TRPCError({ code: "BAD_REQUEST", message: "You do not belong to an organization" });
}
return await OrganizationRepository.findCurrentOrg({
const currentOrg = await OrganizationRepository.findCurrentOrg({
userId: ctx.user.id,
orgId: organizationId,
});
if (!currentOrg) {
return currentOrg;
}
const featureRepo = new FeaturesRepository();
const hasDomainWideDelegation = await featureRepo.checkIfTeamHasFeature(
organizationId,
"domain-wide-delegation"
);
return {
...currentOrg,
features: {
domainWideDelegation: hasDomainWideDelegation,
},
};
};
export default listHandler;
@@ -9,6 +9,7 @@ import type { NextApiResponse } from "next";
import { enrichFormWithMigrationData } from "@calcom/app-store/routing-forms/enrichFormWithMigrationData";
import { getUrlSearchParamsToForwardForTestPreview } from "@calcom/app-store/routing-forms/pages/routing-link/getUrlSearchParamsToForward";
import { enrichHostsWithDwdCredentials } from "@calcom/lib/domainWideDelegation/server";
import { entityPrismaWhereClause } from "@calcom/lib/entityPermissionUtils";
import { fromEntriesWithDuplicateKeys } from "@calcom/lib/fromEntriesWithDuplicateKeys";
import { findTeamMembersMatchingAttributeLogic } from "@calcom/lib/raqb/findTeamMembersMatchingAttributeLogic";
@@ -254,7 +255,10 @@ export const findTeamMembersMatchingAttributeLogicOfRouteHandler = async ({
const matchingTeamMembersIds = matchingTeamMembersWithResult.map((member) => member.userId);
const matchingTeamMembers = await UserRepository.findByIds({ ids: matchingTeamMembersIds });
const matchingHosts = eventType.hosts.filter((host) => matchingTeamMembersIds.includes(host.user.id));
const matchingHosts = await enrichHostsWithDwdCredentials({
orgId: formOrgId,
hosts: eventType.hosts.filter((host) => matchingTeamMembersIds.includes(host.user.id)),
});
if (matchingTeamMembers.length !== matchingHosts.length) {
throw new TRPCError({
@@ -18,7 +18,7 @@ import { checkForConflicts } from "@calcom/features/bookings/lib/conflictChecker
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
import { getShouldServeCache } from "@calcom/features/calendar-cache/lib/getShouldServeCache";
import { parseBookingLimit, parseDurationLimit } from "@calcom/lib";
import { findQualifiedHosts } from "@calcom/lib/bookings/findQualifiedHosts";
import { findQualifiedHostsWithDwdCredentials } from "@calcom/lib/bookings/findQualifiedHostsWithDwdCredentials";
import { shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";
import { RESERVED_SUBDOMAINS } from "@calcom/lib/constants";
import { getUTCOffsetByTimezone } from "@calcom/lib/date-fns";
@@ -38,6 +38,7 @@ import { PeriodType, Prisma } from "@calcom/prisma/client";
import { BookingStatus, SchedulingType } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { EventBusyDate } from "@calcom/types/Calendar";
import type { CredentialPayload, CredentialForCalendarService } from "@calcom/types/Credential";
import { TRPCError } from "@trpc/server";
@@ -46,6 +47,12 @@ import type { TGetScheduleInputSchema } from "./getSchedule.schema";
import { handleNotificationWhenNoSlots } from "./handleNotificationWhenNoSlots";
const log = logger.getSubLogger({ prefix: ["[slots/util]"] });
type GetAvailabilityUserWithoutDwdCredentials = Omit<GetAvailabilityUser, "credentials"> & {
credentials: CredentialPayload[];
};
type GetAvailabilityUserWithDwdCredentials = Omit<GetAvailabilityUser, "credentials"> & {
credentials: CredentialForCalendarService[];
};
const selectSelectedSlots = Prisma.validator<Prisma.SelectedSlotsDefaultArgs>()({
select: {
id: true,
@@ -268,7 +275,7 @@ export function getUsersWithCredentials({
}: {
hosts: {
isFixed?: boolean;
user: GetAvailabilityUser;
user: GetAvailabilityUserWithDwdCredentials;
}[];
}) {
return hosts.map(({ isFixed, user }) => ({ isFixed, ...user }));
@@ -377,7 +384,7 @@ async function _getAvailableSlots({ input, ctx }: GetScheduleOptions): Promise<I
}
const { qualifiedRRHosts, allFallbackRRHosts, fixedHosts } = await monitorCallbackAsync(
findQualifiedHosts<GetAvailabilityUser>,
findQualifiedHostsWithDwdCredentials<GetAvailabilityUserWithoutDwdCredentials>,
{
eventType,
rescheduleUid: input.rescheduleUid ?? null,
@@ -994,7 +1001,7 @@ const calculateHostsAndAvailabilities = async ({
eventType: Exclude<Awaited<ReturnType<typeof getRegularOrDynamicEventType>>, null>;
hosts: {
isFixed?: boolean;
user: GetAvailabilityUser;
user: GetAvailabilityUserWithDwdCredentials;
}[];
loggerWithEventDetails: Logger<unknown>;
startTime: ReturnType<typeof getStartTime>;
@@ -1,4 +1,5 @@
import { getUserAvailability } from "@calcom/core/getUserAvailability";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { isTeamMember } from "@calcom/lib/server/queries/teams";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -25,17 +26,21 @@ export const getMemberAvailabilityHandler = async ({ ctx, input }: GetMemberAvai
if (!member) throw new TRPCError({ code: "NOT_FOUND", message: "Member not found" });
if (!member.user.username)
throw new TRPCError({ code: "BAD_REQUEST", message: "Member doesn't have a username" });
const username = member.user.username;
const user = await enrichUserWithDwdCredentialsWithoutOrgId({
user: member.user,
});
// get availability for this member
return await getUserAvailability(
{
username: member.user.username,
username: username,
dateFrom: input.dateFrom,
dateTo: input.dateTo,
returnDateOverrides: true,
bypassBusyCalendarTimes: false,
},
{ user: member.user, busyTimesFromLimitsBookings: [] }
{ user, busyTimesFromLimitsBookings: [] }
);
};
@@ -1,6 +1,7 @@
import dayjs from "@calcom/dayjs";
import { ensureAvailableUsers } from "@calcom/features/bookings/lib/handleNewBooking/ensureAvailableUsers";
import type { IsFixedAwareUser } from "@calcom/features/bookings/lib/handleNewBooking/types";
import { enrichUsersWithDwdCredentials } from "@calcom/lib/domainWideDelegation/server";
import { ErrorCode } from "@calcom/lib/errorCodes";
import logger from "@calcom/lib/logger";
import { withSelectedCalendars } from "@calcom/lib/server/repository/user";
@@ -21,6 +22,7 @@ type GetRoundRobinHostsToReassignOptions = {
async function getTeamHostsFromDB({
eventTypeId,
organizationId,
prisma,
searchTerm,
cursor,
@@ -28,6 +30,7 @@ async function getTeamHostsFromDB({
excludeUserId,
}: {
eventTypeId: number;
organizationId: number | null;
prisma: PrismaClient;
searchTerm?: string;
cursor?: number;
@@ -77,13 +80,17 @@ async function getTeamHostsFromDB({
const hasNextPage = hosts.length > limit;
const hosts_subset = hasNextPage ? hosts.slice(0, -1) : hosts;
const hostsMergedWithUser = hosts_subset.map((host) => ({
...host.user,
isFixed: host.isFixed,
priority: host.priority ?? 2,
}));
return {
hosts: hosts_subset.map((host) => ({
...host.user,
isFixed: host.isFixed,
priority: host.priority ?? 2,
})),
hosts: await enrichUsersWithDwdCredentials({
orgId: organizationId,
users: hostsMergedWithUser,
}),
totalCount,
hasNextPage,
nextCursor: hasNextPage ? hosts_subset[hosts_subset.length - 1].user.id : null,
@@ -97,9 +104,9 @@ async function getEventTypeFromDB(eventTypeId: number, prisma: PrismaClient) {
}
export const getRoundRobinHostsToReassign = async ({ ctx, input }: GetRoundRobinHostsToReassignOptions) => {
const { prisma } = ctx;
const { prisma, user } = ctx;
const { bookingId, limit, cursor, searchTerm } = input;
const organizationId = user.organizationId;
const gettingRoundRobinHostsToReassignLogger = logger.getSubLogger({
prefix: ["gettingRoundRobinHostsToReassign", `${bookingId}`],
});
@@ -120,6 +127,7 @@ export const getRoundRobinHostsToReassign = async ({ ctx, input }: GetRoundRobin
const { hosts, totalCount, nextCursor } = await getTeamHostsFromDB({
eventTypeId: booking.eventTypeId,
organizationId,
prisma,
searchTerm,
cursor,