chore: rename DWD to DelegationCredential (#19703)

* chore: rename DWD to DelegationCredential

* fixup! chore: rename DWD to DelegationCredential

* fixup! fixup! chore: rename DWD to DelegationCredential

* fixup! Merge branch 'main' into rename-domain-wide-delegation

* fixup! fixup! Merge branch 'main' into rename-domain-wide-delegation

* fixup! fixup! fixup! Merge branch 'main' into rename-domain-wide-delegation
This commit is contained in:
Morgan authored and GitHub committed 2025-03-04 09:45:39 -03:00
1 parent a39b5e47a7
commit 7a9ddf2194
167 files changed
+4232 -2356

No files matched your search

@@ -1,4 +1,4 @@
import { getAllDwdCredentialsForUserByAppType } from "@calcom/lib/domainWideDelegation/server";
import { getAllDelegationCredentialsForUserByAppType } from "@calcom/lib/delegationCredential/server";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -44,7 +44,7 @@ export const appCredentialsByTypeHandler = async ({ ctx, input }: AppCredentials
},
});
const dwdCredentials = await getAllDwdCredentialsForUserByAppType({
const delegationCredentials = await getAllDelegationCredentialsForUserByAppType({
user: { id: user.id, email: user.email },
appType: input.appType,
});
@@ -52,7 +52,7 @@ export const appCredentialsByTypeHandler = async ({ ctx, input }: AppCredentials
// 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: [...dwdCredentials, ...credentials],
credentials: [...delegationCredentials, ...credentials],
userAdminTeams: userAdminTeamsIds,
};
};
@@ -1,5 +1,5 @@
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/lib/CalendarManager";
import { buildNonDwdCredentials } from "@calcom/lib/domainWideDelegation/server";
import { buildNonDelegationCredentials } from "@calcom/lib/delegationCredential/server";
import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -24,8 +24,8 @@ const checkInvalidGoogleCalendarCredentials = async ({ ctx }: Props) => {
select: credentialForCalendarServiceSelect,
});
// TODO: Call top buildNonDwdCredentials here can be avoided by moving credential prisma query to repository.
const calendarCredentials = getCalendarCredentials(buildNonDwdCredentials(userCredentials));
// TODO: Call top buildNonDelegationCredentials here can be avoided by moving credential prisma query to repository.
const calendarCredentials = getCalendarCredentials(buildNonDelegationCredentials(userCredentials));
const { connectedCalendars } = await getConnectedCalendars(
calendarCredentials,
@@ -6,7 +6,7 @@ import {
getOrganizer,
getScenarioData,
createOrganization,
createDwdCredential,
createDelegationCredential,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
@@ -28,7 +28,7 @@ vi.mock("@calcom/lib/CalendarManager", () => ({
describe("setDestinationCalendarHandler", () => {
setupAndTeardown();
it("should successfully set destination calendar with DWD credentials", async () => {
it("should successfully set destination calendar with DelegationCredential credentials", async () => {
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
@@ -73,9 +73,9 @@ describe("setDestinationCalendarHandler", () => {
],
});
const dwd = await createDwdCredential(org.id);
const delegationCredential = await createDelegationCredential(org.id);
const dwdCredentialId = dwd.id;
const delegationCredentialId = delegationCredential.id;
const testExternalId = "[email protected]";
// Mock the getConnectedCalendars response
@@ -90,7 +90,7 @@ describe("setDestinationCalendarHandler", () => {
primary: true,
email: organizer.email,
credentialId: -1,
domainWideDelegationCredentialId: dwdCredentialId,
delegationCredentialId: delegationCredentialId,
},
{
externalId: testExternalId,
@@ -99,7 +99,7 @@ describe("setDestinationCalendarHandler", () => {
primary: null,
email: organizer.email,
credentialId: -1,
domainWideDelegationCredentialId: dwdCredentialId,
delegationCredentialId: delegationCredentialId,
},
],
},
@@ -129,7 +129,7 @@ describe("setDestinationCalendarHandler", () => {
integration: "google_calendar",
externalId: testExternalId,
credentialId: null,
domainWideDelegationCredentialId: dwdCredentialId,
delegationCredentialId: delegationCredentialId,
},
],
},
@@ -146,7 +146,7 @@ describe("setDestinationCalendarHandler", () => {
integration: "google_calendar",
externalId: testExternalId,
credentialId: null,
domainWideDelegationCredentialId: dwdCredentialId,
delegationCredentialId: delegationCredentialId,
},
],
} as NonNullable<TrpcSessionUser>,
@@ -172,7 +172,7 @@ describe("setDestinationCalendarHandler", () => {
integration: "google_calendar",
externalId: testExternalId,
credentialId: null,
domainWideDelegationCredentialId: dwdCredentialId,
delegationCredentialId: delegationCredentialId,
})
);
});
@@ -33,11 +33,11 @@ export const getFirstConnectedCalendar = ({
}) => {
const calendars = connectedCalendars.flatMap((c) => c.calendars ?? []);
const matchingCalendars = calendars.filter(matcher);
const dwdCredentialCalendar = matchingCalendars.find((cal) => !!cal.domainWideDelegationCredentialId);
const delegationCredentialCalendar = matchingCalendars.find((cal) => !!cal.delegationCredentialId);
// Prefer DWD credential calendar as there could be other one due to existing connections even after DWD is enabled.
if (dwdCredentialCalendar) {
return dwdCredentialCalendar;
// Prefer Delegation credential calendar as there could be other one due to existing connections even after DelegationCredential is enabled.
if (delegationCredentialCalendar) {
return delegationCredentialCalendar;
} else {
return matchingCalendars[0];
}
@@ -48,8 +48,8 @@ export const getFirstConnectedCalendar = ({
* 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.
* With the addition of Delegation credential, it adds another dimension to the problem.
* A user could have DelegationCredential and non-Delegation credential for the same calendar and he might be selecting Delegation credential connected calendar but it could still be set with nullish destinationCalendar.delegationCredentialId.
*/
export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinationCalendarOptions) => {
const { user } = ctx;
@@ -69,11 +69,11 @@ export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinati
cal.externalId === externalId && cal.integration === integration && cal.readOnly === false,
});
const { credentialId, domainWideDelegationCredentialId } = firstConnectedCalendar || {};
const { credentialId, delegationCredentialId } = firstConnectedCalendar || {};
let where;
if (!credentialId && !domainWideDelegationCredentialId) {
if (!credentialId && !delegationCredentialId) {
throw new TRPCError({ code: "BAD_REQUEST", message: `Could not find calendar ${input.externalId}` });
}
@@ -81,8 +81,7 @@ export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinati
allCals.find(
(cal) =>
cal.primary &&
(cal.credentialId === credentialId ||
cal.domainWideDelegationCredentialId === domainWideDelegationCredentialId)
(cal.credentialId === credentialId || cal.delegationCredentialId === delegationCredentialId)
)?.email ?? null;
if (eventTypeId) {
@@ -110,7 +109,7 @@ export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinati
externalId,
primaryEmail,
credentialId,
domainWideDelegationCredentialId,
delegationCredentialId,
},
create: {
...where,
@@ -118,7 +117,7 @@ export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinati
externalId,
primaryEmail,
credentialId,
domainWideDelegationCredentialId,
delegationCredentialId,
},
});
};
@@ -15,8 +15,8 @@ import { attributesRouter } from "./attributes/_router";
import { authRouter } from "./auth/_router";
import { availabilityRouter } from "./availability/_router";
import { bookingsRouter } from "./bookings/_router";
import { delegationCredentialRouter } from "./delegationCredential/_router";
import { deploymentSetupRouter } from "./deploymentSetup/_router";
import { domainWideDelegationRouter } from "./domainWideDelegation/_router";
import { dsyncRouter } from "./dsync/_router";
import { eventTypesRouter } from "./eventTypes/_router";
import { googleWorkspaceRouter } from "./googleWorkspace/_router";
@@ -45,7 +45,7 @@ export const viewerRouter = mergeRouters(
teams: viewerTeamsRouter,
timezones: timezonesRouter,
organizations: viewerOrganizationsRouter,
domainWideDelegation: domainWideDelegationRouter,
delegationCredential: delegationCredentialRouter,
webhook: webhookRouter,
apiKeys: apiKeysRouter,
slots: slotsRouter,
@@ -1,5 +1,5 @@
import { getAppFromSlug } from "@calcom/app-store/utils";
import { getAllDwdCredentialsForUserByAppSlug } from "@calcom/lib/domainWideDelegation/server";
import { getAllDelegationCredentialsForUserByAppSlug } from "@calcom/lib/delegationCredential/server";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "../../../trpc";
@@ -27,11 +27,11 @@ export const queryForDependenciesHandler = async ({ ctx, input }: QueryForDepend
},
});
const dwdCredentials = await getAllDwdCredentialsForUserByAppSlug({
const delegationCredentials = await getAllDelegationCredentialsForUserByAppSlug({
user: ctx.user,
appSlug: appId,
});
const appInstalled = !!dbCredential || !!dwdCredentials.length;
const appInstalled = !!dbCredential || !!delegationCredentials.length;
const app = getAppFromSlug(dependency);
@@ -1,6 +1,6 @@
import dayjs from "@calcom/dayjs";
import { getBusyCalendarTimes } from "@calcom/lib/CalendarManager";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "@calcom/lib/delegationCredential/server";
import { prisma } from "@calcom/prisma";
import type { EventBusyDate } from "@calcom/types/Calendar";
@@ -30,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 nonDwdCredentials = await prisma.credential.findMany({
const nonDelegationCredentials = await prisma.credential.findMany({
where: {
id: {
in: uniqueCredentialIds,
@@ -53,10 +53,10 @@ export const calendarOverlayHandler = async ({ ctx, input }: ListOptions) => {
},
});
const { credentials } = await enrichUserWithDwdCredentialsWithoutOrgId({
const { credentials } = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: {
...user,
credentials: nonDwdCredentials,
credentials: nonDelegationCredentials,
},
});
@@ -11,7 +11,7 @@ import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import { isPrismaObjOrUndefined } from "@calcom/lib";
import { CalendarEventBuilder } from "@calcom/lib/builders/CalendarEvent/builder";
import { CalendarEventDirector } from "@calcom/lib/builders/CalendarEvent/director";
import { getDwdOrRegularCredential } from "@calcom/lib/domainWideDelegation/server";
import { getDelegationCredentialOrRegularCredential } from "@calcom/lib/delegationCredential/server";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
@@ -240,22 +240,22 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
if (bookingRef.type.endsWith("_calendar")) {
const calendar = await getCalendar(
getDwdOrRegularCredential({
getDelegationCredentialOrRegularCredential({
credentials,
id: {
credentialId: bookingRef?.credentialId,
dwdId: bookingRef?.domainWideDelegationCredentialId,
delegationCredentialId: bookingRef?.delegationCredentialId,
},
})
);
return calendar?.deleteEvent(bookingRef.uid, builder.calendarEvent, bookingRef.externalCalendarId);
} else if (bookingRef.type.endsWith("_video")) {
return deleteMeeting(
getDwdOrRegularCredential({
getDelegationCredentialOrRegularCredential({
credentials,
id: {
credentialId: bookingRef?.credentialId,
dwdId: bookingRef?.domainWideDelegationCredentialId,
delegationCredentialId: bookingRef?.delegationCredentialId,
},
}),
bookingRef.uid
@@ -6,16 +6,16 @@ import { TRPCError } from "@trpc/server";
import authedProcedure, { authedOrgAdminProcedure } from "../../../procedures/authedProcedure";
import { router, importHandler } from "../../../trpc";
import {
DomainWideDelegationCreateSchema,
DomainWideDelegationUpdateSchema,
DomainWideDelegationDeleteSchema,
DomainWideDelegationToggleEnabledSchema,
DelegationCredentialCreateSchema,
DelegationCredentialUpdateSchema,
DelegationCredentialDeleteSchema,
DelegationCredentialToggleEnabledSchema,
} from "./schema";
const NAMESPACE = "domainWideDelegation";
const NAMESPACE = "delegationCredential";
const namespaced = (s: string) => `${NAMESPACE}.${s}`;
const checkDomainWideDelegationFeature = async ({
const checkDelegationCredentialFeature = async ({
ctx,
next,
}: {
@@ -33,41 +33,41 @@ const checkDomainWideDelegationFeature = async ({
});
}
const hasDomainWideDelegation = await featureRepo.checkIfTeamHasFeature(
const hasDelegationCredential = await featureRepo.checkIfTeamHasFeature(
user.organizationId,
"domain-wide-delegation"
"delegation-credential"
);
if (!hasDomainWideDelegation) {
if (!hasDelegationCredential) {
throw new TRPCError({
code: "FORBIDDEN",
message: t("domain_wide_delegation_feature_not_enabled"),
message: t("delegation_credential_feature_not_enabled"),
});
}
return next();
};
export const domainWideDelegationRouter = router({
list: authedOrgAdminProcedure.use(checkDomainWideDelegationFeature).query(async (opts) => {
export const delegationCredentialRouter = router({
list: authedOrgAdminProcedure.use(checkDelegationCredentialFeature).query(async (opts) => {
const handler = await importHandler(namespaced("list"), () => import("./list.handler"));
return handler(opts);
}),
update: authedOrgAdminProcedure
.use(checkDomainWideDelegationFeature)
.input(DomainWideDelegationUpdateSchema)
.use(checkDelegationCredentialFeature)
.input(DelegationCredentialUpdateSchema)
.mutation(async (opts) => {
const handler = await importHandler(namespaced("update"), () => import("./update.handler"));
return handler(opts);
}),
add: authedOrgAdminProcedure
.use(checkDomainWideDelegationFeature)
.input(DomainWideDelegationCreateSchema)
.use(checkDelegationCredentialFeature)
.input(DelegationCredentialCreateSchema)
.mutation(async (opts) => {
const handler = await importHandler(namespaced("add"), () => import("./add.handler"));
return handler(opts);
}),
toggleEnabled: authedOrgAdminProcedure
.use(checkDomainWideDelegationFeature)
.input(DomainWideDelegationToggleEnabledSchema)
.use(checkDelegationCredentialFeature)
.input(DelegationCredentialToggleEnabledSchema)
.mutation(async (opts) => {
const handler = await importHandler(
namespaced("toggleEnabled"),
@@ -76,13 +76,13 @@ export const domainWideDelegationRouter = router({
return handler(opts);
}),
delete: authedOrgAdminProcedure
.use(checkDomainWideDelegationFeature)
.input(DomainWideDelegationDeleteSchema)
.use(checkDelegationCredentialFeature)
.input(DelegationCredentialDeleteSchema)
.mutation(async (opts) => {
const handler = await importHandler(namespaced("delete"), () => import("./delete.handler"));
return handler(opts);
}),
listWorkspacePlatforms: authedProcedure.use(checkDomainWideDelegationFeature).query(async () => {
listWorkspacePlatforms: authedProcedure.use(checkDelegationCredentialFeature).query(async () => {
const handler = await importHandler(
namespaced("listWorkspacePlatforms"),
() => import("./listWorkspacePlatforms.handler")
@@ -1,22 +1,22 @@
import type { z } from "zod";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform";
import { TRPCError } from "@trpc/server";
import type { DomainWideDelegationCreateSchema } from "./schema";
import type { DelegationCredentialCreateSchema } from "./schema";
import {
ensureDomainWideDelegationNotAlreadyConfigured,
ensureDelegationCredentialNotAlreadyConfigured,
ensureNoServiceAccountKey,
handleDomainWideDelegationError,
handleDelegationCredentialError,
} from "./utils";
export default async function handler({
input,
ctx,
}: {
input: z.infer<typeof DomainWideDelegationCreateSchema>;
input: z.infer<typeof DelegationCredentialCreateSchema>;
ctx: { user: { id: number; organizationId: number | null } };
}) {
const { workspacePlatformSlug, domain, serviceAccountKey } = input;
@@ -26,7 +26,7 @@ export default async function handler({
if (!organizationId) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You must be part of an organization to add a domain-wide delegation",
message: "You must be part of an organization to add a delegation credential",
});
}
@@ -42,13 +42,13 @@ export default async function handler({
});
}
await ensureDomainWideDelegationNotAlreadyConfigured({
await ensureDelegationCredentialNotAlreadyConfigured({
domain,
currentOrganizationId: organizationId,
dwdBeingUpdatedId: null,
delegationCredentialBeingUpdatedId: null,
});
const createdDelegation = await DomainWideDelegationRepository.create({
const createdDelegation = await DelegationCredentialRepository.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.
@@ -59,6 +59,6 @@ export default async function handler({
return ensureNoServiceAccountKey(createdDelegation);
} catch (error) {
handleDomainWideDelegationError(error);
handleDelegationCredentialError(error);
}
}
@@ -0,0 +1,21 @@
import type z from "zod";
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
import { TRPCError } from "@trpc/server";
import type { DelegationCredentialDeleteSchema } from "./schema";
export default async function handler({
input,
}: {
input: z.infer<typeof DelegationCredentialDeleteSchema>;
}) {
const { id } = input;
// We might want to consider allowing this in the future. Right now, toggling off DelegationCredential achieves similar but non-destructive effect
throw new TRPCError({ code: "BAD_REQUEST", message: "Not allowed" });
await DelegationCredentialRepository.deleteById({ id });
return { id };
}
@@ -1,4 +1,4 @@
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
import { encryptedServiceAccountKeySchema } from "@calcom/lib/server/serviceAccountKey";
import type { PrismaClient } from "@calcom/prisma";
@@ -14,14 +14,14 @@ export default async function handler({
const organizationId = user.organization?.id;
if (!organizationId) {
throw new Error("You must be in an organization to list domain wide delegations");
throw new Error("You must be in an organization to list delegation credentials");
}
const domainWideDelegations =
await DomainWideDelegationRepository.findByOrgIdIncludeSensitiveServiceAccountKey({
const delegationCredentials =
await DelegationCredentialRepository.findByOrgIdIncludeSensitiveServiceAccountKey({
organizationId,
});
return domainWideDelegations.map((delegation) => {
return delegationCredentials.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 = encryptedServiceAccountKeySchema.safeParse(delegation.serviceAccountKey);
@@ -2,23 +2,23 @@ import { z } from "zod";
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
export const DomainWideDelegationCreateSchema = z.object({
export const DelegationCredentialCreateSchema = z.object({
workspacePlatformSlug: z.string(),
domain: z.string(),
serviceAccountKey: serviceAccountKeySchema,
});
export const DomainWideDelegationUpdateSchema = z.object({
export const DelegationCredentialUpdateSchema = z.object({
id: z.string(),
workspacePlatformSlug: z.string(),
domain: z.string(),
});
export const DomainWideDelegationToggleEnabledSchema = z.object({
export const DelegationCredentialToggleEnabledSchema = z.object({
id: z.string(),
enabled: z.boolean(),
});
export const DomainWideDelegationDeleteSchema = z.object({
export const DelegationCredentialDeleteSchema = z.object({
id: z.string(),
});
@@ -1,11 +1,11 @@
import type { z } from "zod";
import { checkIfSuccessfullyConfiguredInWorkspace } from "@calcom/lib/domainWideDelegation/server";
import { checkIfSuccessfullyConfiguredInWorkspace } from "@calcom/lib/delegationCredential/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 { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
import type { ServiceAccountKey } from "@calcom/lib/server/repository/delegationCredential";
import type { DomainWideDelegationToggleEnabledSchema } from "./schema";
import type { DelegationCredentialToggleEnabledSchema } from "./schema";
import { ensureNoServiceAccountKey } from "./utils";
type LoggedInUser = {
@@ -23,7 +23,7 @@ export default async function toggleEnabledHandler({
ctx: {
user: LoggedInUser;
};
input: z.infer<typeof DomainWideDelegationToggleEnabledSchema>;
input: z.infer<typeof DelegationCredentialToggleEnabledSchema>;
}) {
const { user: loggedInUser } = ctx;
const t = await getTranslation(ctx.user.locale ?? "en", "common");
@@ -32,51 +32,53 @@ export default async function toggleEnabledHandler({
throw new Error(t("verify_your_email"));
}
return toggleDwdEnabled(loggedInUser, input);
return toggleDelegationCredentialEnabled(loggedInUser, input);
}
export async function toggleDwdEnabled(
export async function toggleDelegationCredentialEnabled(
loggedInUser: Omit<LoggedInUser, "locale" | "emailVerified">,
input: z.infer<typeof DomainWideDelegationToggleEnabledSchema>
input: z.infer<typeof DelegationCredentialToggleEnabledSchema>
) {
if (input.enabled) {
await assertWorkspaceConfigured({
domainWideDelegationId: input.id,
delegationCredentialId: input.id,
user: loggedInUser,
});
}
const updatedDomainWideDelegation = await DomainWideDelegationRepository.updateById({
const updatedDelegationCredential = await DelegationCredentialRepository.updateById({
id: input.id,
data: {
enabled: input.enabled,
},
});
return ensureNoServiceAccountKey(updatedDomainWideDelegation);
return ensureNoServiceAccountKey(updatedDelegationCredential);
}
const assertWorkspaceConfigured = async ({
domainWideDelegationId,
delegationCredentialId,
user,
}: {
domainWideDelegationId: string;
delegationCredentialId: string;
user: { id: number; email: string; organizationId: number | null };
}) => {
const dwd = await DomainWideDelegationRepository.findByIdIncludeSensitiveServiceAccountKey({
id: domainWideDelegationId,
});
const delegationCredential = await DelegationCredentialRepository.findByIdIncludeSensitiveServiceAccountKey(
{
id: delegationCredentialId,
}
);
if (!dwd) {
if (!delegationCredential) {
throw new Error("Domain wide delegation not found");
}
if (!hasServiceAccountKey(dwd)) {
if (!hasServiceAccountKey(delegationCredential)) {
throw new Error("Domain wide delegation doesn't have service account key");
}
const isSuccessfullyConfigured = await checkIfSuccessfullyConfiguredInWorkspace({
dwd,
delegationCredential,
user,
});
@@ -86,7 +88,7 @@ const assertWorkspaceConfigured = async ({
};
function hasServiceAccountKey<T extends { serviceAccountKey: ServiceAccountKey | null }>(
domainWideDelegation: T
): domainWideDelegation is T & { serviceAccountKey: ServiceAccountKey } {
return domainWideDelegation.serviceAccountKey !== null;
delegationCredential: T
): delegationCredential is T & { serviceAccountKey: ServiceAccountKey } {
return delegationCredential.serviceAccountKey !== null;
}
@@ -1,22 +1,22 @@
import type { z } from "zod";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
import { WorkspacePlatformRepository } from "@calcom/lib/server/repository/workspacePlatform";
import { TRPCError } from "@trpc/server";
import type { DomainWideDelegationUpdateSchema } from "./schema";
import type { DelegationCredentialUpdateSchema } from "./schema";
import {
ensureDomainWideDelegationNotAlreadyConfigured,
ensureDelegationCredentialNotAlreadyConfigured,
ensureNoServiceAccountKey,
handleDomainWideDelegationError,
handleDelegationCredentialError,
} from "./utils";
export default async function handler({
input,
ctx,
}: {
input: z.infer<typeof DomainWideDelegationUpdateSchema>;
input: z.infer<typeof DelegationCredentialUpdateSchema>;
ctx: { user: { id: number; organizationId: number | null } };
}) {
const { id, workspacePlatformSlug, domain } = input;
@@ -26,14 +26,14 @@ export default async function handler({
if (!organizationId) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You must be part of an organization to update a domain wide delegation",
message: "You must be part of an organization to update a delegation credential",
});
}
await ensureDomainWideDelegationNotAlreadyConfigured({
await ensureDelegationCredentialNotAlreadyConfigured({
domain,
currentOrganizationId: organizationId,
dwdBeingUpdatedId: id,
delegationCredentialBeingUpdatedId: id,
});
try {
@@ -48,7 +48,7 @@ export default async function handler({
});
}
const updatedDelegation = await DomainWideDelegationRepository.updateById({
const updatedDelegation = await DelegationCredentialRepository.updateById({
id,
data: {
workspacePlatformId: workspacePlatform.id,
@@ -59,6 +59,6 @@ export default async function handler({
return ensureNoServiceAccountKey(updatedDelegation);
} catch (error) {
handleDomainWideDelegationError(error);
handleDelegationCredentialError(error);
}
}
@@ -2,12 +2,12 @@ import { z } from "zod";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
import type { Prisma } from "@calcom/prisma/client";
import { TRPCError } from "@trpc/server";
const log = logger.getSubLogger({ prefix: ["domainWideDelegation/utils"] });
const log = logger.getSubLogger({ prefix: ["delegationCredential/utils"] });
export class InvalidServiceAccountKeyError extends Error {
constructor(message: string) {
super(message);
@@ -15,27 +15,29 @@ export class InvalidServiceAccountKeyError extends Error {
}
}
export async function ensureDomainWideDelegationNotAlreadyConfigured({
export async function ensureDelegationCredentialNotAlreadyConfigured({
domain,
currentOrganizationId,
dwdBeingUpdatedId,
delegationCredentialBeingUpdatedId,
}: {
domain: string;
currentOrganizationId: number;
dwdBeingUpdatedId: string | null;
delegationCredentialBeingUpdatedId: string | null;
}) {
const allDelegationsForDomain = await DomainWideDelegationRepository.findAllByDomain({
const allDelegationsForDomain = await DelegationCredentialRepository.findAllByDomain({
domain,
});
const conflictingDelegationInCurrentOrg = allDelegationsForDomain.find(
(delegation) => delegation.organizationId === currentOrganizationId && delegation.id !== dwdBeingUpdatedId
(delegation) =>
delegation.organizationId === currentOrganizationId &&
delegation.id !== delegationCredentialBeingUpdatedId
);
if (conflictingDelegationInCurrentOrg) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Your organization already has domain-wide delegation for ${conflictingDelegationInCurrentOrg.domain}`,
message: `Your organization already has delegation credential for ${conflictingDelegationInCurrentOrg.domain}`,
});
}
@@ -46,7 +48,7 @@ export async function ensureDomainWideDelegationNotAlreadyConfigured({
if (differentOrgEnabledDelegations.length > 0) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Domain ${domain} already has domain-wide delegation enabled in another organization`,
message: `Domain ${domain} already has delegation credential enabled in another organization`,
});
}
}
@@ -73,7 +75,7 @@ export function parseServiceAccountKey(serviceAccountKey: Prisma.JsonValue) {
return parsedServiceAccountKey.data;
}
export const handleDomainWideDelegationError = (error: unknown) => {
export const handleDelegationCredentialError = (error: unknown) => {
if (error instanceof InvalidServiceAccountKeyError) {
throw new TRPCError({
code: "BAD_REQUEST",
@@ -85,20 +87,20 @@ export const handleDomainWideDelegationError = (error: unknown) => {
throw error;
}
log.error("Error handling domain-wide delegation:", safeStringify(error));
log.error("Error handling delegation credential:", safeStringify(error));
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "An error occurred while handling domain-wide delegation settings.",
message: "An error occurred while handling delegation credential settings.",
});
};
export const ensureNoServiceAccountKey = <T extends { id: string; serviceAccountKey?: unknown } | null>(
domainWideDelegation: T
delegationCredential: T
) => {
if (!domainWideDelegation) {
if (!delegationCredential) {
return null;
}
const { serviceAccountKey: _1, ...rest } = domainWideDelegation;
const { serviceAccountKey: _1, ...rest } = delegationCredential;
return {
...rest,
serviceAccountKey: undefined,
@@ -1,21 +0,0 @@
import type z from "zod";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import { TRPCError } from "@trpc/server";
import type { DomainWideDelegationDeleteSchema } from "./schema";
export default async function handler({
input,
}: {
input: z.infer<typeof DomainWideDelegationDeleteSchema>;
}) {
const { id } = input;
// 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 };
}
@@ -27,15 +27,15 @@ export const listHandler = async ({ ctx }: ListHandlerInput) => {
}
const featureRepo = new FeaturesRepository();
const hasDomainWideDelegation = await featureRepo.checkIfTeamHasFeature(
const hasDelegationCredential = await featureRepo.checkIfTeamHasFeature(
organizationId,
"domain-wide-delegation"
"delegation-credential"
);
return {
...currentOrg,
features: {
domainWideDelegation: hasDomainWideDelegation,
delegationCredential: hasDelegationCredential,
},
};
};
@@ -9,7 +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 { enrichHostsWithDelegationCredentials } from "@calcom/lib/delegationCredential/server";
import { entityPrismaWhereClause } from "@calcom/lib/entityPermissionUtils";
import { fromEntriesWithDuplicateKeys } from "@calcom/lib/fromEntriesWithDuplicateKeys";
import { findTeamMembersMatchingAttributeLogic } from "@calcom/lib/raqb/findTeamMembersMatchingAttributeLogic";
@@ -256,7 +256,7 @@ export const findTeamMembersMatchingAttributeLogicOfRouteHandler = async ({
const matchingTeamMembersIds = matchingTeamMembersWithResult.map((member) => member.userId);
const matchingTeamMembers = await UserRepository.findByIds({ ids: matchingTeamMembersIds });
const matchingHosts = await enrichHostsWithDwdCredentials({
const matchingHosts = await enrichHostsWithDelegationCredentials({
orgId: formOrgId,
hosts: eventType.hosts.filter((host) => matchingTeamMembersIds.includes(host.user.id)),
});
@@ -10,7 +10,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 { findQualifiedHostsWithDwdCredentials } from "@calcom/lib/bookings/findQualifiedHostsWithDwdCredentials";
import { findQualifiedHostsWithDelegationCredentials } from "@calcom/lib/bookings/findQualifiedHostsWithDelegationCredentials";
import { shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";
import { RESERVED_SUBDOMAINS } from "@calcom/lib/constants";
import { getUTCOffsetByTimezone } from "@calcom/lib/date-fns";
@@ -44,10 +44,10 @@ import type { TGetScheduleInputSchema } from "./getSchedule.schema";
import { handleNotificationWhenNoSlots } from "./handleNotificationWhenNoSlots";
const log = logger.getSubLogger({ prefix: ["[slots/util]"] });
type GetAvailabilityUserWithoutDwdCredentials = Omit<GetAvailabilityUser, "credentials"> & {
type GetAvailabilityUserWithoutDelegationCredentials = Omit<GetAvailabilityUser, "credentials"> & {
credentials: CredentialPayload[];
};
type GetAvailabilityUserWithDwdCredentials = Omit<GetAvailabilityUser, "credentials"> & {
type GetAvailabilityUserWithDelegationCredentials = Omit<GetAvailabilityUser, "credentials"> & {
credentials: CredentialForCalendarService[];
};
const selectSelectedSlots = Prisma.validator<Prisma.SelectedSlotsDefaultArgs>()({
@@ -272,7 +272,7 @@ export function getUsersWithCredentials({
}: {
hosts: {
isFixed?: boolean;
user: GetAvailabilityUserWithDwdCredentials;
user: GetAvailabilityUserWithDelegationCredentials;
}[];
}) {
return hosts.map(({ isFixed, user }) => ({ isFixed, ...user }));
@@ -381,7 +381,7 @@ async function _getAvailableSlots({ input, ctx }: GetScheduleOptions): Promise<I
}
const { qualifiedRRHosts, allFallbackRRHosts, fixedHosts } = await monitorCallbackAsync(
findQualifiedHostsWithDwdCredentials<GetAvailabilityUserWithoutDwdCredentials>,
findQualifiedHostsWithDelegationCredentials<GetAvailabilityUserWithoutDelegationCredentials>,
{
eventType,
rescheduleUid: input.rescheduleUid ?? null,
@@ -956,7 +956,7 @@ const calculateHostsAndAvailabilities = async ({
eventType: Exclude<Awaited<ReturnType<typeof getRegularOrDynamicEventType>>, null>;
hosts: {
isFixed?: boolean;
user: GetAvailabilityUserWithDwdCredentials;
user: GetAvailabilityUserWithDelegationCredentials;
}[];
loggerWithEventDetails: Logger<unknown>;
startTime: ReturnType<typeof getStartTime>;
@@ -1,4 +1,4 @@
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "@calcom/lib/delegationCredential/server";
import { getUserAvailability } from "@calcom/lib/getUserAvailability";
import { isTeamMember } from "@calcom/lib/server/queries/teams";
import { MembershipRepository } from "@calcom/lib/server/repository/membership";
@@ -27,7 +27,7 @@ export const getMemberAvailabilityHandler = async ({ ctx, input }: GetMemberAvai
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({
const user = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: member.user,
});
@@ -1,7 +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 { enrichUsersWithDelegationCredentials } from "@calcom/lib/delegationCredential/server";
import { ErrorCode } from "@calcom/lib/errorCodes";
import logger from "@calcom/lib/logger";
import { withSelectedCalendars } from "@calcom/lib/server/repository/user";
@@ -87,7 +87,7 @@ async function getTeamHostsFromDB({
}));
return {
hosts: await enrichUsersWithDwdCredentials({
hosts: await enrichUsersWithDelegationCredentials({
orgId: organizationId,
users: hostsMergedWithUser,
}),