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

+8 -6
View File
@@ -1,7 +1,7 @@
import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { getAppFromSlug } from "@calcom/app-store/utils";
import getInstallCountPerApp from "@calcom/lib/apps/getInstallCountPerApp";
import { getAllDwdCredentialsForUser } from "@calcom/lib/domainWideDelegation/server";
import { getAllDelegationCredentialsForUser } from "@calcom/lib/delegationCredential/server";
import type { UserAdminTeams } from "@calcom/lib/server/repository/user";
import prisma, { safeAppSelect, safeCredentialSelect } from "@calcom/prisma";
import { userMetadata } from "@calcom/prisma/zod-utils";
@@ -92,8 +92,8 @@ export async function getAppRegistryWithCredentials(userId: number, userAdminTea
},
});
const dwdCredentials = user
? await getAllDwdCredentialsForUser({ user: { id: userId, email: user.email } })
const delegationCredentials = user
? await getAllDelegationCredentialsForUser({ user: { id: userId, email: user.email } })
: [];
const usersDefaultApp = userMetadata.parse(user?.metadata)?.defaultConferencingApp?.appSlug;
@@ -103,9 +103,11 @@ export async function getAppRegistryWithCredentials(userId: number, userAdminTea
})[];
const installCountPerApp = await getInstallCountPerApp();
for await (const dbapp of dbApps) {
const dwdCredentialsForApp = dwdCredentials.filter((credential) => credential.appId === dbapp.slug);
const nonDwdCredentialsForApp = dbapp.credentials;
const allCredentials = [...dwdCredentialsForApp, ...nonDwdCredentialsForApp];
const delegationCredentialsForApp = delegationCredentials.filter(
(credential) => credential.appId === dbapp.slug
);
const nonDelegationCredentialsForApp = dbapp.credentials;
const allCredentials = [...delegationCredentialsForApp, ...nonDelegationCredentialsForApp];
const app = await getAppWithMetadata(dbapp);
if (!app) continue;
// Skip if app isn't installed
@@ -19,7 +19,7 @@ export const metadata = {
email: "[email protected]",
dirName: "googlecalendar",
isOAuth: true,
domainWideDelegation: {
delegationCredential: {
// This is unused at the moment but should be used in future
// For now, we have hardcoded imports in the codebase that are supported with Google Workspace(i.e. Google Calendar and Google Meet)
workspacePlatformSlug: "google",
@@ -1,6 +1,6 @@
import type { NextApiRequest } from "next";
import { buildNonDwdCredential } from "@calcom/lib/domainWideDelegation/server";
import { buildNonDelegationCredential } from "@calcom/lib/delegationCredential/server";
import { HttpError } from "@calcom/lib/http-error";
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
@@ -38,7 +38,7 @@ async function postHandler(req: NextApiRequest) {
});
const { selectedCalendars } = credential;
const calendar = await getCalendar(buildNonDwdCredential(credential));
const calendar = await getCalendar(buildNonDelegationCredential(credential));
// Make sure to pass unique SelectedCalendars to avoid unnecessary third party api calls
// Necessary to do here so that it is ensure for all calendar apps
@@ -295,7 +295,7 @@ describe("Watching and unwatching calendar", () => {
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
domainWideDelegationCredentialId: null,
delegationCredentialId: null,
googleChannelId: "mock-channel-id",
googleChannelKind: "api#channel",
googleChannelResourceId: "mock-resource-id",
@@ -325,7 +325,7 @@ describe("Watching and unwatching calendar", () => {
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
domainWideDelegationCredentialId: null,
delegationCredentialId: null,
googleChannelId: null,
googleChannelKind: null,
googleChannelResourceId: null,
@@ -711,13 +711,13 @@ describe("GoogleCalendarService credential handling", () => {
return mockJWTInstance;
};
test("uses JWT auth with impersonation when DWD credential is provided", async () => {
const credentialWithDWD = await createCredentialInDb({
test("uses JWT auth with impersonation when Delegation credential is provided", async () => {
const credentialWithDelegation = await createCredentialInDb({
user: { email: "[email protected]" },
delegatedTo: delegatedCredential,
});
const calendarService = new CalendarService(credentialWithDWD);
const calendarService = new CalendarService(credentialWithDelegation);
await calendarService.listCalendars();
const expectedJWTConfig: MockJWT = {
@@ -738,7 +738,7 @@ describe("GoogleCalendarService credential handling", () => {
});
});
test("uses OAuth2 auth when no DWD credential is provided", async () => {
test("uses OAuth2 auth when no Delegation credential is provided", async () => {
const regularCredential = await createCredentialInDb();
const { client_id, client_secret, redirect_uris } = await getGoogleAppKeys();
@@ -762,8 +762,8 @@ describe("GoogleCalendarService credential handling", () => {
});
});
test("handles DWD authorization errors appropriately", async () => {
const credentialWithDWD = await createCredentialInDb({
test("handles DelegationCredential authorization errors appropriately", async () => {
const credentialWithDelegation = await createCredentialInDb({
user: { email: "[email protected]" },
delegatedTo: delegatedCredential,
});
@@ -778,15 +778,15 @@ describe("GoogleCalendarService credential handling", () => {
},
});
const calendarService = new CalendarService(credentialWithDWD);
const calendarService = new CalendarService(credentialWithDelegation);
await expect(calendarService.listCalendars()).rejects.toThrow(
"Make sure that the Client ID for the domain wide delegation is added to the Google Workspace Admin Console"
"Make sure that the Client ID for the delegation credential is added to the Google Workspace Admin Console"
);
});
test("handles invalid_grant error (user not in workspace) appropriately", async () => {
const credentialWithDWD = await createCredentialInDb({
const credentialWithDelegation = await createCredentialInDb({
user: { email: "[email protected]" },
delegatedTo: delegatedCredential,
});
@@ -801,13 +801,13 @@ describe("GoogleCalendarService credential handling", () => {
},
});
const calendarService = new CalendarService(credentialWithDWD);
const calendarService = new CalendarService(credentialWithDelegation);
await expect(calendarService.listCalendars()).rejects.toThrow("User might not exist in Google Workspace");
});
test("handles general DWD authorization errors appropriately", async () => {
const credentialWithDWD = await createCredentialInDb({
test("handles general DelegationCredential authorization errors appropriately", async () => {
const credentialWithDelegation = await createCredentialInDb({
user: { email: "[email protected]" },
delegatedTo: delegatedCredential,
});
@@ -816,18 +816,18 @@ describe("GoogleCalendarService credential handling", () => {
authorizeError: new Error("Some unexpected error"),
});
const calendarService = new CalendarService(credentialWithDWD);
const calendarService = new CalendarService(credentialWithDelegation);
await expect(calendarService.listCalendars()).rejects.toThrow("Error authorizing domain wide delegation");
await expect(calendarService.listCalendars()).rejects.toThrow("Error authorizing delegation credential");
});
test("handles missing user email for DWD appropriately", async () => {
const credentialWithDWD = await createCredentialInDb({
test("handles missing user email for DelegationCredential appropriately", async () => {
const credentialWithDelegation = await createCredentialInDb({
user: { email: null },
delegatedTo: delegatedCredential,
});
const calendarService = new CalendarService(credentialWithDWD);
const calendarService = new CalendarService(credentialWithDelegation);
const { client_id, client_secret, redirect_uris } = await getGoogleAppKeys();
await calendarService.listCalendars();
@@ -13,9 +13,9 @@ import type { FreeBusyArgs } from "@calcom/features/calendar-cache/calendar-cach
import { getTimeMax, getTimeMin } from "@calcom/features/calendar-cache/lib/datesForCache";
import { getLocation, getRichDescription } from "@calcom/lib/CalEventParser";
import {
CalendarAppDomainWideDelegationClientIdNotAuthorizedError,
CalendarAppDomainWideDelegationInvalidGrantError,
CalendarAppDomainWideDelegationError,
CalendarAppDelegationCredentialClientIdNotAuthorizedError,
CalendarAppDelegationCredentialInvalidGrantError,
CalendarAppDelegationCredentialError,
} from "@calcom/lib/CalendarAppError";
import { uniqueBy } from "@calcom/lib/array";
import {
@@ -180,12 +180,12 @@ export default class GoogleCalendarService implements Calendar {
};
};
private getAuthedCalendarFromDwd = async ({
domainWideDelegation,
private getAuthedCalendarFromDelegationCredential = async ({
delegationCredential,
emailToImpersonate,
}: {
emailToImpersonate: string;
domainWideDelegation: {
delegationCredential: {
serviceAccountKey: {
client_email: string;
client_id: string;
@@ -193,9 +193,9 @@ export default class GoogleCalendarService implements Calendar {
};
};
}) => {
const serviceAccountClientEmail = domainWideDelegation.serviceAccountKey.client_email;
const serviceAccountClientId = domainWideDelegation.serviceAccountKey.client_id;
const serviceAccountPrivateKey = domainWideDelegation.serviceAccountKey.private_key;
const serviceAccountClientEmail = delegationCredential.serviceAccountKey.client_email;
const serviceAccountClientId = delegationCredential.serviceAccountKey.client_id;
const serviceAccountPrivateKey = delegationCredential.serviceAccountKey.private_key;
const authClient = new JWT({
email: serviceAccountClientEmail,
@@ -207,26 +207,26 @@ export default class GoogleCalendarService implements Calendar {
try {
await authClient.authorize();
} catch (error) {
this.log.error("DWD: Error authorizing domain wide delegation", JSON.stringify(error));
this.log.error("DelegationCredential: Error authorizing delegation credential", JSON.stringify(error));
if ((error as any).response?.data?.error === "unauthorized_client") {
throw new CalendarAppDomainWideDelegationClientIdNotAuthorizedError(
"Make sure that the Client ID for the domain wide delegation is added to the Google Workspace Admin Console"
throw new CalendarAppDelegationCredentialClientIdNotAuthorizedError(
"Make sure that the Client ID for the delegation credential is added to the Google Workspace Admin Console"
);
}
if ((error as any).response?.data?.error === "invalid_grant") {
throw new CalendarAppDomainWideDelegationInvalidGrantError(
throw new CalendarAppDelegationCredentialInvalidGrantError(
"User might not exist in Google Workspace"
);
}
// Catch all error
throw new CalendarAppDomainWideDelegationError("Error authorizing domain wide delegation");
throw new CalendarAppDelegationCredentialError("Error authorizing delegation credential");
}
this.log.debug(
"Using domain wide delegation with service account email",
"Using delegation credential with service account email",
safeStringify({
serviceAccountClientEmail,
serviceAccountClientId,
@@ -240,22 +240,22 @@ export default class GoogleCalendarService implements Calendar {
};
public authedCalendar = async () => {
let dwdAuthedCalendar;
let delegationCredentialAuthedCalendar;
if (this.credential.delegatedTo) {
if (!this.credential.user?.email) {
this.log.error("DWD: No email to impersonate found for domain wide delegation");
this.log.error("DelegationCredential: No email to impersonate found for delegation credential");
} else {
const oauthClientIdAliasRegex = /\+[a-zA-Z0-9]{25}/;
dwdAuthedCalendar = await this.getAuthedCalendarFromDwd({
domainWideDelegation: this.credential.delegatedTo,
delegationCredentialAuthedCalendar = await this.getAuthedCalendarFromDelegationCredential({
delegationCredential: this.credential.delegatedTo,
emailToImpersonate: this.credential.user.email.replace(oauthClientIdAliasRegex, ""),
});
}
}
if (dwdAuthedCalendar) {
return dwdAuthedCalendar;
if (delegationCredentialAuthedCalendar) {
return delegationCredentialAuthedCalendar;
}
const myGoogleAuth = await this.auth.getMyGoogleAuthWithRefreshedToken();
@@ -865,8 +865,8 @@ export default class GoogleCalendarService implements Calendar {
}
}
// It would error if the domain wide delegation is not set up correctly
async testDomainWideDelegationSetup() {
// It would error if the delegation credential is not set up correctly
async testDelegationCredentialSetup() {
const calendar = await this.authedCalendar();
const cals = await calendar.calendarList.list({ fields: "items(id)" });
return !!cals.data.items;
@@ -4,8 +4,8 @@ import type { DefaultBodyType } from "msw";
import dayjs from "@calcom/dayjs";
import { getLocation, getRichDescription } from "@calcom/lib/CalEventParser";
import {
CalendarAppDomainWideDelegationInvalidGrantError,
CalendarAppDomainWideDelegationConfigurationError,
CalendarAppDelegationCredentialInvalidGrantError,
CalendarAppDelegationCredentialConfigurationError,
} from "@calcom/lib/CalendarAppError";
import { handleErrorsJson, handleErrorsRaw } from "@calcom/lib/errors";
import logger from "@calcom/lib/logger";
@@ -72,27 +72,24 @@ export default class Office365CalendarService implements Calendar {
appSlug: metadata.slug,
currentTokenObject: tokenResponse,
fetchNewTokenObject: async ({ refreshToken }: { refreshToken: string | null }) => {
const isDomainWideDelegated = Boolean(credential?.delegatedTo);
const isDelegated = Boolean(credential?.delegatedTo);
if (!isDomainWideDelegated && !refreshToken) {
if (!isDelegated && !refreshToken) {
return null;
}
const { client_id, client_secret } = await this.getAuthCredentials(isDomainWideDelegated);
const { client_id, client_secret } = await this.getAuthCredentials(isDelegated);
const url = this.getAuthUrl(
isDomainWideDelegated,
credential?.delegatedTo?.serviceAccountKey?.tenant_id
);
const url = this.getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
const bodyParams = {
scope: isDomainWideDelegated
scope: isDelegated
? "https://graph.microsoft.com/.default"
: "User.Read Calendars.Read Calendars.ReadWrite",
client_id,
client_secret,
grant_type: isDomainWideDelegated ? "client_credentials" : "refresh_token",
...(isDomainWideDelegated ? {} : { refresh_token: refreshToken ?? "" }),
grant_type: isDelegated ? "client_credentials" : "refresh_token",
...(isDelegated ? {} : { refresh_token: refreshToken ?? "" }),
};
return fetch(url, {
@@ -127,8 +124,8 @@ export default class Office365CalendarService implements Calendar {
private getAuthUrl(delegatedTo: boolean, tenantId?: string): string {
if (delegatedTo) {
if (!tenantId) {
throw new CalendarAppDomainWideDelegationInvalidGrantError(
"Invalid DomainWideDelegation Settings: tenantId is missing"
throw new CalendarAppDelegationCredentialInvalidGrantError(
"Invalid DelegationCredential Settings: tenantId is missing"
);
}
return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
@@ -137,14 +134,14 @@ export default class Office365CalendarService implements Calendar {
return "https://login.microsoftonline.com/common/oauth2/v2.0/token";
}
private async getAuthCredentials(isDomainWideDelegated: boolean) {
if (isDomainWideDelegated) {
private async getAuthCredentials(isDelegated: boolean) {
if (isDelegated) {
const client_id = this.credential?.delegatedTo?.serviceAccountKey?.client_id;
const client_secret = this.credential?.delegatedTo?.serviceAccountKey?.private_key;
if (!client_id || !client_secret) {
throw new CalendarAppDomainWideDelegationConfigurationError(
"Domain Wide Delegated credential without clientId or Secret"
throw new CalendarAppDelegationCredentialConfigurationError(
"Delegation credential without clientId or Secret"
);
}
@@ -157,18 +154,18 @@ export default class Office365CalendarService implements Calendar {
private async getAzureUserId(credential: CredentialForCalendarServiceWithTenantId) {
if (this.azureUserId) return this.azureUserId;
const isDomainWideDelegated = Boolean(credential?.delegatedTo);
const isDelegated = Boolean(credential?.delegatedTo);
if (!isDomainWideDelegated) return;
if (!isDelegated) return;
const url = this.getAuthUrl(isDomainWideDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
const url = this.getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
const dwdClientId = credential.delegatedTo?.serviceAccountKey?.client_id;
const dwdClientSecret = credential.delegatedTo?.serviceAccountKey?.private_key;
const delegationCredentialClientId = credential.delegatedTo?.serviceAccountKey?.client_id;
const delegationCredentialClientSecret = credential.delegatedTo?.serviceAccountKey?.private_key;
if (!dwdClientId || !dwdClientSecret) {
throw new CalendarAppDomainWideDelegationConfigurationError(
"Domain Wide Delegated credential without clientId or Secret"
if (!delegationCredentialClientId || !delegationCredentialClientSecret) {
throw new CalendarAppDelegationCredentialConfigurationError(
"Delegation credential without clientId or Secret"
);
}
const loginResponse = await fetch(url, {
@@ -176,9 +173,9 @@ export default class Office365CalendarService implements Calendar {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
scope: "https://graph.microsoft.com/.default",
client_id: dwdClientId,
client_id: delegationCredentialClientId,
grant_type: "client_credentials",
client_secret: dwdClientSecret,
client_secret: delegationCredentialClientSecret,
}),
});
@@ -202,7 +199,7 @@ export default class Office365CalendarService implements Calendar {
const parsedBody = await response.json();
if (!parsedBody?.value?.[0]?.id) {
throw new CalendarAppDomainWideDelegationInvalidGrantError(
throw new CalendarAppDelegationCredentialInvalidGrantError(
"User might not exist in Microsoft Azure Active Directory"
);
}
@@ -211,16 +208,16 @@ export default class Office365CalendarService implements Calendar {
return this.azureUserId;
}
// It would error if the domain wide delegation is not set up correctly
async testDomainWideDelegationSetup(): Promise<boolean> {
const dwdClientId = this.credential.delegatedTo?.serviceAccountKey?.client_id;
const dwdClientSecret = this.credential.delegatedTo?.serviceAccountKey?.private_key;
// It would error if the delegation credential is not set up correctly
async testDelegationCredentialSetup(): Promise<boolean> {
const delegationCredentialClientId = this.credential.delegatedTo?.serviceAccountKey?.client_id;
const delegationCredentialClientSecret = this.credential.delegatedTo?.serviceAccountKey?.private_key;
const url = this.getAuthUrl(
Boolean(this.credential?.delegatedTo),
this.credential?.delegatedTo?.serviceAccountKey?.tenant_id
);
if (!dwdClientId || !dwdClientSecret) {
if (!delegationCredentialClientId || !delegationCredentialClientSecret) {
return false;
}
const loginResponse = await fetch(url, {
@@ -228,9 +225,9 @@ export default class Office365CalendarService implements Calendar {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
scope: "https://graph.microsoft.com/.default",
client_id: dwdClientId,
client_id: delegationCredentialClientId,
grant_type: "client_credentials",
client_secret: dwdClientSecret,
client_secret: delegationCredentialClientSecret,
}),
});
const parsedLoginResponse = await loginResponse.json();
@@ -1,8 +1,8 @@
import { z } from "zod";
import {
CalendarAppDomainWideDelegationConfigurationError,
CalendarAppDomainWideDelegationInvalidGrantError,
CalendarAppDelegationCredentialConfigurationError,
CalendarAppDelegationCredentialInvalidGrantError,
} from "@calcom/lib/CalendarAppError";
import { handleErrorsRaw } from "@calcom/lib/errors";
import { HttpError } from "@calcom/lib/http-error";
@@ -49,26 +49,26 @@ const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenant
appSlug: config.slug,
currentTokenObject: tokenResponse,
fetchNewTokenObject: async ({ refreshToken }: { refreshToken: string | null }) => {
const isDomainWideDelegated = Boolean(credential?.delegatedTo);
if (!isDomainWideDelegated && !refreshToken) {
const isDelegated = Boolean(credential?.delegatedTo);
if (!isDelegated && !refreshToken) {
return null;
}
const credentials = isDomainWideDelegated
const credentials = isDelegated
? {
client_id: credential?.delegatedTo?.serviceAccountKey?.client_id,
client_secret: credential?.delegatedTo?.serviceAccountKey?.private_key,
}
: await getO365VideoAppKeys();
if (isDomainWideDelegated && (!credentials.client_id || !credentials.client_secret)) {
throw new CalendarAppDomainWideDelegationConfigurationError(
"Domain Wide Delegated credential without clientId or Secret"
if (isDelegated && (!credentials.client_id || !credentials.client_secret)) {
throw new CalendarAppDelegationCredentialConfigurationError(
"Delegation credential without clientId or Secret"
);
}
const url = getAuthUrl(isDomainWideDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
const scope = isDomainWideDelegated
const url = getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
const scope = isDelegated
? "https://graph.microsoft.com/.default"
: "User.Read Calendars.Read Calendars.ReadWrite";
@@ -76,8 +76,8 @@ const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenant
scope,
client_id: credentials.client_id || "",
client_secret: credentials.client_secret || "",
grant_type: isDomainWideDelegated ? "client_credentials" : "refresh_token",
...(isDomainWideDelegated ? {} : { refresh_token: refreshToken ?? "" }),
grant_type: isDelegated ? "client_credentials" : "refresh_token",
...(isDelegated ? {} : { refresh_token: refreshToken ?? "" }),
};
return await fetch(url, {
@@ -108,8 +108,8 @@ const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenant
function getAuthUrl(delegatedTo: boolean, tenantId?: string): string {
if (delegatedTo) {
if (!tenantId) {
throw new CalendarAppDomainWideDelegationInvalidGrantError(
"Invalid DomainWideDelegation Settings: tenantId is missing"
throw new CalendarAppDelegationCredentialInvalidGrantError(
"Invalid DelegationCredential Settings: tenantId is missing"
);
}
return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
@@ -129,18 +129,18 @@ const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenant
async function getAzureUserId(credential: CredentialForCalendarServiceWithTenantId) {
if (azureUserId) return azureUserId;
const isDomainWideDelegated = Boolean(credential?.delegatedTo);
const isDelegated = Boolean(credential?.delegatedTo);
if (!isDomainWideDelegated) return null;
if (!isDelegated) return null;
const url = getAuthUrl(isDomainWideDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
const url = getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
const dwdClientId = credential.delegatedTo?.serviceAccountKey?.client_id;
const dwdClientSecret = credential.delegatedTo?.serviceAccountKey?.private_key;
const delegationCredentialClientId = credential.delegatedTo?.serviceAccountKey?.client_id;
const delegationCredentialClientSecret = credential.delegatedTo?.serviceAccountKey?.private_key;
if (!dwdClientId || !dwdClientSecret) {
throw new CalendarAppDomainWideDelegationConfigurationError(
"Domain Wide Delegated credential without clientId or Secret"
if (!delegationCredentialClientId || !delegationCredentialClientSecret) {
throw new CalendarAppDelegationCredentialConfigurationError(
"Delegation credential without clientId or Secret"
);
}
const loginResponse = await fetch(url, {
@@ -148,9 +148,9 @@ const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenant
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
scope: "https://graph.microsoft.com/.default",
client_id: dwdClientId,
client_id: delegationCredentialClientId,
grant_type: "client_credentials",
client_secret: dwdClientSecret,
client_secret: delegationCredentialClientSecret,
}),
});
@@ -173,7 +173,7 @@ const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenant
const parsedBody = await response.json();
if (!parsedBody?.value?.[0]?.id) {
throw new CalendarAppDomainWideDelegationInvalidGrantError(
throw new CalendarAppDelegationCredentialInvalidGrantError(
"User might not exist in Microsoft Azure Active Directory"
);
}
+15 -13
View File
@@ -4,9 +4,9 @@ import type { TFunction } from "next-i18next";
import { defaultVideoAppCategories } from "@calcom/app-store/utils";
import getEnabledAppsFromCredentials from "@calcom/lib/apps/getEnabledAppsFromCredentials";
import {
buildNonDwdCredentials,
enrichUserWithDwdConferencingCredentialsWithoutOrgId,
} from "@calcom/lib/domainWideDelegation/server";
buildNonDelegationCredentials,
enrichUserWithDelegationConferencingCredentialsWithoutOrgId,
} from "@calcom/lib/delegationCredential/server";
import { prisma } from "@calcom/prisma";
import { AppCategories } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -63,7 +63,7 @@ export async function getLocationGroupedOptions(
});
}
const nonDwdCredentials = await prisma.credential.findMany({
const nonDelegationCredentials = await prisma.credential.findMany({
where: {
...idToSearchObject,
app: {
@@ -84,17 +84,19 @@ export async function getLocationGroupedOptions(
let credentials;
if (user) {
// We only add dwd credentials if the request for location options is for a user because DWD Credential is applicable to Users only.
const { credentials: allCredentials } = await enrichUserWithDwdConferencingCredentialsWithoutOrgId({
user: {
...user,
credentials: nonDwdCredentials,
},
});
// We only add delegationCredentials if the request for location options is for a user because DelegationCredential Credential is applicable to Users only.
const { credentials: allCredentials } = await enrichUserWithDelegationConferencingCredentialsWithoutOrgId(
{
user: {
...user,
credentials: nonDelegationCredentials,
},
}
);
credentials = allCredentials;
} else {
// TODO: We can avoid calling buildNonDwdCredentials here by moving the above prisma query to the repository and doing it there
credentials = buildNonDwdCredentials(nonDwdCredentials);
// TODO: We can avoid calling buildNonDelegationCredentials here by moving the above prisma query to the repository and doing it there
credentials = buildNonDelegationCredentials(nonDelegationCredentials);
}
const integrations = await getEnabledAppsFromCredentials(credentials, { filterOnCredentials: true });
@@ -12,7 +12,7 @@ import type {
EventTypes,
} from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { BulkEditDefaultForEventsModal } from "@calcom/features/eventtypes/components/BulkEditDefaultForEventsModal";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { isDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AppCategories } from "@calcom/prisma/enums";
import { type RouterOutputs } from "@calcom/trpc";
@@ -230,7 +230,7 @@ function ConnectOrDisconnectIntegrationMenuItem(props: {
<DropdownItem
color="destructive"
onClick={() => handleDisconnect(credentialId, app, teamId)}
disabled={isGlobal || isDwdCredential({ credentialId })}
disabled={isGlobal || isDelegationCredential({ credentialId })}
StartIcon="trash">
{t("remove_app")}
</DropdownItem>
@@ -2,7 +2,7 @@
import { useState } from "react";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { isDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { ButtonProps } from "@calcom/ui";
@@ -38,8 +38,8 @@ export default function DisconnectIntegration(props: {
},
});
// Such a credential is added in-memory and removed when Domain-wide delegation is disabled.
const disableDisconnect = isDwdCredential({ credentialId });
// Such a credential is added in-memory and removed when Delegation credential is disabled.
const disableDisconnect = isDelegationCredential({ credentialId });
return (
<DisconnectIntegrationComponent
onDeletionConfirmation={() => mutation.mutate({ id: credentialId, ...(teamId ? { teamId } : {}) })}
@@ -1,6 +1,6 @@
import type z from "zod";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "@calcom/lib/delegationCredential/server";
import { UserRepository } from "@calcom/lib/server/repository/user";
import prisma from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -120,9 +120,9 @@ export const getAllCredentials = async (
}
});
const userWithDwdCredentials = await enrichUserWithDwdCredentialsWithoutOrgId({
const userWithDelegationCredentials = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: { ...user, credentials: allCredentials },
});
return userWithDwdCredentials.credentials;
return userWithDelegationCredentials.credentials;
};
@@ -1,7 +1,7 @@
import async from "async";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { buildAllCredentials } from "@calcom/lib/domainWideDelegation/server";
import { isDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
import { buildAllCredentials } from "@calcom/lib/delegationCredential/server";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import { refreshCredential } from "./refreshCredential";
@@ -14,8 +14,12 @@ import { refreshCredential } from "./refreshCredential";
export async function refreshCredentials(
credentials: Array<CredentialForCalendarService>
): Promise<Array<CredentialForCalendarService>> {
const nonDwdCredentials = credentials.filter((cred) => !isDwdCredential({ credentialId: cred.id }));
const dwdCredentials = credentials.filter((cred) => isDwdCredential({ credentialId: cred.id }));
const refreshedDbCredentials = await async.mapLimit(nonDwdCredentials, 5, refreshCredential);
return buildAllCredentials({ dwdCredentials, existingCredentials: refreshedDbCredentials });
const nonDelegationCredentials = credentials.filter(
(cred) => !isDelegationCredential({ credentialId: cred.id })
);
const delegationCredentials = credentials.filter((cred) =>
isDelegationCredential({ credentialId: cred.id })
);
const refreshedDbCredentials = await async.mapLimit(nonDelegationCredentials, 5, refreshCredential);
return buildAllCredentials({ delegationCredentials, existingCredentials: refreshedDbCredentials });
}
@@ -70,7 +70,7 @@ async function getBookingToDelete(id: number | undefined, uid: string | undefine
externalCalendarId: true,
credentialId: true,
thirdPartyRecurringEventId: true,
domainWideDelegationCredentialId: true,
delegationCredentialId: true,
},
},
payment: true,
@@ -48,9 +48,9 @@ import EventManager from "@calcom/lib/EventManager";
import { shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";
import { getDefaultEvent, getUsernameList } from "@calcom/lib/defaultEvents";
import {
enrichHostsWithDwdCredentials,
getFirstDwdConferencingCredentialAppLocation,
} from "@calcom/lib/domainWideDelegation/server";
enrichHostsWithDelegationCredentials,
getFirstDelegationConferencingCredentialAppLocation,
} from "@calcom/lib/delegationCredential/server";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { getEventName } from "@calcom/lib/event";
@@ -690,7 +690,7 @@ async function handler(
// find a lucky user that is not already in the luckyUsers array
availableUsers: freeUsers,
allRRHosts: (
await enrichHostsWithDwdCredentials({
await enrichHostsWithDelegationCredentials({
orgId: firstUserOrgId ?? null,
hosts: eventTypeWithUsers.hosts,
})
@@ -809,7 +809,7 @@ async function handler(
}
}
const organizationDefaultLocation = getFirstDwdConferencingCredentialAppLocation({
const organizationDefaultLocation = getFirstDelegationConferencingCredentialAppLocation({
credentials: firstUser.credentials,
});
@@ -1,4 +1,4 @@
import { getFirstDwdConferencingCredentialAppLocation } from "@calcom/lib/domainWideDelegation/server";
import { getFirstDelegationConferencingCredentialAppLocation } from "@calcom/lib/delegationCredential/server";
import type { Prisma } from "@calcom/prisma/client";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
@@ -36,13 +36,14 @@ export const getLocationValuesForDb = <
users = sortUsersByDynamicList(users, dynamicUserList);
const firstDynamicGroupMember = users[0];
const firstDynamicGroupMemberMetadata = userMetadataSchema.parse(firstDynamicGroupMember.metadata);
const firstDynamicGroupMemberDwdConferencingAppLocation = getFirstDwdConferencingCredentialAppLocation({
credentials: firstDynamicGroupMember.credentials,
});
const firstDynamicGroupMemberDelegationCredentialConferencingAppLocation =
getFirstDelegationConferencingCredentialAppLocation({
credentials: firstDynamicGroupMember.credentials,
});
firstDynamicGroupMemberDefaultLocationUrl =
firstDynamicGroupMemberMetadata?.defaultConferencingApp?.appLink ||
firstDynamicGroupMemberDwdConferencingAppLocation;
firstDynamicGroupMemberDelegationCredentialConferencingAppLocation;
locationBodyString = firstDynamicGroupMemberDefaultLocationUrl || locationBodyString;
}
@@ -2,8 +2,8 @@ import type { Prisma } from "@prisma/client";
import type { IncomingMessage } from "http";
import type { Logger } from "tslog";
import { findQualifiedHostsWithDwdCredentials } from "@calcom/lib/bookings/findQualifiedHostsWithDwdCredentials";
import { enrichUsersWithDwdCredentials } from "@calcom/lib/domainWideDelegation/server";
import { findQualifiedHostsWithDelegationCredentials } from "@calcom/lib/bookings/findQualifiedHostsWithDelegationCredentials";
import { enrichUsersWithDelegationCredentials } from "@calcom/lib/delegationCredential/server";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { HttpError } from "@calcom/lib/http-error";
import { getPiiFreeUser } from "@calcom/lib/piiFreeData";
@@ -25,7 +25,10 @@ type Users = (Awaited<ReturnType<typeof loadUsers>>[number] & {
createdAt?: Date;
})[];
export type UsersWithDwdCredentials = (Omit<Awaited<ReturnType<typeof loadUsers>>[number], "credentials"> & {
export type UsersWithDelegationCredentials = (Omit<
Awaited<ReturnType<typeof loadUsers>>[number],
"credentials"
> & {
isFixed?: boolean;
metadata?: Prisma.JsonValue;
createdAt?: Date;
@@ -72,9 +75,9 @@ export async function loadAndValidateUsers({
rescheduleUid,
routingFormResponse,
}: InputProps): Promise<{
qualifiedRRUsers: UsersWithDwdCredentials;
additionalFallbackRRUsers: UsersWithDwdCredentials;
fixedUsers: UsersWithDwdCredentials;
qualifiedRRUsers: UsersWithDelegationCredentials;
additionalFallbackRRUsers: UsersWithDelegationCredentials;
fixedUsers: UsersWithDelegationCredentials;
}> {
let users: Users = await loadUsers({
eventType,
@@ -125,13 +128,14 @@ export async function loadAndValidateUsers({
? false
: user.isFixed || eventType.schedulingType !== SchedulingType.ROUND_ROBIN,
}));
const { qualifiedRRHosts, allFallbackRRHosts, fixedHosts } = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: routedTeamMemberIds || [],
rescheduleUid,
contactOwnerEmail,
routingFormResponse,
});
const { qualifiedRRHosts, allFallbackRRHosts, fixedHosts } =
await findQualifiedHostsWithDelegationCredentials({
eventType,
routedTeamMemberIds: routedTeamMemberIds || [],
rescheduleUid,
contactOwnerEmail,
routingFormResponse,
});
const allQualifiedHostsHashMap = [...qualifiedRRHosts, ...(allFallbackRRHosts ?? []), ...fixedHosts].reduce(
(acc, host) => {
if (host.user.id) {
@@ -141,14 +145,14 @@ export async function loadAndValidateUsers({
},
{} as {
[key: number]: Awaited<
ReturnType<typeof findQualifiedHostsWithDwdCredentials>
ReturnType<typeof findQualifiedHostsWithDelegationCredentials>
>["qualifiedRRHosts"][number];
}
);
let qualifiedRRUsers: UsersWithDwdCredentials = [];
let allFallbackRRUsers: UsersWithDwdCredentials = [];
let fixedUsers: UsersWithDwdCredentials = [];
let qualifiedRRUsers: UsersWithDelegationCredentials = [];
let allFallbackRRUsers: UsersWithDelegationCredentials = [];
let fixedUsers: UsersWithDelegationCredentials = [];
if (qualifiedRRHosts.length) {
// remove users that are not in the qualified hosts array
@@ -189,14 +193,14 @@ export async function loadAndValidateUsers({
memberId: firstUser.id ?? null,
teamId: eventType.teamId,
});
const usersEnrichedWithDwd = await enrichUsersWithDwdCredentials({
const usersEnrichedWithDelegationCredential = await enrichUsersWithDelegationCredentials({
orgId: firstUserOrgId ?? null,
users,
});
return {
qualifiedRRUsers,
additionalFallbackRRUsers, // without qualified
fixedUsers: usersEnrichedWithDwd,
fixedUsers: usersEnrichedWithDelegationCredential,
};
}
@@ -17,9 +17,9 @@ import {
mockSuccessfulVideoMeetingCreation,
mockCalendarToHaveNoBusySlots,
BookingLocations,
createDwdCredential,
createDelegationCredential,
createOrganization,
buildDwdCredential,
buildDelegationCredential,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { createMockNextJsRequest } from "@calcom/web/test/utils/bookingScenario/createMockNextJsRequest";
import {
@@ -50,11 +50,11 @@ const timeout = process.env.CI ? 5000 : 20000;
describe("handleNewBooking", () => {
setupAndTeardown();
describe("Domain Wide Delegation", () => {
describe("Delegation Credential", () => {
test(
`should create a successful booking using the domain wide delegation credential
1. Should create a booking in the database with reference having DWD credential
2. Should create an event in calendar with DWD credential
`should create a successful booking using the delegation credential
1. Should create a booking in the database with reference having Delegation credential
2. Should create an event in calendar with Delegation credential
3. Should use Google Meet as the location even when not explicitly set.
`,
async ({ emails }) => {
@@ -90,14 +90,14 @@ describe("handleNewBooking", () => {
id: 101,
schedules: [TestData.schedules.IstWorkHours],
selectedCalendars: [TestData.selectedCalendars.google],
// User must be part of organization to be able to use that organization's DWD credential
// User must be part of organization to be able to use that organization's Delegation credential
teams: payloadToMakePartOfOrganization,
// No regular credentials provided
credentials: [],
destinationCalendar: TestData.selectedCalendars.google,
});
const dwd = await createDwdCredential(org.id);
const delegationCredential = await createDelegationCredential(org.id);
const payloadToCreateUserEventTypeForOrganizer = {
id: 1,
slotInterval: 30,
@@ -193,8 +193,8 @@ describe("handleNewBooking", () => {
meetingId: "GOOGLE_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
// Verify DWD credential was used
domainWideDelegationCredentialId: dwd.id,
// Verify Delegation credential was used
delegationCredentialId: delegationCredential.id,
},
],
iCalUID: createdBooking.iCalUID,
@@ -202,7 +202,9 @@ describe("handleNewBooking", () => {
expectWorkflowToBeTriggered({ emailsToReceive: [organizer.email], emails });
expectSuccessfulCalendarEventCreationInCalendar(calendarMock, {
credential: buildDwdCredential({ serviceAccountKey: dwd.serviceAccountKey }),
credential: buildDelegationCredential({
serviceAccountKey: delegationCredential.serviceAccountKey,
}),
calendarId: TestData.selectedCalendars.google.externalId,
// There would be no videoCallUrl in this case as it is not a dedicated conferencing case and hangoutLink is used instead
videoCallUrl: null,
@@ -232,9 +234,9 @@ describe("handleNewBooking", () => {
);
test(
`should create a successful booking using the office365 domain wide delegation credential with Cal Video as the location
1. Should create a booking in the database with reference having DWD credential
2. Should create an event in Outlook calendar with DWD credential
`should create a successful booking using the office365 delegation credential with Cal Video as the location
1. Should create a booking in the database with reference having Delegation credential
2. Should create an event in Outlook calendar with Delegation credential
`,
async ({ emails }) => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
@@ -269,14 +271,14 @@ describe("handleNewBooking", () => {
id: 101,
schedules: [TestData.schedules.IstWorkHours],
selectedCalendars: [TestData.selectedCalendars.office365],
// User must be part of organization to be able to use that organization's DWD credential
// User must be part of organization to be able to use that organization's Delegation credential
teams: payloadToMakePartOfOrganization,
// No regular credentials provided
credentials: [],
destinationCalendar: TestData.selectedCalendars.office365,
});
const dwd = await createDwdCredential(org.id, "office365");
const delegationCredential = await createDelegationCredential(org.id, "office365");
const payloadToCreateUserEventTypeForOrganizer = {
id: 1,
slotInterval: 30,
@@ -390,8 +392,8 @@ describe("handleNewBooking", () => {
meetingId: "OFFICE_365_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://UNUSED_URL",
// Verify DWD credential was used
domainWideDelegationCredentialId: dwd.id,
// Verify Delegation credential was used
delegationCredentialId: delegationCredential.id,
},
],
iCalUID: createdBooking.iCalUID,
@@ -399,7 +401,9 @@ describe("handleNewBooking", () => {
expectWorkflowToBeTriggered({ emailsToReceive: [organizer.email], emails });
expectSuccessfulCalendarEventCreationInCalendar(calendarMock, {
credential: buildDwdCredential({ serviceAccountKey: dwd.serviceAccountKey }),
credential: buildDelegationCredential({
serviceAccountKey: delegationCredential.serviceAccountKey,
}),
calendarId: TestData.selectedCalendars.office365.externalId,
// There would be no videoCallUrl in this case as it is not a dedicated conferencing case and hangoutLink is used instead
videoCallUrl: null,
@@ -430,7 +434,7 @@ describe("handleNewBooking", () => {
);
test(
`should fail calendar event creation when organizer isn't part of the organization of DWD Credential`,
`should fail calendar event creation when organizer isn't part of the organization of DelegationCredential Credential`,
async () => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
@@ -470,13 +474,13 @@ describe("handleNewBooking", () => {
id: 101,
schedules: [TestData.schedules.IstWorkHours],
selectedCalendars: [TestData.selectedCalendars.google],
// User must be part of organization to be able to use that organization's DWD credential
// User must be part of organization to be able to use that organization's Delegation credential
teams: payloadToMakePartOfOrganization,
// No regular credentials provided
credentials: [],
});
await createDwdCredential(anotherOrg.id);
await createDelegationCredential(anotherOrg.id);
const payloadToCreateUserEventTypeForOrganizer = {
id: 1,
slotInterval: 30,
@@ -598,9 +602,9 @@ describe("handleNewBooking", () => {
);
test(
`should create a successful dynamic group booking using the domain wide delegation credential
1. Should create a booking in the database with reference having DWD credential
2. Should create an event in calendar with DWD credential for both users
`should create a successful dynamic group booking using the delegation credential
1. Should create a booking in the database with reference having Delegation credential
2. Should create an event in calendar with Delegation credential for both users
3. Should use Google Meet as the location even when not explicitly set.
`,
async () => {
@@ -654,7 +658,7 @@ describe("handleNewBooking", () => {
destinationCalendar: TestData.selectedCalendars.google,
});
const dwd = await createDwdCredential(org.id);
const delegationCredential = await createDelegationCredential(org.id);
await createBookingScenario(
getScenarioData({
@@ -747,8 +751,8 @@ describe("handleNewBooking", () => {
meetingId: "GOOGLE_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
// Verify DWD credential was used
domainWideDelegationCredentialId: dwd.id,
// Verify Delegation credential was used
delegationCredentialId: delegationCredential.id,
},
],
iCalUID: createdBooking.iCalUID,
@@ -4,8 +4,8 @@ import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { sendCancelledSeatEmailsAndSMS } from "@calcom/emails";
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import { getAllDwdCredentialsForUser } from "@calcom/lib/domainWideDelegation/server";
import { getDwdOrFindRegularCredential } from "@calcom/lib/domainWideDelegation/server";
import { getAllDelegationCredentialsForUser } from "@calcom/lib/delegationCredential/server";
import { getDelegationCredentialOrFindRegularCredential } from "@calcom/lib/delegationCredential/server";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -69,8 +69,8 @@ async function cancelAttendeeSeat(
const attendee = bookingToDelete?.attendees.find((attendee) => attendee.id === seatReference.attendeeId);
const bookingToDeleteUser = bookingToDelete.user ?? null;
const dwdCredentials = bookingToDeleteUser
? await getAllDwdCredentialsForUser({
const delegationCredentials = bookingToDeleteUser
? await getAllDelegationCredentialsForUser({
user: { email: bookingToDeleteUser.email, id: bookingToDeleteUser.id },
})
: [];
@@ -81,13 +81,13 @@ async function cancelAttendeeSeat(
const integrationsToUpdate = [];
for (const reference of bookingToDelete.references) {
if (reference.credentialId || reference.domainWideDelegationCredentialId) {
const credential = await getDwdOrFindRegularCredential({
if (reference.credentialId || reference.delegationCredentialId) {
const credential = await getDelegationCredentialOrFindRegularCredential({
id: {
credentialId: reference.credentialId,
domainWideDelegationCredentialId: reference.domainWideDelegationCredentialId,
delegationCredentialId: reference.delegationCredentialId,
},
dwdCredentials,
delegationCredentials,
});
if (credential) {
@@ -2,8 +2,8 @@ import type { Attendee } from "@prisma/client";
// eslint-disable-next-line no-restricted-imports
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { getAllDwdCredentialsForUser } from "@calcom/lib/domainWideDelegation/server";
import { getDwdOrFindRegularCredential } from "@calcom/lib/domainWideDelegation/server";
import { getAllDelegationCredentialsForUser } from "@calcom/lib/delegationCredential/server";
import { getDelegationCredentialOrFindRegularCredential } from "@calcom/lib/delegationCredential/server";
import { deleteMeeting } from "@calcom/lib/videoClient";
import prisma from "@calcom/prisma";
import { BookingStatus } from "@calcom/prisma/enums";
@@ -20,8 +20,8 @@ const lastAttendeeDeleteBooking = async (
) => {
let deletedReferences = false;
const bookingUser = originalRescheduledBooking?.user;
const dwdCredentials = bookingUser
? await getAllDwdCredentialsForUser({
const delegationCredentials = bookingUser
? await getAllDelegationCredentialsForUser({
user: { email: bookingUser.email, id: bookingUser.id },
})
: [];
@@ -29,13 +29,13 @@ const lastAttendeeDeleteBooking = async (
const integrationsToDelete = [];
for (const reference of originalRescheduledBooking.references) {
if (reference.credentialId || reference.domainWideDelegationCredentialId) {
const credential = await getDwdOrFindRegularCredential({
if (reference.credentialId || reference.delegationCredentialId) {
const credential = await getDelegationCredentialOrFindRegularCredential({
id: {
credentialId: reference.credentialId,
domainWideDelegationCredentialId: reference.domainWideDelegationCredentialId,
delegationCredentialId: reference.delegationCredentialId,
},
dwdCredentials,
delegationCredentials,
});
if (credential) {
@@ -17,7 +17,7 @@ export type ICalendarSwitchProps = {
isLastItemInList?: boolean;
destination?: boolean;
credentialId: number;
domainWideDelegationCredentialId: string | null;
delegationCredentialId: string | null;
eventTypeId: number | null;
disabled?: boolean;
};
@@ -36,7 +36,7 @@ const CalendarSwitch = (props: ICalendarSwitchProps) => {
isChecked,
name,
credentialId,
domainWideDelegationCredentialId,
delegationCredentialId,
eventTypeId,
disabled,
} = props;
@@ -48,7 +48,7 @@ const CalendarSwitch = (props: ICalendarSwitchProps) => {
const body = {
integration: type,
externalId: externalId,
...(domainWideDelegationCredentialId && { domainWideDelegationCredentialId }),
...(delegationCredentialId && { delegationCredentialId }),
// new URLSearchParams does not accept numbers
credentialId: String(credentialId),
...(eventTypeId ? { eventTypeId: String(eventTypeId) } : {}),
@@ -7,7 +7,7 @@ import { sendCancelledEmailsAndSMS } from "@calcom/emails";
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
import { deleteWebhookScheduledTriggers } from "@calcom/features/webhooks/lib/scheduleTrigger";
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
import { buildNonDwdCredential } from "@calcom/lib/domainWideDelegation/server";
import { buildNonDelegationCredential } from "@calcom/lib/delegationCredential/server";
import { DailyLocationType } from "@calcom/lib/location";
import { deletePayment } from "@calcom/lib/payment/deletePayment";
import { getTranslation } from "@calcom/lib/server/i18n";
@@ -430,7 +430,7 @@ const handleDeleteCredential = async ({
// If it's a calendar remove it from the SelectedCalendars
if (credential.app?.categories.includes(AppCategories.calendar)) {
try {
const calendar = await getCalendar(buildNonDwdCredential(credential));
const calendar = await getCalendar(buildNonDelegationCredential(credential));
const calendars = await calendar?.listCalendars();
@@ -186,7 +186,7 @@ function CreateDelegationDialog({
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent enableOverflow title={t("add_domain_wide_delegation")}>
<DialogContent enableOverflow title={t("add_delegation_credential")}>
<Form form={form} handleSubmit={handleSubmit}>
<DelegationFormFields workspacePlatforms={workspacePlatforms} isCreate={true} />
<DialogFooter>
@@ -226,7 +226,7 @@ function EditDelegationDialog({
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent title={t("edit_domain_wide_delegation")}>
<DialogContent title={t("edit_delegation_credential")}>
<Form form={form} handleSubmit={handleEdit}>
<DelegationFormFields workspacePlatforms={workspacePlatforms} isCreate={false} />
<DialogFooter>
@@ -282,26 +282,26 @@ function DelegationFormFields({
);
}
function DomainWideDelegationList() {
function DelegationCredentialList() {
const { t } = useLocale();
const utils = trpc.useContext();
const { data: delegations, isLoading, error } = trpc.viewer.domainWideDelegation.list.useQuery();
const { data: delegations, isLoading, error } = trpc.viewer.delegationCredential.list.useQuery();
const updateMutation = trpc.viewer.domainWideDelegation.update.useMutation({
onSuccess: () => utils.viewer.domainWideDelegation.list.invalidate(),
const updateMutation = trpc.viewer.delegationCredential.update.useMutation({
onSuccess: () => utils.viewer.delegationCredential.list.invalidate(),
onError: (error) => {
showToast(error.message, "error");
},
});
const toggleEnabledMutation = trpc.viewer.domainWideDelegation.toggleEnabled.useMutation({
const toggleEnabledMutation = trpc.viewer.delegationCredential.toggleEnabled.useMutation({
onSuccess: (data) => {
if (data) {
showToast(
data.enabled ? t("domain_wide_delegation_enabled") : t("domain_wide_delegation_disabled"),
data.enabled ? t("delegation_credential_enabled") : t("delegation_credential_disabled"),
"success"
);
utils.viewer.domainWideDelegation.list.invalidate();
utils.viewer.delegationCredential.list.invalidate();
}
},
onError: (error) => {
@@ -309,15 +309,15 @@ function DomainWideDelegationList() {
},
});
const createMutation = trpc.viewer.domainWideDelegation.add.useMutation({
onSuccess: () => utils.viewer.domainWideDelegation.list.invalidate(),
const createMutation = trpc.viewer.delegationCredential.add.useMutation({
onSuccess: () => utils.viewer.delegationCredential.list.invalidate(),
onError: (error) => {
showToast(error.message, "error");
},
});
const deleteMutation = trpc.viewer.domainWideDelegation.delete.useMutation({
onSuccess: () => utils.viewer.domainWideDelegation.list.invalidate(),
const deleteMutation = trpc.viewer.delegationCredential.delete.useMutation({
onSuccess: () => utils.viewer.delegationCredential.list.invalidate(),
onError: (error) => {
showToast(error.message, "error");
},
@@ -345,7 +345,7 @@ function DomainWideDelegationList() {
});
const { data: workspacePlatforms, isLoading: isLoadingWorkspacePlatforms } =
trpc.viewer.domainWideDelegation.listWorkspacePlatforms.useQuery();
trpc.viewer.delegationCredential.listWorkspacePlatforms.useQuery();
const enabledWorkspacePlatforms = workspacePlatforms?.filter((platform) => platform.enabled) || [];
@@ -379,7 +379,7 @@ function DomainWideDelegationList() {
const AddDwDButton = () => {
return (
<Button type="button" color="secondary" StartIcon="plus" className="mt-6" onClick={onCreateClick}>
{t("add_domain_wide_delegation")}
{t("add_delegation_credential")}
</Button>
);
};
@@ -419,8 +419,8 @@ function DomainWideDelegationList() {
) : (
<EmptyScreen
Icon="link"
headline={t("add_domain_wide_delegation")}
description={t("domain_wide_delegation_description")}
headline={t("add_delegation_credential")}
description={t("delegation_credential_description")}
className="rounded-b-lg rounded-t-none border-t-0"
buttonRaw={<AddDwDButton />}
/>
@@ -446,6 +446,6 @@ function DomainWideDelegationList() {
);
}
export default function DomainWideDelegationListPage() {
return <DomainWideDelegationList />;
export default function DelegationCredentialListPage() {
return <DelegationCredentialList />;
}
@@ -20,7 +20,7 @@ import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/rem
import { isPrismaObjOrUndefined } from "@calcom/lib";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import { SENDER_NAME } from "@calcom/lib/constants";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "@calcom/lib/delegationCredential/server";
import { getEventName } from "@calcom/lib/event";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import logger from "@calcom/lib/logger";
@@ -275,7 +275,7 @@ export const roundRobinManualReassignment = async ({
include: { user: { select: { email: true } } },
});
const newUserWithCredentials = await enrichUserWithDwdCredentialsWithoutOrgId({
const newUserWithCredentials = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: { ...newUser, credentials },
});
@@ -22,9 +22,9 @@ import { isPrismaObjOrUndefined } from "@calcom/lib";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import { SENDER_NAME } from "@calcom/lib/constants";
import {
enrichHostsWithDwdCredentials,
enrichUserWithDwdCredentialsWithoutOrgId,
} from "@calcom/lib/domainWideDelegation/server";
enrichHostsWithDelegationCredentials,
enrichUserWithDelegationCredentialsWithoutOrgId,
} from "@calcom/lib/delegationCredential/server";
import { getEventName } from "@calcom/lib/event";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import logger from "@calcom/lib/logger";
@@ -119,7 +119,7 @@ export const roundRobinReassignment = async ({
const previousRRHostT = await getTranslation(previousRRHost?.locale || "en", "common");
const eventTypeHosts = await enrichHostsWithDwdCredentials({
const eventTypeHosts = await enrichHostsWithDelegationCredentials({
orgId,
hosts: eventType.hosts,
});
@@ -320,7 +320,7 @@ export const roundRobinReassignment = async ({
},
});
const organizerWithCredentials = await enrichUserWithDwdCredentialsWithoutOrgId({
const organizerWithCredentials = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: { ...organizer, credentials },
});
+1 -1
View File
@@ -16,6 +16,6 @@ export type AppFlags = {
"disable-signup": boolean;
attributes: boolean;
"organizer-request-email-v2": boolean;
"domain-wide-delegation": boolean;
"delegation-credential": boolean;
"salesforce-crm-tasker": boolean;
};
+1 -1
View File
@@ -15,7 +15,7 @@ const initialData: AppFlags = {
"disable-signup": false,
attributes: false,
"organizer-request-email-v2": false,
"domain-wide-delegation": false,
"delegation-credential": false,
"salesforce-crm-tasker": false,
};
+10 -10
View File
@@ -5,37 +5,37 @@ export class CalendarAppError extends Error {
}
}
export class CalendarAppDomainWideDelegationError extends CalendarAppError {
export class CalendarAppDelegationCredentialError extends CalendarAppError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationError";
this.name = "CalendarAppDelegationCredentialError";
}
}
export class CalendarAppDomainWideDelegationConfigurationError extends CalendarAppDomainWideDelegationError {
export class CalendarAppDelegationCredentialConfigurationError extends CalendarAppDelegationCredentialError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationConfigurationError";
this.name = "CalendarAppDelegationCredentialConfigurationError";
}
}
export class CalendarAppDomainWideDelegationInvalidGrantError extends CalendarAppDomainWideDelegationError {
export class CalendarAppDelegationCredentialInvalidGrantError extends CalendarAppDelegationCredentialError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationInvalidGrantError";
this.name = "CalendarAppDelegationCredentialInvalidGrantError";
}
}
export class CalendarAppDomainWideDelegationClientIdNotAuthorizedError extends CalendarAppDomainWideDelegationConfigurationError {
export class CalendarAppDelegationCredentialClientIdNotAuthorizedError extends CalendarAppDelegationCredentialConfigurationError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationClientIdNotAuthorizedError";
this.name = "CalendarAppDelegationCredentialClientIdNotAuthorizedError";
}
}
export class CalendarAppDomainWideDelegationNotSetupError extends CalendarAppDomainWideDelegationConfigurationError {
export class CalendarAppDelegationCredentialNotSetupError extends CalendarAppDelegationCredentialConfigurationError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationNotSetupError";
this.name = "CalendarAppDelegationCredentialNotSetupError";
}
}
+16 -14
View File
@@ -5,8 +5,8 @@ import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import getApps from "@calcom/app-store/utils";
import dayjs from "@calcom/dayjs";
import { getUid } from "@calcom/lib/CalEventParser";
import { CalendarAppDomainWideDelegationError } from "@calcom/lib/CalendarAppError";
import { buildNonDwdCredentials } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { CalendarAppDelegationCredentialError } from "@calcom/lib/CalendarAppError";
import { buildNonDelegationCredentials } from "@calcom/lib/delegationCredential/clientAndServer";
import logger from "@calcom/lib/logger";
import { getPiiFreeCalendarEvent, getPiiFreeCredential } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -40,8 +40,8 @@ export const getCalendarCredentials = (credentials: Array<CredentialForCalendarS
return calendarCredentials;
};
export const getCalendarCredentialsWithoutDwd = (credentials: CredentialPayload[]) => {
return getCalendarCredentials(buildNonDwdCredentials(credentials));
export const getCalendarCredentialsWithoutDelegation = (credentials: CredentialPayload[]) => {
return getCalendarCredentials(buildNonDelegationCredentials(credentials));
};
export const getConnectedCalendars = async (
@@ -57,12 +57,12 @@ export const getConnectedCalendars = async (
const calendar = await item.calendar;
// Don't leak credentials to the client
const credentialId = credential.id;
const domainWideDelegationCredentialId = credential.delegatedToId ?? null;
const delegationCredentialId = credential.delegatedToId ?? null;
if (!calendar) {
return {
integration,
credentialId,
domainWideDelegationCredentialId,
delegationCredentialId,
};
}
const cals = await calendar.listCalendars();
@@ -75,7 +75,7 @@ export const getConnectedCalendars = async (
primary: cal.primary || null,
isSelected: selectedCalendars.some((selected) => selected.externalId === cal.externalId),
credentialId,
domainWideDelegationCredentialId,
delegationCredentialId,
};
}),
["primary"]
@@ -100,7 +100,7 @@ export const getConnectedCalendars = async (
return {
integration: cleanIntegrationKeys(integration),
credentialId,
domainWideDelegationCredentialId,
delegationCredentialId,
primary,
calendars,
};
@@ -114,7 +114,7 @@ export const getConnectedCalendars = async (
}
}
if (error instanceof CalendarAppDomainWideDelegationError) {
if (error instanceof CalendarAppDelegationCredentialError) {
errorMessage = error.message;
}
@@ -123,7 +123,7 @@ export const getConnectedCalendars = async (
return {
integration: cleanIntegrationKeys(item.integration),
credentialId: item.credential.id,
domainWideDelegationCredentialId: item.credential.delegatedToId,
delegationCredentialId: item.credential.delegatedToId,
error: {
message: errorMessage,
},
@@ -153,7 +153,7 @@ const cleanIntegrationKeys = (
export const getBusyCalendarTimes = async (
/**
* withCredentials can possibly have a duplicate credential in case DWD is enabled.
* withCredentials can possibly have a duplicate credential in case DelegationCredential is enabled.
* There is no way to deduplicate that at the moment because a `credential` doesn't directly know for which email it is,
*/
withCredentials: CredentialForCalendarService[],
@@ -209,14 +209,16 @@ export const createEvent = async (
calEvent.additionalNotes = "Notes have been hidden by the organizer"; // TODO: i18n this string?
}
const externalCalendarIdWhenDwdCredentialIsChosen = credential.delegatedToId ? externalId : undefined;
const externalCalendarIdWhenDelegationCredentialIsChosen = credential.delegatedToId
? externalId
: undefined;
// TODO: Surface success/error messages coming from apps to improve end user visibility
const creationResult = calendar
? await calendar
// Ideally we should pass externalId always, but let's start with DWD case first as in that case, CalendarService need to handle a special case for DWD to determine the selectedCalendar.
// Ideally we should pass externalId always, but let's start with DelegationCredential case first as in that case, CalendarService need to handle a special case for DelegationCredential to determine the selectedCalendar.
// Such logic shouldn't exist in CalendarService as it would be same for all calendar apps.
.createEvent(calEvent, credential.id, externalCalendarIdWhenDwdCredentialIsChosen)
.createEvent(calEvent, credential.id, externalCalendarIdWhenDelegationCredentialIsChosen)
.catch(async (error: { code: number; calError: string }) => {
success = false;
/**
+20 -18
View File
@@ -82,13 +82,13 @@ const getCredential = ({
allCredentials,
}: {
id: {
domainWideDelegationCredentialId: string | null;
delegationCredentialId: string | null;
credentialId: number | null;
};
allCredentials: CredentialForCalendarService[];
}) => {
return id.domainWideDelegationCredentialId
? allCredentials.find((c) => c.delegatedToId === id.domainWideDelegationCredentialId)
return id.delegationCredentialId
? allCredentials.find((c) => c.delegatedToId === id.delegationCredentialId)
: allCredentials.find((c) => c.id === id.credentialId);
};
@@ -108,12 +108,12 @@ export const processLocation = (event: CalendarEvent): CalendarEvent => {
};
/**
* Ensures invalid non-dwd credentialId isn't returned
* Ensures invalid non-delegationCredentialId isn't returned
*/
function getCredentialPayload(result: EventResult<Exclude<Event, AdditionalInformation>>) {
return {
credentialId: result?.credentialId && result.credentialId > 0 ? result.credentialId : undefined,
domainWideDelegationCredentialId: result?.delegatedToId || undefined,
delegationCredentialId: result?.delegatedToId || undefined,
};
}
@@ -155,7 +155,7 @@ export default class EventManager {
.sort(latestCredentialFirst)
// TODO: Change it to delegatedCredentialFirst in a followup PR.
// We are keeping delegated credentials at the end so that there is no impact on existing users connections as we still use their existing credentials
// Soon after DWD is released and stable, we switch it. Could be an env variable also to toggle this.
// Soon after DelegationCredential is released and stable, we switch it. Could be an env variable also to toggle this.
.sort(delegatedCredentialLast);
this.videoCredentials = appCredentials
@@ -364,7 +364,7 @@ export default class EventManager {
credentialId,
this.calendarCredentials,
credentialType,
reference.domainWideDelegationCredentialId
reference.delegationCredentialId
);
if (calendarCredential) {
@@ -396,10 +396,10 @@ export default class EventManager {
credentialId: number | null | undefined,
credentials: CredentialForCalendarService[],
type: string,
domainWideDelegationCredentialId?: string | null
delegationCredentialId?: string | null
) {
if (domainWideDelegationCredentialId) {
return this.calendarCredentials.find((cred) => cred.delegatedToId === domainWideDelegationCredentialId);
if (delegationCredentialId) {
return this.calendarCredentials.find((cred) => cred.delegatedToId === delegationCredentialId);
}
const credential = credentials.find((cred) => cred.id === credentialId);
if (credential) {
@@ -699,11 +699,11 @@ export default class EventManager {
for (const destination of destinationCalendars) {
if (eventCreated) break;
log.silly("Creating Calendar event", JSON.stringify({ destination }));
if (destination.credentialId || destination.domainWideDelegationCredentialId) {
if (destination.credentialId || destination.delegationCredentialId) {
let credential = getCredential({
id: {
credentialId: destination.credentialId,
domainWideDelegationCredentialId: destination.domainWideDelegationCredentialId,
delegationCredentialId: destination.delegationCredentialId,
},
allCredentials: this.calendarCredentials,
});
@@ -728,14 +728,16 @@ export default class EventManager {
delegatedTo: credentialFromDB.delegatedTo,
};
}
} else if (destination.domainWideDelegationCredentialId) {
log.warn("DWD: DWD seems to be disabled, falling back to first non-dwd credential");
// In case DWD is disabled, we land here where the destination calendar is connected to a DWD credential, but the credential isn't available(because DWD is disabled)
// In this case, we fallback to the first non-dwd credential. That would be there for all existing users before DWD was enabled
const firstNonDwdCalendarCredential = this.calendarCredentials.find(
} else if (destination.delegationCredentialId) {
log.warn(
"DelegationCredential: DelegationCredential seems to be disabled, falling back to first non-delegationCredential"
);
// In case DelegationCredential is disabled, we land here where the destination calendar is connected to a Delegation credential, but the credential isn't available(because DelegationCredential is disabled)
// In this case, we fallback to the first non-delegationCredential. That would be there for all existing users before DelegationCredential was enabled
const firstNonDelegatedCalendarCredential = this.calendarCredentials.find(
(cred) => !cred.type.endsWith("other_calendar") && !cred.delegatedToId
);
credential = firstNonDwdCalendarCredential;
credential = firstNonDelegatedCalendarCredential;
}
}
if (credential) {
@@ -4,7 +4,7 @@ import type { CredentialDataWithTeamName } from "@calcom/app-store/utils";
import getApps from "@calcom/app-store/utils";
import { prisma } from "@calcom/prisma";
import { isDwdCredential } from "../domainWideDelegation/clientAndServer";
import { isDelegationCredential } from "../delegationCredential/clientAndServer";
type EnabledApp = ReturnType<typeof getApps>[number] & { enabled: boolean };
@@ -32,8 +32,8 @@ const getEnabledAppsFromCredentials = async (
},
} satisfies Prisma.AppWhereInput;
const dwdCredentialsWithAppId = credentials
.filter((credential) => isDwdCredential({ credentialId: credential.id }))
const delegationCredentialsWithAppId = credentials
.filter((credential) => isDelegationCredential({ credentialId: credential.id }))
.filter((credential): credential is typeof credential & { appId: string } => credential.appId !== null);
if (filterOnCredentials) {
@@ -59,17 +59,17 @@ const getEnabledAppsFromCredentials = async (
select: { slug: true, enabled: true },
});
const dwdSupportedEnabledApps = await prisma.app.findMany({
const delegationCredentialSupportedEnabledApps = await prisma.app.findMany({
where: {
enabled: true,
slug: {
in: dwdCredentialsWithAppId.map((credential) => credential.appId),
in: delegationCredentialsWithAppId.map((credential) => credential.appId),
},
},
select: { slug: true, enabled: true },
});
enabledApps = [...enabledApps, ...dwdSupportedEnabledApps];
enabledApps = [...enabledApps, ...delegationCredentialSupportedEnabledApps];
const apps = getApps(credentials, filterOnCredentials);
const filteredApps = apps.reduce((reducedArray, app) => {
@@ -6,7 +6,7 @@ import type { Mock } from "vitest";
import { SchedulingType } from "@calcom/prisma/enums";
import { filterHostsByLeadThreshold } from "./filterHostsByLeadThreshold";
import { findQualifiedHostsWithDwdCredentials } from "./findQualifiedHostsWithDwdCredentials";
import { findQualifiedHostsWithDelegationCredentials } from "./findQualifiedHostsWithDelegationCredentials";
import * as getRoutedUsers from "./getRoutedUsers";
// Mock the filterHostsByLeadThreshold function
@@ -21,7 +21,7 @@ afterEach(() => {
(filterHostsByLeadThreshold as Mock).mockClear();
});
describe("findQualifiedHostsWithDwdCredentials", async () => {
describe("findQualifiedHostsWithDelegationCredentials", async () => {
it("should return qualified hosts based on mock of filterHostsByLeadThreshold", async () => {
const hosts = [
{
@@ -88,7 +88,7 @@ describe("findQualifiedHostsWithDwdCredentials", async () => {
};
// Call the function under test
const result = await findQualifiedHostsWithDwdCredentials({
const result = await findQualifiedHostsWithDelegationCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: null,
@@ -139,7 +139,7 @@ describe("findQualifiedHostsWithDwdCredentials", async () => {
};
// Call the function under test
const result = await findQualifiedHostsWithDwdCredentials({
const result = await findQualifiedHostsWithDelegationCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: null,
@@ -225,7 +225,7 @@ describe("findQualifiedHostsWithDwdCredentials", async () => {
};
// Call the function under test
const result = await findQualifiedHostsWithDwdCredentials({
const result = await findQualifiedHostsWithDelegationCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: null,
@@ -313,7 +313,7 @@ describe("findQualifiedHostsWithDwdCredentials", async () => {
};
// Call the function under test
const result = await findQualifiedHostsWithDwdCredentials({
const result = await findQualifiedHostsWithDelegationCredentials({
eventType,
routedTeamMemberIds: [1],
rescheduleUid: null,
@@ -390,7 +390,7 @@ describe("findQualifiedHostsWithDwdCredentials", async () => {
};
prismaMock.booking.findFirst.mockResolvedValue({ userId: 2 });
const result = await findQualifiedHostsWithDwdCredentials({
const result = await findQualifiedHostsWithDelegationCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: "recheduleUid",
@@ -469,7 +469,7 @@ describe("findQualifiedHostsWithDwdCredentials", async () => {
.mockImplementation(async () => [hosts[0]]);
// Call the function under test
const result = await findQualifiedHostsWithDwdCredentials({
const result = await findQualifiedHostsWithDelegationCredentials({
eventType,
routedTeamMemberIds: [0, 1, 2],
rescheduleUid: null,
@@ -562,7 +562,7 @@ describe("findQualifiedHostsWithDwdCredentials", async () => {
]);
// Call the function under test
const result = await findQualifiedHostsWithDwdCredentials({
const result = await findQualifiedHostsWithDelegationCredentials({
eventType,
routedTeamMemberIds: [2, 3],
rescheduleUid: null,
@@ -661,7 +661,7 @@ describe("findQualifiedHostsWithDwdCredentials", async () => {
(filterHostsByLeadThreshold as Mock).mockResolvedValue(rrHostsAfterFairness);
// Call the function under test
const result = await findQualifiedHostsWithDwdCredentials({
const result = await findQualifiedHostsWithDelegationCredentials({
eventType,
routedTeamMemberIds: [2, 3],
rescheduleUid: null,
@@ -1,6 +1,6 @@
import {
findMatchingHostsWithEventSegment,
getNormalizedHostsWithDwdCredentials,
getNormalizedHostsWithDelegationCredentials,
} from "@calcom/lib/bookings/getRoutedUsers";
import type { EventType } from "@calcom/lib/bookings/getRoutedUsers";
import type { SelectedCalendar } from "@calcom/prisma/client";
@@ -46,7 +46,7 @@ const isFixedHost = <T extends { isFixed: boolean }>(host: T): host is T & { isF
return host.isFixed;
};
export const findQualifiedHostsWithDwdCredentials = async <
export const findQualifiedHostsWithDelegationCredentials = async <
T extends {
email: string;
id: number;
@@ -97,11 +97,10 @@ export const findQualifiedHostsWithDwdCredentials = async <
user: Omit<T, "credentials"> & { credentials: CredentialForCalendarService[] };
}[];
}> => {
const { hosts: normalizedHosts, fallbackHosts: fallbackUsers } = await getNormalizedHostsWithDwdCredentials(
{
const { hosts: normalizedHosts, fallbackHosts: fallbackUsers } =
await getNormalizedHostsWithDelegationCredentials({
eventType,
}
);
});
// not a team event type, or some other reason - segment matching isn't necessary.
if (!normalizedHosts) {
const fixedHosts = fallbackUsers.filter(isFixedHost);
+12 -12
View File
@@ -5,7 +5,7 @@ import { safeStringify } from "@calcom/lib/safeStringify";
import { SchedulingType } from "@calcom/prisma/enums";
import type { CredentialPayload } from "@calcom/types/Credential";
import { enrichHostsWithDwdCredentials } from "../domainWideDelegation/server";
import { enrichHostsWithDelegationCredentials } from "../delegationCredential/server";
import getOrgIdFromMemberOrTeamId from "../getOrgIdFromMemberOrTeamId";
const log = logger.getSubLogger({ prefix: ["[getRoutedUsers]"] });
@@ -118,7 +118,7 @@ export function getNormalizedHosts<User extends BaseUser, Host extends BaseHost<
}
}
type BaseUserWithCredentialPayload = BaseUser & { credentials: CredentialPayload[] };
export async function getNormalizedHostsWithDwdCredentials<
export async function getNormalizedHostsWithDelegationCredentials<
User extends BaseUserWithCredentialPayload,
Host extends BaseHost<User>
>({
@@ -132,28 +132,28 @@ export async function getNormalizedHostsWithDwdCredentials<
};
}) {
if (eventType.hosts?.length && eventType.schedulingType) {
const hostsWithoutDwd = eventType.hosts.map((host) => ({
const hostsWithoutDelegationCredential = eventType.hosts.map((host) => ({
isFixed: host.isFixed,
user: host.user,
priority: host.priority,
weight: host.weight,
createdAt: host.createdAt,
}));
const firstHost = hostsWithoutDwd[0];
const firstHost = hostsWithoutDelegationCredential[0];
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
memberId: firstHost?.user?.id ?? null,
teamId: eventType.teamId,
});
const hostsEnrichedWithDwd = await enrichHostsWithDwdCredentials({
const hostsEnrichedWithDelegationCredential = await enrichHostsWithDelegationCredentials({
orgId: firstUserOrgId ?? null,
hosts: hostsWithoutDwd ?? null,
hosts: hostsWithoutDelegationCredential ?? null,
});
return {
hosts: hostsEnrichedWithDwd,
hosts: hostsEnrichedWithDelegationCredential,
fallbackHosts: null,
};
} else {
const hostsWithoutDwd = eventType.users.map((user) => {
const hostsWithoutDelegationCredential = eventType.users.map((user) => {
return {
isFixed: !eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE,
email: user.email,
@@ -161,18 +161,18 @@ export async function getNormalizedHostsWithDwdCredentials<
createdAt: null,
};
});
const firstHost = hostsWithoutDwd[0];
const firstHost = hostsWithoutDelegationCredential[0];
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
memberId: firstHost?.user?.id ?? null,
teamId: eventType.teamId,
});
const hostsEnrichedWithDwd = await enrichHostsWithDwdCredentials({
const hostsEnrichedWithDelegationCredential = await enrichHostsWithDelegationCredentials({
orgId: firstUserOrgId ?? null,
hosts: hostsWithoutDwd ?? null,
hosts: hostsWithoutDelegationCredential ?? null,
});
return {
hosts: null,
fallbackHosts: hostsEnrichedWithDwd,
fallbackHosts: hostsEnrichedWithDelegationCredential,
};
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ type DestinationCalendar = {
userId: number | null;
eventTypeId: number | null;
credentialId: number | null;
domainWideDelegationCredentialId: string | null;
delegationCredentialId: string | null;
} | null;
type Attendee = {
@@ -0,0 +1,27 @@
export function isDelegationCredential({ credentialId }: { credentialId: number | null | undefined }) {
// Though it is set as -1 right now, but we might want to set it to some other negative value.
return typeof credentialId === "number" && credentialId < 0;
}
export const buildNonDelegationCredential = <T extends Record<string, unknown> | null>(credential: T) => {
type WithDelegationCredential = T extends null
? null
: T & {
delegatedTo: null;
delegatedToId: null;
};
if (!credential) return null as WithDelegationCredential;
return {
...credential,
delegatedTo: null,
delegatedToId: null,
} as WithDelegationCredential;
};
export const buildNonDelegationCredentials = <T extends Record<string, unknown>>(credentials: T[]) => {
return credentials.map(buildNonDelegationCredential).filter((credential) => !!credential) as (T & {
delegatedTo: null;
delegatedToId: null;
})[];
};
@@ -4,20 +4,20 @@ import { describe, it, expect, beforeEach, vi } from "vitest";
import { metadata as googleCalendarMetadata } from "@calcom/app-store/googlecalendar/_metadata";
import { metadata as googleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
import type { ServiceAccountKey } from "@calcom/lib/server/repository/domainWideDelegation";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import type { ServiceAccountKey } from "@calcom/lib/server/repository/delegationCredential";
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import { SMSLockState } from "@calcom/prisma/enums";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import {
getAllDwdCredentialsForUser,
getAllDelegationCredentialsForUser,
buildAllCredentials,
getDwdOrRegularCredential,
enrichUsersWithDwdCredentials,
enrichHostsWithDwdCredentials,
enrichUserWithDwdCredentialsWithoutOrgId,
enrichUserWithDwdConferencingCredentialsWithoutOrgId,
getDelegationCredentialOrRegularCredential,
enrichUsersWithDelegationCredentials,
enrichHostsWithDelegationCredentials,
enrichUserWithDelegationCredentialsWithoutOrgId,
enrichUserWithDelegationConferencingCredentialsWithoutOrgId,
} from "./server";
// Mock OrganizationRepository
@@ -27,9 +27,9 @@ vi.mock("@calcom/lib/server/repository/organization", () => ({
},
}));
// Mock DomainWideDelegationRepository
vi.mock("@calcom/lib/server/repository/domainWideDelegation", () => ({
DomainWideDelegationRepository: {
// Mock DelegationCredentialRepository
vi.mock("@calcom/lib/server/repository/delegationCredential", () => ({
DelegationCredentialRepository: {
findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey: vi.fn(),
findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey: vi.fn(),
},
@@ -51,8 +51,8 @@ const mockWorkspacePlatform = {
slug: "google",
};
const mockDwd = {
id: "dwd-1",
const mockDelegationCredential = {
id: "delegationCredential-1",
enabled: true,
domain: "example.com",
organizationId: 1,
@@ -106,11 +106,11 @@ const mockOrganization = {
};
// Credential Builders
const buildDwdCredential = (overrides = {}) => ({
const buildDelegationCredential = (overrides = {}) => ({
type: "google_calendar",
appId: "google-calendar",
id: -1,
delegatedToId: mockDwd.id,
delegatedToId: mockDelegationCredential.id,
userId: mockUser.id,
user: { email: mockUser.email },
key: { access_token: "NOOP_UNUSED_DELEGATION_TOKEN" },
@@ -123,16 +123,16 @@ const buildDwdCredential = (overrides = {}) => ({
...overrides,
});
const buildDwdGoogleCalendarCredential = (overrides = {}) => ({
...buildDwdCredential({
const buildGoogleCalendarDelegationCredential = (overrides = {}) => ({
...buildDelegationCredential({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
}),
...overrides,
});
const buildDwdGoogleMeetCredential = (overrides = {}) => ({
...buildDwdCredential({
const buildDelegationCredentialGoogleMeetCredential = (overrides = {}) => ({
...buildDelegationCredential({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
}),
@@ -167,13 +167,13 @@ const buildMockWorkspacePlatform = (overrides: Partial<typeof mockWorkspacePlatf
...overrides,
});
const buildMockDwd = (overrides: Partial<typeof mockDwd> = {}) => ({
...mockDwd,
const buildMockDelegationCredential = (overrides: Partial<typeof mockDelegationCredential> = {}) => ({
...mockDelegationCredential,
workspacePlatform: buildMockWorkspacePlatform(overrides.workspacePlatform || {}),
...overrides,
});
describe("getAllDwdCredentialsForUser", () => {
describe("getAllDelegationCredentialsForUser", () => {
setupAndTeardown();
beforeEach(() => {
@@ -181,138 +181,141 @@ describe("getAllDwdCredentialsForUser", () => {
vi.mocked(OrganizationRepository.findByMemberEmail).mockResolvedValue(mockOrganization);
});
it("should return empty array when no DWD found", async () => {
it("should return empty array when no DelegationCredential found", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await getAllDwdCredentialsForUser({ user: mockUser });
const result = await getAllDelegationCredentialsForUser({ user: mockUser });
expect(result).toEqual([]);
});
it("should return empty array when DWD is disabled", async () => {
it("should return empty array when DelegationCredential is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
const result = await getAllDwdCredentialsForUser({ user: mockUser });
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
const result = await getAllDelegationCredentialsForUser({ user: mockUser });
expect(result).toEqual([]);
});
it("should return credentials for enabled Google DWD", async () => {
it("should return credentials for enabled Google DelegationCredential", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await getAllDwdCredentialsForUser({ user: mockUser });
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await getAllDelegationCredentialsForUser({ user: mockUser });
expect(result).toHaveLength(2);
expect(result).toEqual([buildDwdGoogleCalendarCredential(), buildDwdGoogleMeetCredential()]);
expect(result).toEqual([
buildGoogleCalendarDelegationCredential(),
buildDelegationCredentialGoogleMeetCredential(),
]);
});
it("should return empty array for non-Google platforms(as they are not supported yet)", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(
buildMockDwd({
buildMockDelegationCredential({
workspacePlatform: {
name: "Microsoft",
slug: "microsoft",
},
})
);
const result = await getAllDwdCredentialsForUser({ user: mockUser });
const result = await getAllDelegationCredentialsForUser({ user: mockUser });
expect(result).toEqual([]);
});
});
describe("buildAllCredentials", () => {
const mockDwdGoogleCalendarCred = buildDwdGoogleCalendarCredential();
const mockDelegationCredentialGoogleCalendarCred = buildGoogleCalendarDelegationCredential();
const mockRegularGoogleCalendarCred = buildRegularGoogleCalendarCredential();
it("should combine DWD and regular credentials", () => {
it("should combine DelegationCredential and regular credentials", () => {
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred],
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred],
existingCredentials: [mockRegularGoogleCalendarCred],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDwdGoogleCalendarCred);
expect(result).toContainEqual(mockDelegationCredentialGoogleCalendarCred);
expect(result).toContainEqual(mockRegularGoogleCalendarCred);
});
it("should deduplicate DWD credentials with same delegatedToId and appId", () => {
const duplicateDwdCredential = buildDwdGoogleCalendarCredential();
it("should deduplicate DelegationCredential credentials with same delegatedToId and appId", () => {
const duplicateDelegationCredential = buildGoogleCalendarDelegationCredential();
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred, duplicateDwdCredential],
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred, duplicateDelegationCredential],
existingCredentials: [],
});
expect(result).toHaveLength(1);
expect(result[0]).toEqual(mockDwdGoogleCalendarCred);
expect(result[0]).toEqual(mockDelegationCredentialGoogleCalendarCred);
});
it("should keep DWD credentials with same delegatedToId but different appId", () => {
const differentAppDwdCredential = buildDwdGoogleMeetCredential();
it("should keep DelegationCredential credentials with same delegatedToId but different appId", () => {
const differentAppDelegationCredential = buildDelegationCredentialGoogleMeetCredential();
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred, differentAppDwdCredential],
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred, differentAppDelegationCredential],
existingCredentials: [],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDwdGoogleCalendarCred);
expect(result).toContainEqual(differentAppDwdCredential);
expect(result).toContainEqual(mockDelegationCredentialGoogleCalendarCred);
expect(result).toContainEqual(differentAppDelegationCredential);
});
it("should filter out DWD credentials from existingCredentials", () => {
const dwdCalendarCredential = buildRegularGoogleCalendarCredential({ id: -2 });
it("should filter out DelegationCredential credentials from existingCredentials", () => {
const delegatedCalendarCredential = buildRegularGoogleCalendarCredential({ id: -2 });
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred],
existingCredentials: [mockRegularGoogleCalendarCred, dwdCalendarCredential],
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred],
existingCredentials: [mockRegularGoogleCalendarCred, delegatedCalendarCredential],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDwdGoogleCalendarCred);
expect(result).toContainEqual(mockDelegationCredentialGoogleCalendarCred);
expect(result).toContainEqual(mockRegularGoogleCalendarCred);
});
});
describe("getDwdOrRegularCredential", () => {
const mockDwdGoogleCalendarCred = buildDwdGoogleCalendarCredential();
describe("getDelegationCredentialOrRegularCredential", () => {
const mockDelegationCredentialGoogleCalendarCred = buildGoogleCalendarDelegationCredential();
const mockRegularGoogleCalendarCred = buildRegularGoogleCalendarCredential();
const credentials = [mockDwdGoogleCalendarCred, mockRegularGoogleCalendarCred];
const credentials = [mockDelegationCredentialGoogleCalendarCred, mockRegularGoogleCalendarCred];
it("should find DWD credential by dwdId", () => {
const result = getDwdOrRegularCredential({
it("should find Delegation credential by delegationCredentialId", () => {
const result = getDelegationCredentialOrRegularCredential({
credentials,
id: { credentialId: null, dwdId: mockDwd.id },
id: { credentialId: null, delegationCredentialId: mockDelegationCredential.id },
});
expect(result).toEqual(mockDwdGoogleCalendarCred);
expect(result).toEqual(mockDelegationCredentialGoogleCalendarCred);
});
it("should find regular credential by credentialId", () => {
const result = getDwdOrRegularCredential({
const result = getDelegationCredentialOrRegularCredential({
credentials,
id: { credentialId: mockRegularGoogleCalendarCred.id, dwdId: null },
id: { credentialId: mockRegularGoogleCalendarCred.id, delegationCredentialId: null },
});
expect(result).toEqual(mockRegularGoogleCalendarCred);
});
it("should return null when no matching credential found", () => {
const result = getDwdOrRegularCredential({
const result = getDelegationCredentialOrRegularCredential({
credentials,
id: { credentialId: 999, dwdId: null },
id: { credentialId: 999, delegationCredentialId: null },
});
expect(result).toBeNull();
});
it("should not match null to null for delegatedToId", () => {
const result = getDwdOrRegularCredential({
const result = getDelegationCredentialOrRegularCredential({
credentials,
id: { credentialId: null, dwdId: null },
id: { credentialId: null, delegationCredentialId: null },
});
expect(result).toBeNull();
});
});
describe("enrichUsersWithDwdCredentials", () => {
describe("enrichUsersWithDelegationCredentials", () => {
const mockUsers = [
{
...mockUser,
@@ -330,7 +333,7 @@ describe("enrichUsersWithDwdCredentials", () => {
});
it("should return users as is when orgId is null", async () => {
const result = await enrichUsersWithDwdCredentials({
const result = await enrichUsersWithDelegationCredentials({
orgId: null,
users: mockUsers,
});
@@ -347,19 +350,19 @@ describe("enrichUsersWithDwdCredentials", () => {
);
});
it("should enrich users with DWD credentials when available", async () => {
it("should enrich users with DelegationCredential credentials when available", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await enrichUsersWithDwdCredentials({
const result = await enrichUsersWithDelegationCredentials({
orgId: 1,
users: mockUsers,
});
expect(result).toHaveLength(2);
result.forEach((enrichedUser) => {
expect(enrichedUser.credentials).toHaveLength(3); // 1 regular + 2 DWD (calendar + meet)
expect(enrichedUser.credentials).toHaveLength(3); // 1 regular + 2 DelegationCredential (calendar + meet)
expect(enrichedUser.credentials).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
@@ -375,12 +378,12 @@ describe("enrichUsersWithDwdCredentials", () => {
});
});
it("should not add DWD credentials when DWD is disabled", async () => {
it("should not add DelegationCredential credentials when DelegationCredential is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
const result = await enrichUsersWithDwdCredentials({
const result = await enrichUsersWithDelegationCredentials({
orgId: 1,
users: mockUsers,
});
@@ -398,7 +401,7 @@ describe("enrichUsersWithDwdCredentials", () => {
});
});
describe("enrichHostsWithDwdCredentials", () => {
describe("enrichHostsWithDelegationCredentials", () => {
const mockHosts = [
{
user: {
@@ -422,7 +425,7 @@ describe("enrichHostsWithDwdCredentials", () => {
});
it("should return hosts as is when orgId is null", async () => {
const result = await enrichHostsWithDwdCredentials({
const result = await enrichHostsWithDelegationCredentials({
orgId: null,
hosts: mockHosts,
});
@@ -442,12 +445,12 @@ describe("enrichHostsWithDwdCredentials", () => {
);
});
it("should enrich hosts with DWD credentials when available", async () => {
it("should enrich hosts with DelegationCredential credentials when available", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await enrichHostsWithDwdCredentials({
const result = await enrichHostsWithDelegationCredentials({
orgId: 1,
hosts: mockHosts,
});
@@ -455,7 +458,7 @@ describe("enrichHostsWithDwdCredentials", () => {
expect(result).toHaveLength(2);
result.forEach((enrichedHost) => {
expect(enrichedHost.metadata).toBeDefined(); // Preserve non-user data
expect(enrichedHost.user.credentials).toHaveLength(3); // 1 regular + 2 DWD (calendar + meet)
expect(enrichedHost.user.credentials).toHaveLength(3); // 1 regular + 2 DelegationCredential (calendar + meet)
expect(enrichedHost.user.credentials).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
@@ -471,12 +474,12 @@ describe("enrichHostsWithDwdCredentials", () => {
});
});
it("should not add DWD credentials when DWD is disabled", async () => {
it("should not add DelegationCredential credentials when DelegationCredential is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
const result = await enrichHostsWithDwdCredentials({
const result = await enrichHostsWithDelegationCredentials({
orgId: 1,
hosts: mockHosts,
});
@@ -497,7 +500,7 @@ describe("enrichHostsWithDwdCredentials", () => {
});
});
describe("enrichUserWithDwdCredentialsWithoutOrgId", () => {
describe("enrichUserWithDelegationCredentialsWithoutOrgId", () => {
const mockUserWithCredentials = {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
@@ -507,16 +510,16 @@ describe("enrichUserWithDwdCredentialsWithoutOrgId", () => {
vi.clearAllMocks();
});
it("should enrich user with DWD credentials when available", async () => {
it("should enrich user with DelegationCredential credentials when available", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await enrichUserWithDwdCredentialsWithoutOrgId({
const result = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result.credentials).toHaveLength(3); // 1 regular + 2 DWD (calendar + meet)
expect(result.credentials).toHaveLength(3); // 1 regular + 2 DelegationCredential (calendar + meet)
expect(result.credentials).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
@@ -531,12 +534,12 @@ describe("enrichUserWithDwdCredentialsWithoutOrgId", () => {
);
});
it("should not add DWD credentials when DWD is not found", async () => {
it("should not add DelegationCredential credentials when DelegationCredential is not found", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await enrichUserWithDwdCredentialsWithoutOrgId({
const result = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
@@ -550,12 +553,12 @@ describe("enrichUserWithDwdCredentialsWithoutOrgId", () => {
});
});
it("should not add DWD credentials when DWD is disabled", async () => {
it("should not add DelegationCredential credentials when DelegationCredential is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
const result = await enrichUserWithDwdCredentialsWithoutOrgId({
const result = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
@@ -570,7 +573,7 @@ describe("enrichUserWithDwdCredentialsWithoutOrgId", () => {
});
});
describe("enrichUserWithDwdConferencingCredentialsWithoutOrgId", () => {
describe("enrichUserWithDelegationConferencingCredentialsWithoutOrgId", () => {
const mockUserWithCredentials = {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
@@ -582,10 +585,10 @@ describe("enrichUserWithDwdConferencingCredentialsWithoutOrgId", () => {
it("should only return conferencing credentials", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDelegationCredential());
const result = await enrichUserWithDwdConferencingCredentialsWithoutOrgId({
const result = await enrichUserWithDelegationConferencingCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
@@ -600,10 +603,10 @@ describe("enrichUserWithDwdConferencingCredentialsWithoutOrgId", () => {
it("should return empty credentials array when no conferencing credentials found", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await enrichUserWithDwdConferencingCredentialsWithoutOrgId({
const result = await enrichUserWithDelegationConferencingCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
@@ -6,21 +6,21 @@ import { metadata as office365VideoMetaData } from "@calcom/app-store/office365v
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import type { ServiceAccountKey } from "@calcom/lib/server/repository/domainWideDelegation";
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import type { ServiceAccountKey } from "@calcom/lib/server/repository/delegationCredential";
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import { buildNonDwdCredentials, isDwdCredential } from "./clientAndServer";
import { buildNonDelegationCredentials, isDelegationCredential } from "./clientAndServer";
export { buildNonDwdCredentials, buildNonDwdCredential } from "./clientAndServer";
export { buildNonDelegationCredentials, buildNonDelegationCredential } from "./clientAndServer";
const GOOGLE_WORKSPACE_SLUG = "google";
const OFFICE365_WORKSPACE_SLUG = "office365";
const WORKSPACE_PLATFORM_SLUGS = [GOOGLE_WORKSPACE_SLUG, OFFICE365_WORKSPACE_SLUG] as const;
type WORKSPACE_PLATFORM_SLUGS_TYPE = (typeof WORKSPACE_PLATFORM_SLUGS)[number];
const log = logger.getSubLogger({ prefix: ["lib/domainWideDelegation/server"] });
interface DomainWideDelegation {
const log = logger.getSubLogger({ prefix: ["lib/delegationCredential/server"] });
interface DelegationCredential {
id: string;
workspacePlatform: {
slug: string;
@@ -28,7 +28,7 @@ interface DomainWideDelegation {
serviceAccountKey: ServiceAccountKey | null;
}
interface DomainWideDelegationWithSensitiveServiceAccountKey extends DomainWideDelegation {
interface DelegationCredentialWithSensitiveServiceAccountKey extends DelegationCredential {
serviceAccountKey: ServiceAccountKey;
}
@@ -41,7 +41,10 @@ const isValidWorkspaceSlug = (slug: string) => {
return WORKSPACE_PLATFORM_SLUGS.includes(slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE);
};
const getDwdAppMetadata = (slug: WORKSPACE_PLATFORM_SLUGS_TYPE, isConferencing?: boolean) => {
const getDelegationCredentialAppMetadata = (
slug: WORKSPACE_PLATFORM_SLUGS_TYPE,
isConferencing?: boolean
) => {
switch (slug) {
case GOOGLE_WORKSPACE_SLUG:
return isConferencing
@@ -66,10 +69,16 @@ const _isConferencingCredential = (credential: CredentialPayload) => {
);
};
const _buildCommonUserCredential = ({ dwd, user }: { dwd: DomainWideDelegation; user: User }) => {
const _buildCommonUserCredential = ({
delegationCredential,
user,
}: {
delegationCredential: DelegationCredential;
user: User;
}) => {
return {
id: -1,
delegatedToId: dwd.id,
delegatedToId: delegationCredential.id,
userId: user.id,
user: {
email: user.email,
@@ -80,159 +89,181 @@ const _buildCommonUserCredential = ({ dwd, user }: { dwd: DomainWideDelegation;
invalid: false,
teamId: null,
team: null,
delegatedTo: dwd.serviceAccountKey
delegatedTo: delegationCredential.serviceAccountKey
? {
serviceAccountKey: dwd.serviceAccountKey,
serviceAccountKey: delegationCredential.serviceAccountKey,
}
: null,
};
};
const _buildDwdCalendarCredential = ({ dwd, user }: { dwd: DomainWideDelegation; user: User }) => {
log.debug("buildDomainWideDelegationCredential", safeStringify({ dwd, user }));
const _buildDelegatedCalendarCredential = ({
delegationCredential,
user,
}: {
delegationCredential: DelegationCredential;
user: User;
}) => {
log.debug("buildDelegationCredential", safeStringify({ delegationCredential, user }));
// TODO: Build for other platforms as well
if (!isValidWorkspaceSlug(dwd.workspacePlatform.slug)) {
if (!isValidWorkspaceSlug(delegationCredential.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
dwd.workspacePlatform.slug
delegationCredential.workspacePlatform.slug
}`
);
return null;
}
return {
...getDwdAppMetadata(dwd.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE, false),
..._buildCommonUserCredential({ dwd, user }),
...getDelegationCredentialAppMetadata(
delegationCredential.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE,
false
),
..._buildCommonUserCredential({ delegationCredential, user }),
};
};
const _buildDwdCalendarCredentialWithServiceAccountKey = ({
dwd,
const _buildDelegatedCalendarCredentialWithServiceAccountKey = ({
delegationCredential,
user,
}: {
dwd: DomainWideDelegationWithSensitiveServiceAccountKey;
delegationCredential: DelegationCredentialWithSensitiveServiceAccountKey;
user: User;
}) => {
const credential = _buildDwdCalendarCredential({ dwd, user });
const credential = _buildDelegatedCalendarCredential({ delegationCredential, user });
if (!credential) {
return null;
}
return {
...credential,
delegatedTo: {
serviceAccountKey: dwd.serviceAccountKey,
serviceAccountKey: delegationCredential.serviceAccountKey,
},
};
};
const _buildDwdConferencingCredential = ({ dwd, user }: { dwd: DomainWideDelegation; user: User }) => {
const _buildDelegatedConferencingCredential = ({
delegationCredential,
user,
}: {
delegationCredential: DelegationCredential;
user: User;
}) => {
// TODO: Build for other platforms as well
if (!isValidWorkspaceSlug(dwd.workspacePlatform.slug)) {
if (!isValidWorkspaceSlug(delegationCredential.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
dwd.workspacePlatform.slug
delegationCredential.workspacePlatform.slug
}`
);
return null;
}
return {
...getDwdAppMetadata(dwd.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE, true),
..._buildCommonUserCredential({ dwd, user }),
...getDelegationCredentialAppMetadata(
delegationCredential.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE,
true
),
..._buildCommonUserCredential({ delegationCredential, user }),
};
};
/**
* Gets calendar as well as conferencing credentials(stored in-memory) for the user from the corresponding enabled DomainWideDelegation.
* Gets calendar as well as conferencing credentials(stored in-memory) for the user from the corresponding enabled DelegationCredential.
*/
export async function getAllDwdCredentialsForUser({ user }: { user: { email: string; id: number } }) {
export async function getAllDelegationCredentialsForUser({ user }: { user: { email: string; id: number } }) {
log.debug("called with", safeStringify({ user }));
// We access the repository without checking for feature flag here.
// In case we need to disable the effects of DWD on credential we need to toggle DWD off from organization settings.
// We could think of the teamFeatures flag to just disable the UI. The actual effect of DWD on credentials is disabled by toggling DWD off from UI
const dwd =
await DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
// In case we need to disable the effects of DelegationCredential on credential we need to toggle DelegationCredential off from organization settings.
// We could think of the teamFeatures flag to just disable the UI. The actual effect of DelegationCredential on credentials is disabled by toggling DelegationCredential off from UI
const delegationCredential =
await DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
email: user.email,
});
if (!dwd || !dwd.enabled) {
if (!delegationCredential || !delegationCredential.enabled) {
return [];
}
const domainWideDelegationCredentials = [
_buildDwdCalendarCredential({ dwd, user }),
_buildDwdConferencingCredential({ dwd, user }),
const delegationCredentials = [
_buildDelegatedCalendarCredential({ delegationCredential, user }),
_buildDelegatedConferencingCredential({ delegationCredential, user }),
].filter((credential): credential is NonNullable<typeof credential> => credential !== null);
log.debug("Returned", safeStringify({ domainWideDelegationCredentials }));
return domainWideDelegationCredentials;
log.debug("Returned", safeStringify({ delegationCredentials }));
return delegationCredentials;
}
export async function getAllDwdCalendarCredentialsForUser({ user }: { user: { email: string; id: number } }) {
const dwdCredentials = await getAllDwdCredentialsForUser({ user });
return dwdCredentials.filter((credential) => credential.type.endsWith("_calendar"));
export async function getAllDelegatedCalendarCredentialsForUser({
user,
}: {
user: { email: string; id: number };
}) {
const delegationCredentials = await getAllDelegationCredentialsForUser({ user });
return delegationCredentials.filter((credential) => credential.type.endsWith("_calendar"));
}
async function _getDwdCredentialsMapPerUser({
async function _getDelegationCredentialsMapPerUser({
organizationId,
users,
}: {
organizationId: number | null;
users: User[];
}) {
const emptyMap = new Map<number, NonNullable<ReturnType<typeof _buildDwdCalendarCredential>>[]>();
const emptyMap = new Map<number, NonNullable<ReturnType<typeof _buildDelegatedCalendarCredential>>[]>();
if (!organizationId) {
return emptyMap;
}
const domain = users[0].email.split("@")[1];
log.debug("called with", safeStringify({ users }));
const dwd =
await DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
const delegationCredential =
await DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
{
organizationId,
domain,
}
);
if (!dwd || !dwd.enabled) {
if (!delegationCredential || !delegationCredential.enabled) {
return emptyMap;
}
const credentialsByUserId = new Map<
number,
NonNullable<ReturnType<typeof _buildDwdCalendarCredential>>[]
NonNullable<ReturnType<typeof _buildDelegatedCalendarCredential>>[]
>();
for (const user of users) {
const domainWideDelegationCredentials = [
_buildDwdCalendarCredential({ dwd, user }),
_buildDwdConferencingCredential({ dwd, user }),
const delegationCredentials = [
_buildDelegatedCalendarCredential({ delegationCredential, user }),
_buildDelegatedConferencingCredential({ delegationCredential, user }),
].filter((credential): credential is NonNullable<typeof credential> => credential !== null);
log.debug("Returned for user", safeStringify({ user, domainWideDelegationCredentials }));
credentialsByUserId.set(user.id, domainWideDelegationCredentials);
log.debug("Returned for user", safeStringify({ user, delegationCredentials }));
credentialsByUserId.set(user.id, delegationCredentials);
}
return credentialsByUserId;
}
export async function checkIfSuccessfullyConfiguredInWorkspace({
dwd,
delegationCredential,
user,
}: {
dwd: DomainWideDelegationWithSensitiveServiceAccountKey;
delegationCredential: DelegationCredentialWithSensitiveServiceAccountKey;
user: User;
}) {
if (!isValidWorkspaceSlug(dwd.workspacePlatform.slug)) {
if (!isValidWorkspaceSlug(delegationCredential.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
dwd.workspacePlatform.slug
delegationCredential.workspacePlatform.slug
}`
);
return false;
}
const credential = _buildDwdCalendarCredentialWithServiceAccountKey({
dwd,
const credential = _buildDelegatedCalendarCredentialWithServiceAccountKey({
delegationCredential,
user,
});
@@ -241,31 +272,31 @@ export async function checkIfSuccessfullyConfiguredInWorkspace({
if (!calendar) {
throw new Error("Google Calendar App not found");
}
return await calendar?.testDomainWideDelegationSetup?.();
return await calendar?.testDelegationCredentialSetup?.();
}
export async function getAllDwdCredentialsForUserByAppType({
export async function getAllDelegationCredentialsForUserByAppType({
user,
appType,
}: {
user: User;
appType: string;
}) {
const dwdCredentials = await getAllDwdCredentialsForUser({
const delegationCredentials = await getAllDelegationCredentialsForUser({
user,
});
return dwdCredentials.filter((credential) => credential.type === appType);
return delegationCredentials.filter((credential) => credential.type === appType);
}
export async function getAllDwdCredentialsForUserByAppSlug({
export async function getAllDelegationCredentialsForUserByAppSlug({
user,
appSlug,
}: {
user: User;
appSlug: string;
}) {
const dwdCredentials = await getAllDwdCredentialsForUser({ user });
return dwdCredentials.filter((credential) => credential.appId === appSlug);
const delegationCredentials = await getAllDelegationCredentialsForUser({ user });
return delegationCredentials.filter((credential) => credential.appId === appSlug);
}
type Host<TUser extends { id: number; email: string; credentials: CredentialPayload[] }> = {
@@ -274,19 +305,21 @@ type Host<TUser extends { id: number; email: string; credentials: CredentialPayl
/**
* Prepares credentials for use by CalendarService and EventManager
* - Ensures no duplicate dwd credentials caused by enrichment at possibly multiple places
* - Ensures no duplicate delegationCredentials caused by enrichment at possibly multiple places
*/
export const buildAllCredentials = ({
dwdCredentials,
delegationCredentials,
existingCredentials,
}: {
dwdCredentials: CredentialForCalendarService[];
delegationCredentials: CredentialForCalendarService[];
existingCredentials: CredentialPayload[];
}) => {
const nonDwdCredentials = existingCredentials.filter((cred) => !isDwdCredential({ credentialId: cred.id }));
const nonDelegationCredentials = existingCredentials.filter(
(cred) => !isDelegationCredential({ credentialId: cred.id })
);
const allCredentials: CredentialForCalendarService[] = [
...dwdCredentials,
...buildNonDwdCredentials(nonDwdCredentials),
...delegationCredentials,
...buildNonDelegationCredentials(nonDelegationCredentials),
];
const uniqueAllCredentials = allCredentials.reduce((acc, credential) => {
@@ -295,10 +328,10 @@ export const buildAllCredentials = ({
acc.push(credential);
return acc;
}
const existingDwdCredential = acc.find(
const existingDelegationCredential = acc.find(
(c) => c.delegatedToId === credential.delegatedToId && c.appId === credential.appId
);
if (!existingDwdCredential) {
if (!existingDelegationCredential) {
acc.push(credential);
}
return acc;
@@ -307,10 +340,10 @@ export const buildAllCredentials = ({
return uniqueAllCredentials;
};
export async function enrichUsersWithDwdCredentials<
export async function enrichUsersWithDelegationCredentials<
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({ orgId, users }: { orgId: number | null; users: TUser[] }) {
const dwdCredentialsMap = await _getDwdCredentialsMapPerUser({
const delegationCredentialsMap = await _getDelegationCredentialsMapPerUser({
organizationId: orgId,
users,
});
@@ -318,7 +351,7 @@ export async function enrichUsersWithDwdCredentials<
const enrichedUsers = users.map((user) => {
const { credentials, ...rest } = user;
const enrichedCredentials = buildAllCredentials({
dwdCredentials: dwdCredentialsMap.get(user.id) ?? [],
delegationCredentials: delegationCredentialsMap.get(user.id) ?? [],
existingCredentials: credentials,
});
return {
@@ -326,11 +359,11 @@ export async function enrichUsersWithDwdCredentials<
credentials: enrichedCredentials,
};
});
log.debug("enrichUsersWithDwdCredentials", safeStringify({ enrichedUsers, orgId }));
log.debug("enrichUsersWithDelegationCredentials", safeStringify({ enrichedUsers, orgId }));
return enrichedUsers;
}
export const enrichHostsWithDwdCredentials = async <
export const enrichHostsWithDelegationCredentials = async <
THost extends Host<TUser>,
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({
@@ -340,7 +373,7 @@ export const enrichHostsWithDwdCredentials = async <
orgId: number | null;
hosts: THost[];
}) => {
const dwdCredentialsMap = await _getDwdCredentialsMapPerUser({
const delegationCredentialsMap = await _getDelegationCredentialsMapPerUser({
organizationId: orgId,
users: hosts.map((host) => host.user),
});
@@ -352,38 +385,38 @@ export const enrichHostsWithDwdCredentials = async <
user: {
...restUser,
credentials: buildAllCredentials({
dwdCredentials: dwdCredentialsMap.get(restUser.id) ?? [],
delegationCredentials: delegationCredentialsMap.get(restUser.id) ?? [],
existingCredentials: credentials,
}),
},
};
});
log.debug("enrichHostsWithDwdCredentials", safeStringify({ enrichedHosts, orgId }));
log.debug("enrichHostsWithDelegationCredentials", safeStringify({ enrichedHosts, orgId }));
return enrichedHosts;
};
export const enrichUserWithDwdCredentialsWithoutOrgId = async <
export const enrichUserWithDelegationCredentialsWithoutOrgId = async <
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({
user,
}: {
user: TUser;
}) => {
const dwdCredentials = await getAllDwdCredentialsForUser({ user });
const delegationCredentials = await getAllDelegationCredentialsForUser({ user });
const { credentials, ...restUser } = user;
return {
...restUser,
credentials: buildAllCredentials({
dwdCredentials: dwdCredentials,
delegationCredentials: delegationCredentials,
existingCredentials: credentials,
}),
};
};
export async function enrichUserWithDwdConferencingCredentialsWithoutOrgId<
export async function enrichUserWithDelegationConferencingCredentialsWithoutOrgId<
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({ user }: { user: TUser }) {
const { credentials, ...restUser } = await enrichUserWithDwdCredentialsWithoutOrgId({ user });
const { credentials, ...restUser } = await enrichUserWithDelegationCredentialsWithoutOrgId({ user });
return {
...restUser,
credentials: credentials.filter(_isConferencingCredential),
@@ -391,20 +424,20 @@ export async function enrichUserWithDwdConferencingCredentialsWithoutOrgId<
}
/**
* Either get DWD credential from dwdCredentials or find regular credential from Credential table
* Either get Delegation credential from delegationCredentials or find regular credential from Credential table
*/
export async function getDwdOrFindRegularCredential({
export async function getDelegationCredentialOrFindRegularCredential({
id,
dwdCredentials,
delegationCredentials,
}: {
id: {
credentialId: number | null | undefined;
domainWideDelegationCredentialId: string | null | undefined;
delegationCredentialId: string | null | undefined;
};
dwdCredentials: CredentialForCalendarService[];
delegationCredentials: CredentialForCalendarService[];
}) {
return id.domainWideDelegationCredentialId
? dwdCredentials.find((cred) => cred.delegatedToId === id.domainWideDelegationCredentialId)
return id.delegationCredentialId
? delegationCredentials.find((cred) => cred.delegatedToId === id.delegationCredentialId)
: id.credentialId
? await CredentialRepository.findCredentialForCalendarServiceById({
id: id.credentialId,
@@ -413,20 +446,22 @@ export async function getDwdOrFindRegularCredential({
}
/**
* Utility function to find a credential from a list of credentials, supporting both regular and DWD credentials
* Utility function to find a credential from a list of credentials, supporting both regular and DelegationCredential credentials
*/
export function getDwdOrRegularCredential<TCredential extends { delegatedToId?: string | null; id: number }>({
export function getDelegationCredentialOrRegularCredential<
TCredential extends { delegatedToId?: string | null; id: number }
>({
credentials,
id,
}: {
credentials: TCredential[];
id: { credentialId: number | null | undefined; dwdId: string | null | undefined };
id: { credentialId: number | null | undefined; delegationCredentialId: string | null | undefined };
}) {
return (
credentials.find((cred) => {
// Ensure that we don't match null to null
if (cred.delegatedToId) {
return cred.delegatedToId === id.dwdId;
return cred.delegatedToId === id.delegationCredentialId;
} else if (id.credentialId) {
return cred.id === id.credentialId;
}
@@ -435,7 +470,7 @@ export function getDwdOrRegularCredential<TCredential extends { delegatedToId?:
);
}
export function getFirstDwdConferencingCredential({
export function getFirstDelegationConferencingCredential({
credentials,
}: {
credentials: CredentialForCalendarService[];
@@ -443,16 +478,16 @@ export function getFirstDwdConferencingCredential({
return credentials.find((credential) => _isConferencingCredential(credential));
}
export function getFirstDwdConferencingCredentialAppLocation({
export function getFirstDelegationConferencingCredentialAppLocation({
credentials,
}: {
credentials: CredentialForCalendarService[];
}) {
const dwdConferencingCredential = getFirstDwdConferencingCredential({ credentials });
if (dwdConferencingCredential?.appId === googleMeetMetadata.slug) {
const delegatedConferencingCredential = getFirstDelegationConferencingCredential({ credentials });
if (delegatedConferencingCredential?.appId === googleMeetMetadata.slug) {
return googleMeetMetadata.appData?.location?.type ?? null;
}
if (dwdConferencingCredential?.appId === office365VideoMetaData.slug) {
if (delegatedConferencingCredential?.appId === office365VideoMetaData.slug) {
return office365VideoMetaData.appData?.location?.type ?? null;
}
return null;
@@ -1,27 +0,0 @@
export function isDwdCredential({ credentialId }: { credentialId: number | null | undefined }) {
// Though it is set as -1 right now, but we might want to set it to some other negative value.
return typeof credentialId === "number" && credentialId < 0;
}
export const buildNonDwdCredential = <T extends Record<string, unknown> | null>(credential: T) => {
type WithDelegatedCredential = T extends null
? null
: T & {
delegatedTo: null;
delegatedToId: null;
};
if (!credential) return null as WithDelegatedCredential;
return {
...credential,
delegatedTo: null,
delegatedToId: null,
} as WithDelegatedCredential;
};
export const buildNonDwdCredentials = <T extends Record<string, unknown>>(credentials: T[]) => {
return credentials.map(buildNonDwdCredential).filter((credential) => !!credential) as (T & {
delegatedTo: null;
delegatedToId: null;
})[];
};
+2 -2
View File
@@ -13,7 +13,7 @@ import type { TeamQuery } from "@calcom/trpc/server/routers/loggedInViewer/integ
import type { TIntegrationsInputSchema } from "@calcom/trpc/server/routers/loggedInViewer/integrations.schema";
import type { PaymentApp } from "@calcom/types/PaymentService";
import { buildNonDwdCredentials } from "./domainWideDelegation/clientAndServer";
import { buildNonDelegationCredentials } from "./delegationCredential/clientAndServer";
export type ConnectedApps = Awaited<ReturnType<typeof getConnectedApps>>;
@@ -106,7 +106,7 @@ export async function getConnectedApps({
userTeams = [...teamsQuery, ...parentTeams];
const teamAppCredentials = userTeams.flatMap((teamApp) => {
return teamApp.credentials ? buildNonDwdCredentials(teamApp.credentials.flat()) : [];
return teamApp.credentials ? buildNonDelegationCredentials(teamApp.credentials.flat()) : [];
});
if (!includeTeamInstalledApps || teamId) {
credentials = teamAppCredentials;
@@ -1,6 +1,6 @@
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/lib/CalendarManager";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { isDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "@calcom/lib/delegationCredential/server";
import logger from "@calcom/lib/logger";
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
@@ -27,14 +27,14 @@ export type ConnectedDestinationCalendars = Awaited<
>;
/**
* Ensures that when DWD is enabled and there is already a calendar connected for the corresponding domain, we only allow the DWD calendar to be returned
* This is to ensure that duplicate calendar connections aren't shown in UI(apps/installed/calendars). We choose DWD connection to be shown because we don't want users to be able to work with individual calendars
* Ensures that when DelegationCredential is enabled and there is already a calendar connected for the corresponding domain, we only allow the DelegationCredential calendar to be returned
* This is to ensure that duplicate calendar connections aren't shown in UI(apps/installed/calendars). We choose DelegationCredential connection to be shown because we don't want users to be able to work with individual calendars
*/
const _ensureNoConflictingNonDwdConnectedCalendar = <
const _ensureNoConflictingNonDelegatedConnectedCalendar = <
T extends {
integration: { slug: string };
primary?: { email?: string | null | undefined } | undefined;
domainWideDelegationCredentialId?: string | null | undefined;
delegationCredentialId?: string | null | undefined;
}
>({
connectedCalendars,
@@ -51,18 +51,18 @@ const _ensureNoConflictingNonDwdConnectedCalendar = <
// If no other calendar with this slug, keep it
if (allCalendarsWithSameAppSlug.length === 1) return true;
const dwdCalendarsWithSameAppSlug = allCalendarsWithSameAppSlug.filter(
(cal) => cal.domainWideDelegationCredentialId
const delegatedCalendarsWithSameAppSlug = allCalendarsWithSameAppSlug.filter(
(cal) => cal.delegationCredentialId
);
if (!dwdCalendarsWithSameAppSlug.length) {
if (!delegatedCalendarsWithSameAppSlug.length) {
return true;
}
if (connectedCalendar.domainWideDelegationCredentialId) {
if (connectedCalendar.delegationCredentialId) {
return true;
}
// DWD Credential is always of the loggedInUser
// DelegationCredential Credential is always of the loggedInUser
if (!connectedCalendar.primary?.email || connectedCalendar.primary.email !== loggedInUser.email) {
return true;
}
@@ -116,7 +116,7 @@ async function handleNoDestinationCalendar({
integration = "",
externalId = "",
credentialId,
domainWideDelegationCredentialId,
delegationCredentialId,
email: primaryEmail,
} = connectedCalendars[0].primary ?? {};
@@ -140,12 +140,12 @@ async function handleNoDestinationCalendar({
integration,
externalId,
primaryEmail,
...(!isDwdCredential({ credentialId })
...(!isDelegationCredential({ credentialId })
? {
credentialId,
}
: {
domainWideDelegationCredentialId,
delegationCredentialId,
}),
},
});
@@ -285,7 +285,7 @@ export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
select: credentialForCalendarServiceSelect,
});
const { credentials: allCredentials } = await enrichUserWithDwdCredentialsWithoutOrgId({
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: { id: user.id, email: user.email, credentials: userCredentials },
});
@@ -363,12 +363,12 @@ export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
});
}
const noConflictingNonDwdConnectedCalendars = _ensureNoConflictingNonDwdConnectedCalendar({
const noConflictingNonDelegatedConnectedCalendars = _ensureNoConflictingNonDelegatedConnectedCalendar({
connectedCalendars,
loggedInUser: { email: user.email },
});
return {
connectedCalendars: noConflictingNonDwdConnectedCalendars,
connectedCalendars: noConflictingNonDelegatedConnectedCalendars,
destinationCalendar: {
...(user.destinationCalendar as DestinationCalendar),
...destinationCalendar,
+5 -5
View File
@@ -9,7 +9,7 @@ import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/crede
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "../domainWideDelegation/server";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "../delegationCredential/server";
import { getBookerBaseUrl } from "../getBookerUrl/server";
async function getEventType(id: number) {
@@ -103,11 +103,11 @@ export async function getBooking(bookingId: number) {
const eventType = { ...eventTypeRaw, metadata: EventTypeMetaDataSchema.parse(eventTypeRaw?.metadata) };
const { user: userWithoutDwdCredentials } = booking;
const { user: userWithoutDelegationCredentials } = booking;
if (!userWithoutDwdCredentials) throw new HttpCode({ statusCode: 204, message: "No user found" });
const user = await enrichUserWithDwdCredentialsWithoutOrgId({
user: userWithoutDwdCredentials,
if (!userWithoutDelegationCredentials) throw new HttpCode({ statusCode: 204, message: "No user found" });
const user = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: userWithoutDelegationCredentials,
});
const t = await getTranslation(user.locale ?? "en", "common");
@@ -1,28 +1,28 @@
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { isDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
export function buildCredentialPayloadForPrisma({
credentialId,
domainWideDelegationCredentialId,
delegationCredentialId,
}: {
credentialId: number | null | undefined;
domainWideDelegationCredentialId: string | null | undefined;
delegationCredentialId: string | null | undefined;
}) {
if (credentialId === undefined) {
return {
credentialId,
domainWideDelegationCredentialId,
delegationCredentialId,
};
}
if (isDwdCredential({ credentialId })) {
if (isDelegationCredential({ credentialId })) {
return {
credentialId: null,
domainWideDelegationCredentialId,
delegationCredentialId,
};
} else {
return {
credentialId,
domainWideDelegationCredentialId: null,
delegationCredentialId: null,
};
}
}
@@ -1,6 +1,6 @@
import type { Prisma } from "@prisma/client";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "@calcom/lib/delegationCredential/server";
import { availabilityUserSelect } from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -23,7 +23,7 @@ export async function findUsersForAvailabilityCheck({ where }: { where: Prisma.U
return null;
}
return await enrichUserWithDwdCredentialsWithoutOrgId({
return await enrichUserWithDelegationCredentialsWithoutOrgId({
user: withSelectedCalendars(user),
});
}
+3 -3
View File
@@ -2,13 +2,13 @@ import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "../domainWideDelegation/server";
import { enrichUserWithDelegationCredentialsWithoutOrgId } from "../delegationCredential/server";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = { id: SessionUser["id"]; email: SessionUser["email"] };
/**
* It includes in-memory DWD credentials as well.
* It includes in-memory DelegationCredential credentials as well.
*/
export async function getUsersCredentials(user: User) {
const credentials = await prisma.credential.findMany({
@@ -21,7 +21,7 @@ export async function getUsersCredentials(user: User) {
},
});
const { credentials: allCredentials } = await enrichUserWithDwdCredentialsWithoutOrgId({
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsWithoutOrgId({
user: {
email: user.email,
id: user.id,
@@ -4,7 +4,7 @@ import { describe, expect, it, beforeEach, vi } from "vitest";
import { encryptServiceAccountKey } from "@calcom/lib/server/serviceAccountKey";
import { DomainWideDelegationRepository } from "../domainWideDelegation";
import { DelegationCredentialRepository } from "../delegationCredential";
import { OrganizationRepository } from "../organization";
vi.mock("../organization", () => ({
@@ -56,7 +56,7 @@ const buildMockOrganization = () => ({
isOrganization: true,
});
const buildMockDomainWideDelegation = (overrides = {}) => ({
const buildMockDelegationCredential = (overrides = {}) => ({
id: "test-id",
enabled: true,
domain: "example.com",
@@ -68,7 +68,7 @@ const buildMockDomainWideDelegation = (overrides = {}) => ({
});
// Test Utilities
const createTestDomainWideDelegation = async (overrides = {}) => {
const createTestDelegationCredential = async (overrides = {}) => {
// Create organization first (as a team with isOrganization true)
await prismock.team.create({
data: buildMockOrganization(),
@@ -79,9 +79,9 @@ const createTestDomainWideDelegation = async (overrides = {}) => {
data: buildMockWorkspacePlatform(),
});
const data = buildMockDomainWideDelegation(overrides);
const data = buildMockDelegationCredential(overrides);
return await prismock.domainWideDelegation.create({
return await prismock.delegationCredential.create({
data: {
...data,
serviceAccountKey: encryptServiceAccountKey(data.serviceAccountKey),
@@ -96,9 +96,9 @@ const setupOrganizationMock = (returnValue: any) => {
vi.mocked(OrganizationRepository.findByMemberEmail).mockResolvedValue(returnValue);
};
describe("DomainWideDelegationRepository", () => {
describe("DelegationCredentialRepository", () => {
beforeEach(() => {
prismock.domainWideDelegation.deleteMany();
prismock.delegationCredential.deleteMany();
prismock.workspacePlatform.deleteMany();
prismock.team.deleteMany();
vi.clearAllMocks();
@@ -106,13 +106,13 @@ describe("DomainWideDelegationRepository", () => {
describe("Service Account Key Access Control", () => {
beforeEach(async () => {
await createTestDomainWideDelegation();
await createTestDelegationCredential();
});
describe("Regular Find Methods (No Service Account Key)", () => {
describe("findById", () => {
it("should not expose service account key in response", async () => {
const result = await DomainWideDelegationRepository.findById({ id: "test-id" });
const result = await DelegationCredentialRepository.findById({ id: "test-id" });
expect(result).not.toHaveProperty("serviceAccountKey");
expect(result).toEqual(
@@ -127,7 +127,7 @@ describe("DomainWideDelegationRepository", () => {
describe("findAllByDomain", () => {
it("should not expose service account key in any of the results", async () => {
const results = await DomainWideDelegationRepository.findAllByDomain({ domain: "example.com" });
const results = await DelegationCredentialRepository.findAllByDomain({ domain: "example.com" });
expect(results.length).toBeGreaterThan(0);
results.forEach((result) => {
@@ -145,7 +145,7 @@ describe("DomainWideDelegationRepository", () => {
describe("Sensitive Methods (With Service Account Key)", () => {
describe("findByIdIncludeSensitiveServiceAccountKey", () => {
it("should expose valid service account key", async () => {
const result = await DomainWideDelegationRepository.findByIdIncludeSensitiveServiceAccountKey({
const result = await DelegationCredentialRepository.findByIdIncludeSensitiveServiceAccountKey({
id: "test-id",
});
@@ -156,7 +156,7 @@ describe("DomainWideDelegationRepository", () => {
describe("findByOrgIdIncludeSensitiveServiceAccountKey", () => {
it("should expose validated service account keys", async () => {
const results = await DomainWideDelegationRepository.findByOrgIdIncludeSensitiveServiceAccountKey({
const results = await DelegationCredentialRepository.findByOrgIdIncludeSensitiveServiceAccountKey({
organizationId: 1,
});
@@ -170,7 +170,7 @@ describe("DomainWideDelegationRepository", () => {
describe("findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey", () => {
it("should expose validated service account key", async () => {
const result =
await DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
await DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
{
organizationId: 1,
domain: "example.com",
@@ -187,7 +187,7 @@ describe("DomainWideDelegationRepository", () => {
setupOrganizationMock({ id: 1 });
const result =
await DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
await DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
email: "[email protected]",
});
@@ -200,7 +200,7 @@ describe("DomainWideDelegationRepository", () => {
setupOrganizationMock(null);
const result =
await DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
await DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
email: "[email protected]",
});
@@ -212,7 +212,7 @@ describe("DomainWideDelegationRepository", () => {
describe("CRUD Operations", () => {
describe("create", () => {
it("should store domain wide delegation with all required fields and establish connections", async () => {
it("should store delegation credential with all required fields and establish connections", async () => {
// Create organization first (as a team with isOrganization true)
await prismock.team.create({
data: buildMockOrganization(),
@@ -223,11 +223,11 @@ describe("DomainWideDelegationRepository", () => {
data: buildMockWorkspacePlatform(),
});
const data = buildMockDomainWideDelegation();
const data = buildMockDelegationCredential();
delete data.id; // ID is auto-generated
delete data.workspacePlatform; // Don't include the relation in create
const result = await DomainWideDelegationRepository.create(data);
const result = await DelegationCredentialRepository.create(data);
expect(result).toEqual({
id: expect.any(String),
@@ -246,7 +246,7 @@ describe("DomainWideDelegationRepository", () => {
describe("update", () => {
it("should modify workspace platform connection when workspacePlatformId is provided", async () => {
const created = await createTestDomainWideDelegation();
const created = await createTestDelegationCredential();
// Create new workspace platform
const newWorkspacePlatform = await prismock.workspacePlatform.create({
@@ -257,7 +257,7 @@ describe("DomainWideDelegationRepository", () => {
},
});
const result = await DomainWideDelegationRepository.updateById({
const result = await DelegationCredentialRepository.updateById({
id: created.id,
data: { workspacePlatformId: newWorkspacePlatform.id },
});
@@ -277,7 +277,7 @@ describe("DomainWideDelegationRepository", () => {
});
it("should modify organization connection when organizationId is provided", async () => {
const created = await createTestDomainWideDelegation();
const created = await createTestDelegationCredential();
// Create new organization (as a team with isOrganization true)
const newOrganization = await prismock.team.create({
@@ -288,7 +288,7 @@ describe("DomainWideDelegationRepository", () => {
},
});
const result = await DomainWideDelegationRepository.updateById({
const result = await DelegationCredentialRepository.updateById({
id: created.id,
data: { organizationId: newOrganization.id },
});
@@ -308,9 +308,9 @@ describe("DomainWideDelegationRepository", () => {
});
it("should modify specified fields while preserving others", async () => {
const created = await createTestDomainWideDelegation();
const created = await createTestDelegationCredential();
const result = await DomainWideDelegationRepository.updateById({
const result = await DelegationCredentialRepository.updateById({
id: created.id,
data: { enabled: false },
});
@@ -326,12 +326,12 @@ describe("DomainWideDelegationRepository", () => {
});
describe("delete", () => {
it("should remove the domain wide delegation completely", async () => {
const created = await createTestDomainWideDelegation();
it("should remove the delegation credential completely", async () => {
const created = await createTestDelegationCredential();
await DomainWideDelegationRepository.deleteById({ id: created.id });
await DelegationCredentialRepository.deleteById({ id: created.id });
const result = await prismock.domainWideDelegation.findUnique({
const result = await prismock.delegationCredential.findUnique({
where: { id: created.id },
});
expect(result).toBeNull();
+7 -7
View File
@@ -2,7 +2,7 @@ import { prisma } from "@calcom/prisma";
import { safeCredentialSelect } from "@calcom/prisma/selects/credential";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { buildNonDwdCredential } from "../../domainWideDelegation/server";
import { buildNonDelegationCredential } from "../../delegationCredential/server";
type CredentialCreateInput = {
type: string;
@@ -14,7 +14,7 @@ type CredentialCreateInput = {
export class CredentialRepository {
static async create(data: CredentialCreateInput) {
const credential = await prisma.credential.create({ data: { ...data } });
return buildNonDwdCredential(credential);
return buildNonDelegationCredential(credential);
}
static async findByAppIdAndUserId({ appId, userId }: { appId: string; userId: number }) {
const credential = await prisma.credential.findFirst({
@@ -23,7 +23,7 @@ export class CredentialRepository {
userId,
},
});
return buildNonDwdCredential(credential);
return buildNonDelegationCredential(credential);
}
/**
@@ -31,7 +31,7 @@ export class CredentialRepository {
*/
static async findFirstByIdWithUser({ id }: { id: number }) {
const credential = await prisma.credential.findFirst({ where: { id }, select: safeCredentialSelect });
return buildNonDwdCredential(credential);
return buildNonDelegationCredential(credential);
}
/**
@@ -42,7 +42,7 @@ export class CredentialRepository {
where: { id },
select: { ...safeCredentialSelect, key: true },
});
return buildNonDwdCredential(credential);
return buildNonDelegationCredential(credential);
}
static async findFirstByAppIdAndUserId({ appId, userId }: { appId: string; userId: number }) {
@@ -56,7 +56,7 @@ export class CredentialRepository {
static async findFirstByUserIdAndType({ userId, type }: { userId: number; type: string }) {
const credential = await prisma.credential.findFirst({ where: { userId, type } });
return buildNonDwdCredential(credential);
return buildNonDelegationCredential(credential);
}
static async deleteById({ id }: { id: number }) {
@@ -73,6 +73,6 @@ export class CredentialRepository {
return dbCredential;
}
return buildNonDwdCredential(dbCredential);
return buildNonDelegationCredential(dbCredential);
}
}
@@ -13,8 +13,8 @@ import { prisma } from "@calcom/prisma";
import { OrganizationRepository } from "./organization";
export type { ServiceAccountKey };
const repositoryLogger = logger.getSubLogger({ prefix: ["DomainWideDelegationRepository"] });
const domainWideDelegationSafeSelect = {
const repositoryLogger = logger.getSubLogger({ prefix: ["DelegationCredentialRepository"] });
const delegationCredentialSafeSelect = {
id: true,
enabled: true,
domain: true,
@@ -29,12 +29,12 @@ const domainWideDelegationSafeSelect = {
},
};
const domainWideDelegationSelectIncludesServiceAccountKey = {
...domainWideDelegationSafeSelect,
const delegationCredentialSelectIncludesServiceAccountKey = {
...delegationCredentialSafeSelect,
serviceAccountKey: true,
};
export class DomainWideDelegationRepository {
export class DelegationCredentialRepository {
private static encryptServiceAccountKey(serviceAccountKey: ServiceAccountKey): EncryptedServiceAccountKey {
return encryptServiceAccountKey(serviceAccountKey);
}
@@ -44,12 +44,12 @@ export class DomainWideDelegationRepository {
}
private static withParsedServiceAccountKey<T extends { serviceAccountKey: Prisma.JsonValue } | null>(
domainWideDelegation: T
delegationCredential: T
) {
if (!domainWideDelegation) {
if (!delegationCredential) {
return null;
}
const { serviceAccountKey, ...rest } = domainWideDelegation;
const { serviceAccountKey, ...rest } = delegationCredential;
// Decrypt the service account key if it exists
const decryptedKey = this.decryptServiceAccountKey(serviceAccountKey);
@@ -69,7 +69,7 @@ export class DomainWideDelegationRepository {
serviceAccountKey: ServiceAccountKey;
}) {
const encryptedKey = this.encryptServiceAccountKey(data.serviceAccountKey);
return await prisma.domainWideDelegation.create({
return await prisma.delegationCredential.create({
data: {
workspacePlatform: {
connect: {
@@ -85,14 +85,14 @@ export class DomainWideDelegationRepository {
},
serviceAccountKey: encryptedKey,
},
select: domainWideDelegationSafeSelect,
select: delegationCredentialSafeSelect,
});
}
static async findById({ id }: { id: string }) {
return await prisma.domainWideDelegation.findUnique({
return await prisma.delegationCredential.findUnique({
where: { id },
select: domainWideDelegationSafeSelect,
select: delegationCredentialSafeSelect,
});
}
@@ -103,20 +103,20 @@ export class DomainWideDelegationRepository {
organizationId: number;
domain: string;
}) {
const dwd = await prisma.domainWideDelegation.findUnique({
const delegationCredential = await prisma.delegationCredential.findUnique({
where: { organizationId_domain: { organizationId, domain } },
select: domainWideDelegationSelectIncludesServiceAccountKey,
select: delegationCredentialSelectIncludesServiceAccountKey,
});
return DomainWideDelegationRepository.withParsedServiceAccountKey(dwd);
return DelegationCredentialRepository.withParsedServiceAccountKey(delegationCredential);
}
static async findByIdIncludeSensitiveServiceAccountKey({ id }: { id: string }) {
const domainWideDelegation = await prisma.domainWideDelegation.findUnique({
const delegationCredential = await prisma.delegationCredential.findUnique({
where: { id },
select: domainWideDelegationSelectIncludesServiceAccountKey,
select: delegationCredentialSelectIncludesServiceAccountKey,
});
if (!domainWideDelegation) return null;
return DomainWideDelegationRepository.withParsedServiceAccountKey(domainWideDelegation);
if (!delegationCredential) return null;
return DelegationCredentialRepository.withParsedServiceAccountKey(delegationCredential);
}
static async findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({ email }: { email: string }) {
@@ -131,23 +131,23 @@ export class DomainWideDelegationRepository {
}
const emailDomain = email.split("@")[1];
const domainWideDelegation = await prisma.domainWideDelegation.findUnique({
const delegationCredential = await prisma.delegationCredential.findUnique({
where: {
organizationId_domain: {
organizationId: organization.id,
domain: emailDomain,
},
},
select: domainWideDelegationSelectIncludesServiceAccountKey,
select: delegationCredentialSelectIncludesServiceAccountKey,
});
return DomainWideDelegationRepository.withParsedServiceAccountKey(domainWideDelegation);
return DelegationCredentialRepository.withParsedServiceAccountKey(delegationCredential);
}
static async findAllByDomain({ domain }: { domain: string }) {
return await prisma.domainWideDelegation.findMany({
return await prisma.delegationCredential.findMany({
where: { domain },
select: domainWideDelegationSafeSelect,
select: delegationCredentialSafeSelect,
});
}
@@ -164,7 +164,7 @@ export class DomainWideDelegationRepository {
}>;
}) {
const { workspacePlatformId, organizationId, ...rest } = data;
return await prisma.domainWideDelegation.update({
return await prisma.delegationCredential.update({
where: { id },
data: {
...(workspacePlatformId && {
@@ -183,21 +183,21 @@ export class DomainWideDelegationRepository {
}),
...rest,
},
select: domainWideDelegationSafeSelect,
select: delegationCredentialSafeSelect,
});
}
static async deleteById({ id }: { id: string }) {
return await prisma.domainWideDelegation.delete({
return await prisma.delegationCredential.delete({
where: { id },
});
}
static async findByOrgIdIncludeSensitiveServiceAccountKey({ organizationId }: { organizationId: number }) {
return await prisma.domainWideDelegation.findMany({
return await prisma.delegationCredential.findMany({
where: { organizationId },
select: {
...domainWideDelegationSelectIncludesServiceAccountKey,
...delegationCredentialSelectIncludesServiceAccountKey,
workspacePlatform: {
select: {
id: true,
@@ -44,24 +44,24 @@ export class DestinationCalendarRepository {
externalId?: string;
credentialId?: number | null;
primaryEmail?: string | null;
domainWideDelegationCredentialId?: string | null;
delegationCredentialId?: string | null;
};
create: {
integration: string;
externalId: string;
credentialId: number | null;
primaryEmail?: string | null;
domainWideDelegationCredentialId?: string | null;
delegationCredentialId?: string | null;
};
}) {
const credentialPayloadForUpdate = buildCredentialPayloadForPrisma({
credentialId: update.credentialId,
domainWideDelegationCredentialId: update.domainWideDelegationCredentialId,
delegationCredentialId: update.delegationCredentialId,
});
const credentialPayloadForCreate = buildCredentialPayloadForPrisma({
credentialId: create.credentialId,
domainWideDelegationCredentialId: create.domainWideDelegationCredentialId,
delegationCredentialId: create.delegationCredentialId,
});
return await prisma.destinationCalendar.upsert({
@@ -290,13 +290,13 @@ describe("SelectedCalendarRepository", () => {
});
});
describe("Domain Wide Delegation", () => {
it("should create a selected calendar with domainWideDelegationCredentialId", async () => {
describe("Delegation Credential", () => {
it("should create a selected calendar with delegationCredentialId", async () => {
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
domainWideDelegationCredentialId: "dwd-123",
delegationCredentialId: "delegationCredential-123",
};
const result = await SelectedCalendarRepository.create(data);
@@ -306,7 +306,7 @@ describe("SelectedCalendarRepository", () => {
describe("upsert", () => {
describe("updation", () => {
it("should update existing record with domainWideDelegationCredentialId if credentialId is -1", async () => {
it("should update existing record with delegationCredentialId if credentialId is -1", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
@@ -322,17 +322,17 @@ describe("SelectedCalendarRepository", () => {
integration: "google_calendar",
externalId: "[email protected]",
credentialId: -1,
domainWideDelegationCredentialId: "dwd-123",
delegationCredentialId: "delegationCredential-123",
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).not.toBe(null);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(null);
expect(result.domainWideDelegationCredentialId).toBe(data.domainWideDelegationCredentialId);
expect(result.delegationCredentialId).toBe(data.delegationCredentialId);
});
it("should update existing record with credentialId if credentialId is valid(>0) even if domainWideDelegationCredentialId is set", async () => {
it("should update existing record with credentialId if credentialId is valid(>0) even if delegationCredentialId is set", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
@@ -348,19 +348,19 @@ describe("SelectedCalendarRepository", () => {
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 2,
domainWideDelegationCredentialId: "dwd-123",
delegationCredentialId: "delegationCredential-123",
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).not.toBe(null);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(data.credentialId);
expect(result.domainWideDelegationCredentialId).toBeNull();
expect(result.delegationCredentialId).toBeNull();
});
});
describe("creation", () => {
it("should create a new record with domainWideDelegationCredentialId if credentialId is -1", async () => {
it("should create a new record with delegationCredentialId if credentialId is -1", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
@@ -376,7 +376,7 @@ describe("SelectedCalendarRepository", () => {
integration: "google_calendar",
externalId: "[email protected]",
credentialId: -1,
domainWideDelegationCredentialId: "dwd-123",
delegationCredentialId: "delegationCredential-123",
};
// It will create a new record because of unique constraint violation
@@ -384,17 +384,17 @@ describe("SelectedCalendarRepository", () => {
expect(result.id).not.toBe(null);
expect(result.id).not.toBe(existingCalendar.id);
expect(result.credentialId).toBe(null);
expect(result.domainWideDelegationCredentialId).toBe(data.domainWideDelegationCredentialId);
expect(result.delegationCredentialId).toBe(data.delegationCredentialId);
});
});
it("shouldnt update existing domainWideDelegationCredentialId if upsert data doesn't have it", async () => {
it("shouldnt update existing delegationCredentialId if upsert data doesn't have it", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
eventTypeId: null,
domainWideDelegationCredentialId: "dwd-123",
delegationCredentialId: "delegationCredential-123",
credentialId: 1,
};
@@ -410,16 +410,16 @@ describe("SelectedCalendarRepository", () => {
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(existingCalendar.credentialId);
expect(result.domainWideDelegationCredentialId).toBe(null);
expect(result.delegationCredentialId).toBe(null);
});
it("shouldnt update domainWideDelegationCredentialId if it is undefined", async () => {
it("shouldnt update delegationCredentialId if it is undefined", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
eventTypeId: null,
domainWideDelegationCredentialId: "dwd-123",
delegationCredentialId: "delegationCredential-123",
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
@@ -433,9 +433,7 @@ describe("SelectedCalendarRepository", () => {
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(existingCalendar.credentialId);
expect(result.domainWideDelegationCredentialId).toBe(
existingCalendar.domainWideDelegationCredentialId
);
expect(result.delegationCredentialId).toBe(existingCalendar.delegationCredentialId);
});
});
});
@@ -82,7 +82,7 @@ export class SelectedCalendarRepository {
// So, this unique constraint can't be used in upsert. Prisma doesn't allow that, So, we do create and update separately
const credentialPayload = buildCredentialPayloadForPrisma({
credentialId: data.credentialId,
domainWideDelegationCredentialId: data.domainWideDelegationCredentialId,
delegationCredentialId: data.delegationCredentialId,
});
const newData = {
+2 -2
View File
@@ -12,7 +12,7 @@ import { userMetadata } from "@calcom/prisma/zod-utils";
import type { UpId, UserProfile } from "@calcom/types/UserProfile";
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "../../availability";
import { buildNonDwdCredentials } from "../../domainWideDelegation/clientAndServer";
import { buildNonDelegationCredentials } from "../../delegationCredential/clientAndServer";
import { withSelectedCalendars } from "../withSelectedCalendars";
import { ProfileRepository } from "./profile";
import { getParsedTeam } from "./teamUtils";
@@ -786,7 +786,7 @@ export class UserRepository {
const { credentials, ...userWithSelectedCalendars } = withSelectedCalendars(user);
return {
...userWithSelectedCalendars,
credentials: buildNonDwdCredentials(credentials),
credentials: buildNonDelegationCredentials(credentials),
};
}
@@ -14,11 +14,7 @@ import { getPlaceholderContent } from "../lib/getPlaceholderContent";
export type DestinationCalendarProps = {
connectedCalendars: ConnectedDestinationCalendars["connectedCalendars"];
destinationCalendar: ConnectedDestinationCalendars["destinationCalendar"];
onChange: (value: {
externalId: string;
integration: string;
domainWideDelegationCredentialId?: string;
}) => void;
onChange: (value: { externalId: string; integration: string; delegationCredentialId?: string }) => void;
isPending?: boolean;
hidePlaceholder?: boolean;
value: string | undefined;
@@ -41,7 +37,7 @@ export const DestinationCalendarSelector = ({
value: string;
label: string;
subtitle: string;
domainWideDelegationCredentialId?: string;
delegationCredentialId?: string;
} | null>(null);
useEffect(() => {
@@ -82,7 +78,7 @@ export const DestinationCalendarSelector = ({
selectedCalendar?.primary?.name
})`,
value: `${cal.integration}:${cal.externalId}`,
domainWideDelegationCredentialId: cal.domainWideDelegationCredentialId || undefined,
delegationCredentialId: cal.delegationCredentialId || undefined,
})),
})) ?? []
);
@@ -141,7 +137,7 @@ export const DestinationCalendarSelector = ({
onChange({
integration,
externalId,
domainWideDelegationCredentialId: newValue.domainWideDelegationCredentialId,
delegationCredentialId: newValue.delegationCredentialId,
});
}}
isLoading={isPending}
@@ -38,11 +38,11 @@ export const DestinationCalendarSettingsPlatformWrapper = ({
value={calendars.data.destinationCalendar.externalId}
hidePlaceholder
hideAdvancedText
onChange={async ({ externalId, integration, domainWideDelegationCredentialId }) => {
onChange={async ({ externalId, integration, delegationCredentialId }) => {
await updateDestinationCalendars({
integration,
externalId,
domainWideDelegationCredentialId,
delegationCredentialId,
});
}}
isPending={isUpdatingCalendar}
@@ -35,15 +35,15 @@ export const useAddSelectedCalendar = (
credentialId: number;
integration: string;
externalId: string;
domainWideDelegationCredentialId: string | null;
delegationCredentialId: string | null;
}
>({
mutationFn: (data) => {
const { domainWideDelegationCredentialId, ...rest } = data;
const { delegationCredentialId, ...rest } = data;
return http
.post(`/selected-calendars`, {
...rest,
...(domainWideDelegationCredentialId ? { domainWideDelegationCredentialId } : {}),
...(delegationCredentialId ? { delegationCredentialId } : {}),
})
.then((res) => {
return res.data;
@@ -35,21 +35,17 @@ export const useRemoveSelectedCalendar = (
credentialId: number;
integration: string;
externalId: string;
domainWideDelegationCredentialId: string | null;
delegationCredentialId: string | null;
}
>({
mutationFn: (data) => {
const { credentialId, externalId, integration, domainWideDelegationCredentialId } = data;
const { credentialId, externalId, integration, delegationCredentialId } = data;
return http
.delete(
`/selected-calendars?credentialId=${credentialId}&integration=${integration}&externalId=${encodeURIComponent(
externalId
)}${
domainWideDelegationCredentialId
? `&domainWideDelegationCredentialId=${domainWideDelegationCredentialId}`
: ""
}`
)}${delegationCredentialId ? `&delegationCredentialId=${delegationCredentialId}` : ""}`
)
.then((res) => {
return res.data;
@@ -30,11 +30,11 @@ export const useUpdateDestinationCalendars = (
integration: string;
externalId: string;
credentialId: number | null;
domainWideDelegationCredentialId?: string;
delegationCredentialId?: string;
};
}>,
unknown,
{ integration: string; externalId: string; domainWideDelegationCredentialId?: string }
{ integration: string; externalId: string; delegationCredentialId?: string }
>({
mutationFn: (data) => {
return http.put(`/destination-calendars`, data).then((res) => {
@@ -83,7 +83,7 @@ export const SelectedCalendarsSettingsPlatformWrapper = ({
className="border-subtle mt-4 rounded-lg border"
actions={
<div className="flex w-32 justify-end">
{allowDelete && !connectedCalendar.domainWideDelegationCredentialId && (
{allowDelete && !connectedCalendar.delegationCredentialId && (
<PlatformDisconnectIntegration
credentialId={connectedCalendar.credentialId}
trashIcon
@@ -107,9 +107,7 @@ export const SelectedCalendarsSettingsPlatformWrapper = ({
isChecked={cal.isSelected}
destination={cal.externalId === destinationCalendarId}
credentialId={cal.credentialId}
domainWideDelegationCredentialId={
connectedCalendar.domainWideDelegationCredentialId
}
delegationCredentialId={connectedCalendar.delegationCredentialId}
eventTypeId={null}
/>
);
@@ -127,7 +125,7 @@ export const SelectedCalendarsSettingsPlatformWrapper = ({
message={<span>{connectedCalendar.error?.message || t("calendar_error")}</span>}
iconClassName="h-10 w-10 ml-2 mr-1 mt-0.5"
actions={
!Boolean(connectedCalendar.domainWideDelegationCredentialId) && (
!Boolean(connectedCalendar.delegationCredentialId) && (
<div className="flex w-32 justify-end">
<PlatformDisconnectIntegration
credentialId={connectedCalendar.credentialId}
@@ -222,7 +220,7 @@ const PlatformDisconnectIntegration = (props: {
};
const PlatformCalendarSwitch = (props: ICalendarSwitchProps) => {
const { isChecked, title, credentialId, type, externalId, domainWideDelegationCredentialId } = props;
const { isChecked, title, credentialId, type, externalId, delegationCredentialId } = props;
const [checkedInternal, setCheckedInternal] = useState(isChecked);
const { toast } = useToast();
@@ -255,13 +253,13 @@ const PlatformCalendarSwitch = (props: ICalendarSwitchProps) => {
externalId: string;
}) => {
if (isOn) {
await addSelectedCalendar({ credentialId, integration, externalId, domainWideDelegationCredentialId });
await addSelectedCalendar({ credentialId, integration, externalId, delegationCredentialId });
} else {
await removeSelectedCalendar({
credentialId,
integration,
externalId,
domainWideDelegationCredentialId,
delegationCredentialId,
});
}
};
@@ -65,8 +65,8 @@ const ConnectedCalendarList = ({
description={connectedCalendar.primary?.email ?? connectedCalendar.integration.description}
className="border-subtle mt-4 rounded-lg border"
actions={
// DWD credential can't be disconnected
!connectedCalendar.domainWideDelegationCredentialId &&
// Delegation credential can't be disconnected
!connectedCalendar.delegationCredentialId &&
!disableConnectionModification && (
<div className="flex w-32 justify-end">
<DisconnectIntegration
@@ -95,9 +95,7 @@ const ConnectedCalendarList = ({
destination={cal.externalId === destinationCalendarId}
credentialId={cal.credentialId}
eventTypeId={shouldUseEventTypeScope ? eventTypeId : null}
domainWideDelegationCredentialId={
connectedCalendar.domainWideDelegationCredentialId
}
delegationCredentialId={connectedCalendar.delegationCredentialId}
/>
))}
</ul>
@@ -122,8 +120,8 @@ const ConnectedCalendarList = ({
}
iconClassName="h-10 w-10 ml-2 mr-1 mt-0.5"
actions={
// DWD credential can't be disconnected
!connectedCalendar.domainWideDelegationCredentialId && (
// Delegation credential can't be disconnected
!connectedCalendar.delegationCredentialId && (
<div className="flex w-32 justify-end">
<DisconnectIntegration
credentialId={connectedCalendar.credentialId}
+24 -24
View File
@@ -32,19 +32,19 @@ import getEnabledAppsFromCredentials from "@calcom/lib/apps/getEnabledAppsFromCr
import getAllUserBookings from "@calcom/lib/bookings/getAllUserBookings";
import { symmetricEncrypt, symmetricDecrypt } from "@calcom/lib/crypto";
import {
getFirstDwdConferencingCredentialAppLocation,
getFirstDwdConferencingCredential,
getDwdOrRegularCredential,
getDwdOrFindRegularCredential,
enrichUserWithDwdConferencingCredentialsWithoutOrgId,
enrichUserWithDwdCredentialsWithoutOrgId,
enrichHostsWithDwdCredentials,
enrichUsersWithDwdCredentials,
getFirstDelegationConferencingCredentialAppLocation,
getFirstDelegationConferencingCredential,
getDelegationCredentialOrRegularCredential,
getDelegationCredentialOrFindRegularCredential,
enrichUserWithDelegationConferencingCredentialsWithoutOrgId,
enrichUserWithDelegationCredentialsWithoutOrgId,
enrichHostsWithDelegationCredentials,
enrichUsersWithDelegationCredentials,
buildAllCredentials,
getAllDwdCredentialsForUserByAppSlug,
getAllDwdCredentialsForUserByAppType,
getAllDelegationCredentialsForUserByAppSlug,
getAllDelegationCredentialsForUserByAppType,
checkIfSuccessfullyConfiguredInWorkspace,
} from "@calcom/lib/domainWideDelegation/server";
} from "@calcom/lib/delegationCredential/server";
import getBulkEventTypes from "@calcom/lib/event-types/getBulkEventTypes";
import { getRoutedUrl } from "@calcom/lib/server/getRoutedUrl";
import { getTeamMemberEmailForResponseOrContactUsingUrlQuery } from "@calcom/lib/server/getTeamMemberEmailFromCrm";
@@ -54,7 +54,7 @@ import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/crede
import { paymentDataSelect } from "@calcom/prisma/selects/payment";
import type { TeamQuery } from "@calcom/trpc/server/routers/loggedInViewer/integrations.handler";
import { updateHandler as updateScheduleHandler } from "@calcom/trpc/server/routers/viewer/availability/schedule/update.handler";
import addDwd from "@calcom/trpc/server/routers/viewer/domainWideDelegation/add.handler";
import addDelegationCredential from "@calcom/trpc/server/routers/viewer/delegationCredential/add.handler";
import { getAvailableSlots } from "@calcom/trpc/server/routers/viewer/slots/util";
import {
createNewUsersConnectToOrgIfExists,
@@ -68,17 +68,17 @@ export { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
export { getApps };
export {
getFirstDwdConferencingCredentialAppLocation,
getFirstDwdConferencingCredential,
getDwdOrRegularCredential,
getDwdOrFindRegularCredential,
enrichUserWithDwdConferencingCredentialsWithoutOrgId,
enrichUserWithDwdCredentialsWithoutOrgId,
enrichHostsWithDwdCredentials,
enrichUsersWithDwdCredentials,
getFirstDelegationConferencingCredentialAppLocation,
getFirstDelegationConferencingCredential,
getDelegationCredentialOrRegularCredential,
getDelegationCredentialOrFindRegularCredential,
enrichUserWithDelegationConferencingCredentialsWithoutOrgId,
enrichUserWithDelegationCredentialsWithoutOrgId,
enrichHostsWithDelegationCredentials,
enrichUsersWithDelegationCredentials,
buildAllCredentials,
getAllDwdCredentialsForUserByAppSlug,
getAllDwdCredentialsForUserByAppType,
getAllDelegationCredentialsForUserByAppSlug,
getAllDelegationCredentialsForUserByAppType,
checkIfSuccessfullyConfiguredInWorkspace,
};
@@ -276,9 +276,9 @@ export { getRoutedUrl };
export { getTeamMemberEmailForResponseOrContactUsingUrlQuery };
export { addDwd };
export { addDelegationCredential };
export { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
export { toggleDwdEnabled } from "@calcom/trpc/server/routers/viewer/domainWideDelegation/toggleEnabled.handler";
export { toggleDelegationCredentialEnabled } from "@calcom/trpc/server/routers/viewer/delegationCredential/toggleEnabled.handler";
export { encryptServiceAccountKey } from "@calcom/lib/server/serviceAccountKey";
export { createHandler as createApiKeyHandler } from "@calcom/trpc/server/routers/viewer/apiKeys/create.handler";
@@ -0,0 +1,68 @@
/*
Warnings:
- You are about to drop the column `domainWideDelegationCredentialId` on the `BookingReference` table. All the data in the column will be lost.
- You are about to drop the column `domainWideDelegationCredentialId` on the `DestinationCalendar` table. All the data in the column will be lost.
- You are about to drop the column `domainWideDelegationCredentialId` on the `SelectedCalendar` table. All the data in the column will be lost.
- You are about to drop the `DomainWideDelegation` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE "BookingReference" DROP CONSTRAINT "BookingReference_domainWideDelegationCredentialId_fkey";
-- DropForeignKey
ALTER TABLE "DestinationCalendar" DROP CONSTRAINT "DestinationCalendar_domainWideDelegationCredentialId_fkey";
-- DropForeignKey
ALTER TABLE "DomainWideDelegation" DROP CONSTRAINT "DomainWideDelegation_organizationId_fkey";
-- DropForeignKey
ALTER TABLE "DomainWideDelegation" DROP CONSTRAINT "DomainWideDelegation_workspacePlatformId_fkey";
-- DropForeignKey
ALTER TABLE "SelectedCalendar" DROP CONSTRAINT "SelectedCalendar_domainWideDelegationCredentialId_fkey";
-- AlterTable
ALTER TABLE "BookingReference" DROP COLUMN "domainWideDelegationCredentialId",
ADD COLUMN "delegationCredentialId" TEXT;
-- AlterTable
ALTER TABLE "DestinationCalendar" DROP COLUMN "domainWideDelegationCredentialId",
ADD COLUMN "delegationCredentialId" TEXT;
-- AlterTable
ALTER TABLE "SelectedCalendar" DROP COLUMN "domainWideDelegationCredentialId",
ADD COLUMN "delegationCredentialId" TEXT;
-- CreateTable
CREATE TABLE "DelegationCredential" (
"id" TEXT NOT NULL,
"workspacePlatformId" INTEGER NOT NULL,
"serviceAccountKey" JSONB NOT NULL,
"enabled" BOOLEAN NOT NULL DEFAULT false,
"organizationId" INTEGER NOT NULL,
"domain" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "DelegationCredential_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "DelegationCredential_organizationId_domain_key" ON "DelegationCredential"("organizationId", "domain");
-- AddForeignKey
ALTER TABLE "DestinationCalendar" ADD CONSTRAINT "DestinationCalendar_delegationCredentialId_fkey" FOREIGN KEY ("delegationCredentialId") REFERENCES "DelegationCredential"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BookingReference" ADD CONSTRAINT "BookingReference_delegationCredentialId_fkey" FOREIGN KEY ("delegationCredentialId") REFERENCES "DelegationCredential"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "SelectedCalendar" ADD CONSTRAINT "SelectedCalendar_delegationCredentialId_fkey" FOREIGN KEY ("delegationCredentialId") REFERENCES "DelegationCredential"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "DelegationCredential" ADD CONSTRAINT "DelegationCredential_workspacePlatformId_fkey" FOREIGN KEY ("workspacePlatformId") REFERENCES "WorkspacePlatform"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "DelegationCredential" ADD CONSTRAINT "DelegationCredential_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+36 -36
View File
@@ -225,20 +225,20 @@ enum IdentityProvider {
}
model DestinationCalendar {
id Int @id @default(autoincrement())
integration String
externalId String
id Int @id @default(autoincrement())
integration String
externalId String
/// @zod.custom(imports.emailSchema)
primaryEmail String?
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int? @unique
booking Booking[]
eventType EventType? @relation(fields: [eventTypeId], references: [id], onDelete: Cascade)
eventTypeId Int? @unique
credentialId Int?
credential Credential? @relation(fields: [credentialId], references: [id], onDelete: Cascade)
domainWideDelegation DomainWideDelegation? @relation(fields: [domainWideDelegationCredentialId], references: [id], onDelete: Cascade)
domainWideDelegationCredentialId String?
primaryEmail String?
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int? @unique
booking Booking[]
eventType EventType? @relation(fields: [eventTypeId], references: [id], onDelete: Cascade)
eventTypeId Int? @unique
credentialId Int?
credential Credential? @relation(fields: [credentialId], references: [id], onDelete: Cascade)
delegationCredential DelegationCredential? @relation(fields: [delegationCredentialId], references: [id], onDelete: Cascade)
delegationCredentialId String?
@@index([userId])
@@index([eventTypeId])
@@ -480,7 +480,7 @@ model Team {
attributes Attribute[]
smsLockReviewedByAdmin Boolean @default(false)
// Available for Organization only
domainWideDelegations DomainWideDelegation[]
delegationCredentials DelegationCredential[]
features TeamFeatures[]
/// @zod.custom(imports.intervalLimitsType)
@@ -591,10 +591,10 @@ model BookingReference {
externalCalendarId String?
deleted Boolean?
credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)
credentialId Int?
domainWideDelegation DomainWideDelegation? @relation(fields: [domainWideDelegationCredentialId], references: [id], onDelete: SetNull)
domainWideDelegationCredentialId String?
credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)
credentialId Int?
delegationCredential DelegationCredential? @relation(fields: [delegationCredentialId], references: [id], onDelete: SetNull)
delegationCredentialId String?
@@index([bookingId])
@@index([type])
@@ -731,22 +731,22 @@ model Availability {
}
model SelectedCalendar {
id String @id @default(uuid())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int
integration String
externalId String
credential Credential? @relation(fields: [credentialId], references: [id], onDelete: Cascade)
credentialId Int?
id String @id @default(uuid())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int
integration String
externalId String
credential Credential? @relation(fields: [credentialId], references: [id], onDelete: Cascade)
credentialId Int?
// Used to identify a watched calendar channel in Google Calendar
googleChannelId String?
googleChannelKind String?
googleChannelResourceId String?
googleChannelResourceUri String?
googleChannelExpiration String?
domainWideDelegationCredential DomainWideDelegation? @relation(fields: [domainWideDelegationCredentialId], references: [id], onDelete: Cascade)
domainWideDelegationCredentialId String?
error String?
googleChannelId String?
googleChannelKind String?
googleChannelResourceId String?
googleChannelResourceUri String?
googleChannelExpiration String?
delegationCredential DelegationCredential? @relation(fields: [delegationCredentialId], references: [id], onDelete: Cascade)
delegationCredentialId String?
error String?
eventTypeId Int?
eventType EventType? @relation(fields: [eventTypeId], references: [id])
@@ -1767,7 +1767,7 @@ enum EventTypeAutoTranslatedField {
TITLE
}
model DomainWideDelegation {
model DelegationCredential {
id String @id @default(uuid())
workspacePlatform WorkspacePlatform @relation(fields: [workspacePlatformId], references: [id], onDelete: Cascade)
workspacePlatformId Int
@@ -1789,7 +1789,7 @@ model DomainWideDelegation {
@@unique([organizationId, domain])
}
// It is for domain-wide delegation
// It is for delegation credential
model WorkspacePlatform {
id Int @id @default(autoincrement())
/// @zod.min(1)
@@ -1802,7 +1802,7 @@ model WorkspacePlatform {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
enabled Boolean @default(false)
domainWideDelegations DomainWideDelegation[]
delegationCredentials DelegationCredential[]
@@unique([slug])
}
+2 -2
View File
@@ -30,7 +30,7 @@ export const ENDPOINTS = [
"googleWorkspace",
"oAuth",
"attributes",
"domainWideDelegation",
"delegationCredential",
"routingForms",
"domainWideDelegation",
"delegationCredential",
] as const;
@@ -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,
}),
+2 -2
View File
@@ -168,9 +168,9 @@ export interface App {
/** Specifies if the App uses an OAuth flow */
isOAuth?: boolean;
/**
* Specifies if the App supports domain-wide delegation
* Specifies if the App supports delegation credential
*/
domainWideDelegation?: {
delegationCredential?: {
workspacePlatformSlug: string;
};
}
+2 -2
View File
@@ -218,7 +218,7 @@ export interface CalendarEvent {
platformCancelUrl?: string | null;
platformBookingUrl?: string | null;
oneTimePassword?: string | null;
domainWideDelegationCredentialId?: string | null;
delegationCredentialId?: string | null;
}
export interface EntryPoint {
@@ -287,7 +287,7 @@ export interface Calendar {
listCalendars(event?: CalendarEvent): Promise<IntegrationCalendar[]>;
testDomainWideDelegationSetup?(): Promise<boolean>;
testDelegationCredentialSetup?(): Promise<boolean>;
watchCalendar?(options: {
calendarId: string;
+1 -1
View File
@@ -10,7 +10,7 @@ export interface PartialReference {
meetingUrl?: string | null;
externalCalendarId?: string | null;
credentialId?: number | null;
domainWideDelegationCredentialId?: string | null;
delegationCredentialId?: string | null;
}
export interface EventResult<T> {