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

* Add endpoints for testing the flow

* Add MVP

* new route

* Fixes

* Fixes

* Remove enable toggle support from domainWideDelegation

* Fixes

* Revert "Remove enable toggle support from domainWideDelegation"

This reverts commit c29e729206cd1fa063f9c9ce0cf148ef1577d60b.

* Revert yarn.lock

* More fixes

* Fix new workspace platform add

* refactor: improvements

* refactor: bug fixes and improvements

* fix: type errors

* fix: conflicts

* chore: update test

* fix: logic

* chore: improvements

* fix: toglle

* fix: bugs

* fix: type err

* chore: check number type

* fix: after conflicts

* chore: fix type err

* fix: type errors and tests

* fix: tets

* test

* chore: remove unused

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

* fix: add property

* fix: type err

* fix: re assingment bug

* fix: use getAllCredentials

* chore: fix import

* fix: installed count

* fix: pass event type

* fix: import

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

* Review fixes

* fix: destination calendar bug

---------

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

* refactor: use repository

* chore: remove duplicate

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

* Reuse buildCredentialPayloadForCalendar

* fixes

---------

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

* fix ts error

* Fix getSchedule not using dwd credentials (#17995)

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

* Remove fn rename to reduce number of files changed

* chore: check feature globally

* test: add unit tests

* chore: move function

* test: add booking test

* wip

* Remove domain-wide-delegation team feature flag

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

* Fix tests and their ts errors

* Fix more tests

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

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

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

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

* Show DWD credential calendars at the top

* Fixed tests

* Calendar Cache DWD support

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

* Self Review: shorten names

* Self ReviewL Dead code removal

* Revert "Calendar Cache DWD support"

This reverts commit 009f236470fa21eba5986117d4f6e4d4c5e38c34.

* Some misc fixes

* fixes

* Performance improvememt in slots loading and booking

* More cases for handling dwd credentials

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

* Fix tests

* Fix installed/conferencing not showing gogole meet

* Shorten name

* Fix ApI v2 tests

* Add some more tests

* add getSchedule tests

* Improve tests

* Make Google Meet default when DWD for google is enabled

* Enable feature flagging for DWD

* chore: bump libraries

* Encrypt serviceaccount private key

* Fix ts errors

* bump platform libraries

* org add dwd

* org add dwd

* bump platform libraries

* fix selected calendars

* fix remove selected dwd calendar

* remove oauthclient id aliad in authedCalendar

* remove oauthclient id aliad in authedCalendar

* refactor: OrganizationsDwdController

* chore: export toggleDwdEnabled from platform-libraries

* feat: v2 update (enable / disable) dwd

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

* wip: DestinationCalendar send domainWideDelegationCredentialId from frontend to api

* try fix set destination calendar api v2

* fixup! try fix set destination calendar api v2

* setting google meet as default location working for dwd

* bump platform libraries version

* allow office 365 workspace slug

* allow office 365 workspace slug

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

* fix: CreateDwdInput serviceAccountKey

* fix: CredentialForCalendarService type

* fix: check workspace slug

* feat: update serviceAccessKey of DWD

* testing

* fixup! testing

* fix: getAuthUtl bug

* fix: unit tests

* fix: type err and unit test

* fix: e2e test

* fix: credentials bug and failing unit tests

* Update CalendarService.ts

* chore: refactor office365 calendar service and add testDomainWideDelegationSetup

* fix: office365Calendar use correct clientId/Secret for DWD

* fix: office365Calendar dwd no need refresh token

* test: add unit test for outlook dwd and setup

* feat: added dwd support for office365 calendar

* feat: added dwd support for office365 video

* test: finish test for outlook dwd

* fix: create dialog bug

* chore: remove console logs

* fix: refreshToken bug

* bump version libraries

* refactor: fetch dwd credentials only in findQualifiedHosts

* fixup! refactor: fetch dwd credentials only in findQualifiedHosts

* fix: type err

* fix: type err

* fix: getUserDisplayName

* fix: unit test

* chore: bump platform lib

---------

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

No files matched your search

+12 -1
View File
@@ -1,6 +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 type { UserAdminTeams } from "@calcom/lib/server/repository/user";
import prisma, { safeAppSelect, safeCredentialSelect } from "@calcom/prisma";
import { userMetadata } from "@calcom/prisma/zod-utils";
@@ -79,15 +80,22 @@ export async function getAppRegistryWithCredentials(userId: number, userAdminTea
},
},
});
const user = await prisma.user.findUnique({
where: {
id: userId,
},
select: {
email: true,
id: true,
metadata: true,
},
});
const dwdCredentials = user
? await getAllDwdCredentialsForUser({ user: { id: userId, email: user.email } })
: [];
const usersDefaultApp = userMetadata.parse(user?.metadata)?.defaultConferencingApp?.appSlug;
const apps = [] as (App & {
credentials: Credential[];
@@ -95,6 +103,9 @@ 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 app = await getAppWithMetadata(dbapp);
if (!app) continue;
// Skip if app isn't installed
@@ -116,7 +127,7 @@ export async function getAppRegistryWithCredentials(userId: number, userAdminTea
apps.push({
...app,
categories: dbapp.categories,
credentials: dbapp.credentials,
credentials: allCredentials,
installed: true,
installCount: installCountPerApp[dbapp.slug] || 0,
isDefault: usersDefaultApp === dbapp.slug,
+4 -2
View File
@@ -1,6 +1,6 @@
import logger from "@calcom/lib/logger";
import type { Calendar, CalendarClass } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import appStore from "..";
@@ -23,7 +23,9 @@ const isCalendarService = (x: unknown): x is CalendarApp =>
!!x.lib &&
"CalendarService" in x.lib;
export const getCalendar = async (credential: CredentialPayload | null): Promise<Calendar | null> => {
export const getCalendar = async (
credential: CredentialForCalendarService | null
): Promise<Calendar | null> => {
if (!credential || !credential.key) return null;
let { type: calendarType } = credential;
if (calendarType?.endsWith("_other_calendar")) {
+7 -6
View File
@@ -1,21 +1,22 @@
import type { Prisma } from "@prisma/client";
import { HttpError } from "@calcom/lib/http-error";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import prisma from "@calcom/prisma";
import type { UserProfile } from "@calcom/types/UserProfile";
export async function checkInstalled(slug: string, userId: number) {
const alreadyInstalled = await prisma.credential.findFirst({
where: {
appId: slug,
userId: userId,
},
});
const alreadyInstalled = await CredentialRepository.findByAppIdAndUserId({ appId: slug, userId });
if (alreadyInstalled) {
throw new HttpError({ statusCode: 422, message: "Already installed" });
}
}
export async function isAppInstalled({ appId, userId }: { appId: string; userId: number }) {
const alreadyInstalled = await CredentialRepository.findByAppIdAndUserId({ appId, userId });
return !!alreadyInstalled;
}
type InstallationArgs = {
appType: string;
user: {
@@ -18,7 +18,7 @@ type CustomUseMutationOptions =
| Omit<UseMutationOptions<unknown, unknown, unknown, unknown>, "mutationKey" | "mutationFn" | "onSuccess">
| undefined;
type AddAppMutationData = { setupPending: boolean } | void;
type AddAppMutationData = { setupPending: boolean; message?: string } | void;
export type UseAddAppMutationOptions = CustomUseMutationOptions & {
onSuccess?: (data: AddAppMutationData) => void;
installGoogleVideo?: boolean;
@@ -94,18 +94,19 @@ function useAddAppMutation(_type: App["type"] | null, options?: UseAddAppMutatio
if (externalUrl) {
// TODO: For Omni installation to authenticate and come back to the page where installation was initiated, some changes need to be done in all apps' add callbacks
gotoUrl(json.url, json.newTab);
return { setupPending: !json.newTab };
return { setupPending: !json.newTab, message: json.message };
} else if (json.url) {
gotoUrl(json.url, json.newTab);
return {
setupPending:
json?.url?.endsWith("/setup") || json?.url?.includes("/apps/installation/event-types"),
message: json.message,
};
} else if (returnTo) {
gotoUrl(returnTo, false);
return { setupPending: true };
return { setupPending: true, message: json.message };
} else {
return { setupPending: false };
return { setupPending: false, message: json.message };
}
},
});
@@ -10,7 +10,7 @@ import {
recordingItemSchema,
} from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { PartialReference } from "@calcom/types/EventManager";
import type { VideoApiAdapter, VideoCallData } from "@calcom/types/VideoApiAdapter";
@@ -43,7 +43,7 @@ export interface DailyVideoCallData {
}
/** @deprecated use metadata on index file */
export const FAKE_DAILY_CREDENTIAL: CredentialPayload & { invalid: boolean } = {
export const FAKE_DAILY_CREDENTIAL: CredentialForCalendarService & { invalid: boolean } = {
id: 0,
type: "daily_video",
key: { apikey: process.env.DAILY_API_KEY },
@@ -52,6 +52,8 @@ export const FAKE_DAILY_CREDENTIAL: CredentialPayload & { invalid: boolean } = {
appId: "daily-video",
invalid: false,
teamId: null,
delegatedToId: null,
delegatedTo: null,
};
function postToDailyAPI(endpoint: string, body: Record<string, unknown>) {
@@ -19,6 +19,11 @@ export const metadata = {
email: "[email protected]",
dirName: "googlecalendar",
isOAuth: true,
domainWideDelegation: {
// 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",
},
} as AppMeta;
export default metadata;
+13 -1
View File
@@ -2,6 +2,7 @@ import { OAuth2Client } from "googleapis-common";
import type { NextApiRequest, NextApiResponse } from "next";
import { GOOGLE_CALENDAR_SCOPES, SCOPE_USERINFO_PROFILE, WEBAPP_URL_FOR_OAUTH } from "@calcom/lib/constants";
import { HttpError } from "@calcom/lib/http-error";
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
@@ -9,7 +10,18 @@ import { encodeOAuthState } from "../../_utils/oauth/encodeOAuthState";
import { getGoogleAppKeys } from "../lib/getGoogleAppKeys";
async function getHandler(req: NextApiRequest, res: NextApiResponse) {
// Get token from Google Calendar API
const loggedInUser = req.session?.user;
if (!loggedInUser) {
throw new HttpError({ statusCode: 401, message: "You must be logged in to do this" });
}
// Ideally this should never happen, as email is there in session user but typings aren't accurate it seems
// TODO: So, confirm and later fix the typings
if (!loggedInUser.email) {
throw new HttpError({ statusCode: 400, message: "Session user must have an email" });
}
const { client_id, client_secret } = await getGoogleAppKeys();
const redirect_uri = `${WEBAPP_URL_FOR_OAUTH}/api/integrations/googlecalendar/callback`;
const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uri);
@@ -81,6 +81,7 @@ async function getHandler(req: NextApiRequest, res: NextApiResponse) {
const gCalService = new GoogleCalendarService({
...gcalCredential,
user: null,
delegatedTo: null,
});
const calendar = new calendar_v3.Calendar({
@@ -1,5 +1,6 @@
import type { NextApiRequest } from "next";
import { buildNonDwdCredential } from "@calcom/lib/domainWideDelegation/server";
import { HttpError } from "@calcom/lib/http-error";
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
@@ -36,7 +37,8 @@ async function postHandler(req: NextApiRequest) {
message: `No credential found for selected calendar for googleChannelId: ${req.headers["x-goog-channel-id"]}`,
});
const { selectedCalendars } = credential;
const calendar = await getCalendar(credential);
const calendar = await getCalendar(buildNonDwdCredential(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
@@ -2,16 +2,39 @@ import prismock from "../../../../tests/libs/__mocks__/prisma";
import oAuthManagerMock, { defaultMockOAuthManager } from "../../tests/__mocks__/OAuthManager";
import { adminMock, calendarMock, setCredentialsMock } from "./__mocks__/googleapis";
import { expect, describe, test, beforeEach, vi } from "vitest";
import { JWT } from "googleapis-common";
import { expect, test, beforeEach, vi, describe } from "vitest";
import "vitest-fetch-mock";
import { CalendarCache } from "@calcom/features/calendar-cache/calendar-cache";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import type { CredentialForCalendarServiceWithEmail } from "@calcom/types/Credential";
import CalendarService from "./CalendarService";
import { getGoogleAppKeys } from "./getGoogleAppKeys";
vi.stubEnv("GOOGLE_WEBHOOK_TOKEN", "test-webhook-token");
interface MockJWT {
type: "jwt";
config: {
email: string;
key: string;
scopes: string[];
subject: string;
};
authorize: () => Promise<void>;
}
interface MockOAuth2Client {
type: "oauth2";
args: [string, string, string];
setCredentials: typeof setCredentialsMock;
}
let lastCreatedJWT: MockJWT | null = null;
let lastCreatedOAuth2Client: MockOAuth2Client | null = null;
vi.mock("@calcom/features/flags/server/utils", () => ({
getFeatureFlag: vi.fn().mockReturnValue(true),
}));
@@ -24,11 +47,28 @@ vi.mock("./getGoogleAppKeys", () => ({
}),
}));
vi.mock("googleapis-common", () => ({
OAuth2Client: vi.fn().mockImplementation(() => ({
setCredentials: setCredentialsMock,
})),
}));
vi.mock("googleapis-common", async () => {
const actual = await vi.importActual("googleapis-common");
return {
...actual,
OAuth2Client: vi.fn().mockImplementation((...args: [string, string, string]) => {
lastCreatedOAuth2Client = {
type: "oauth2",
args,
setCredentials: setCredentialsMock,
};
return lastCreatedOAuth2Client;
}),
JWT: vi.fn().mockImplementation((config: MockJWT["config"]) => {
lastCreatedJWT = {
type: "jwt",
config,
authorize: vi.fn().mockResolvedValue(undefined),
};
return lastCreatedJWT;
}),
};
});
vi.mock("@googleapis/admin", () => adminMock);
vi.mock("@googleapis/calendar", () => calendarMock);
@@ -563,10 +603,16 @@ test("`updateTokenObject` should update credential in DB as well as myGoogleAuth
expect(setCredentialsMock).toHaveBeenCalledWith(newTokenObject);
});
async function createCredentialInDb() {
const user = await prismock.user.create({
async function createCredentialInDb({
user = undefined,
delegatedTo = null,
}: {
user?: { email: string | null };
delegatedTo?: NonNullable<CredentialForCalendarServiceWithEmail["delegatedTo"]> | null;
} = {}): Promise<CredentialForCalendarServiceWithEmail> {
const defaultUser = await prismock.user.create({
data: {
email: "",
email: user?.email ?? "",
},
});
@@ -590,7 +636,7 @@ async function createCredentialInDb() {
...credential,
user: {
connect: {
id: user.id,
id: defaultUser.id,
},
},
app: {
@@ -604,5 +650,196 @@ async function createCredentialInDb() {
},
});
return credentialInDb;
return {
...credentialInDb,
delegatedTo: delegatedTo ?? null,
user: user ? { email: user.email ?? "" } : null,
} as CredentialForCalendarServiceWithEmail;
}
describe("GoogleCalendarService credential handling", () => {
beforeEach(() => {
lastCreatedJWT = null;
lastCreatedOAuth2Client = null;
});
const delegatedCredential = {
serviceAccountKey: {
client_email: "[email protected]",
client_id: "service-client-id",
private_key: "service-private-key",
},
} as const;
const createMockJWTInstance = ({
email = "[email protected]",
authorizeError,
}: {
email?: string;
authorizeError?: { response?: { data?: { error?: string } } } | Error;
}) => {
const mockJWTInstance = {
type: "jwt",
config: {
email: delegatedCredential.serviceAccountKey.client_email,
key: delegatedCredential.serviceAccountKey.private_key,
scopes: ["https://www.googleapis.com/auth/calendar"],
subject: email,
},
authorize: vi.fn().mockRejectedValue(authorizeError ?? new Error("Default error")),
createScoped: vi.fn(),
getRequestMetadataAsync: vi.fn(),
fetchIdToken: vi.fn(),
hasUserScopes: vi.fn(),
getAccessToken: vi.fn(),
getRefreshToken: vi.fn(),
getTokenInfo: vi.fn(),
refreshAccessToken: vi.fn(),
revokeCredentials: vi.fn(),
revokeToken: vi.fn(),
verifyIdToken: vi.fn(),
on: vi.fn(),
setCredentials: vi.fn(),
getCredentials: vi.fn(),
hasAnyScopes: vi.fn(),
authorizeAsync: vi.fn(),
refreshTokenNoCache: vi.fn(),
createGToken: vi.fn(),
};
vi.mocked(JWT).mockImplementation(() => mockJWTInstance as unknown as JWT);
return mockJWTInstance;
};
test("uses JWT auth with impersonation when DWD credential is provided", async () => {
const credentialWithDWD = await createCredentialInDb({
user: { email: "[email protected]" },
delegatedTo: delegatedCredential,
});
const calendarService = new CalendarService(credentialWithDWD);
await calendarService.listCalendars();
const expectedJWTConfig: MockJWT = {
type: "jwt",
config: {
email: delegatedCredential.serviceAccountKey.client_email,
key: delegatedCredential.serviceAccountKey.private_key,
scopes: ["https://www.googleapis.com/auth/calendar"],
subject: "[email protected]",
},
authorize: expect.any(Function) as () => Promise<void>,
};
expect(lastCreatedJWT).toEqual(expectedJWTConfig);
expect(calendarMock.calendar_v3.Calendar).toHaveBeenCalledWith({
auth: lastCreatedJWT,
});
});
test("uses OAuth2 auth when no DWD credential is provided", async () => {
const regularCredential = await createCredentialInDb();
const { client_id, client_secret, redirect_uris } = await getGoogleAppKeys();
const calendarService = new CalendarService(regularCredential);
await calendarService.listCalendars();
expect(lastCreatedJWT).toBeNull();
const expectedOAuth2Client: MockOAuth2Client = {
type: "oauth2",
args: [client_id, client_secret, redirect_uris[0]],
setCredentials: setCredentialsMock,
};
expect(lastCreatedOAuth2Client).toEqual(expectedOAuth2Client);
expect(setCredentialsMock).toHaveBeenCalledWith(regularCredential.key);
expect(calendarMock.calendar_v3.Calendar).toHaveBeenCalledWith({
auth: lastCreatedOAuth2Client,
});
});
test("handles DWD authorization errors appropriately", async () => {
const credentialWithDWD = await createCredentialInDb({
user: { email: "[email protected]" },
delegatedTo: delegatedCredential,
});
createMockJWTInstance({
authorizeError: {
response: {
data: {
error: "unauthorized_client",
},
},
},
});
const calendarService = new CalendarService(credentialWithDWD);
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"
);
});
test("handles invalid_grant error (user not in workspace) appropriately", async () => {
const credentialWithDWD = await createCredentialInDb({
user: { email: "[email protected]" },
delegatedTo: delegatedCredential,
});
createMockJWTInstance({
authorizeError: {
response: {
data: {
error: "invalid_grant",
},
},
},
});
const calendarService = new CalendarService(credentialWithDWD);
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({
user: { email: "[email protected]" },
delegatedTo: delegatedCredential,
});
createMockJWTInstance({
authorizeError: new Error("Some unexpected error"),
});
const calendarService = new CalendarService(credentialWithDWD);
await expect(calendarService.listCalendars()).rejects.toThrow("Error authorizing domain wide delegation");
});
test("handles missing user email for DWD appropriately", async () => {
const credentialWithDWD = await createCredentialInDb({
user: { email: null },
delegatedTo: delegatedCredential,
});
const calendarService = new CalendarService(credentialWithDWD);
const { client_id, client_secret, redirect_uris } = await getGoogleAppKeys();
await calendarService.listCalendars();
expect(lastCreatedJWT).toBeNull();
const expectedOAuth2Client: MockOAuth2Client = {
type: "oauth2",
args: [client_id, client_secret, redirect_uris[0]],
setCredentials: setCredentialsMock,
};
expect(lastCreatedOAuth2Client).toEqual(expectedOAuth2Client);
});
});
@@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { calendar_v3 } from "@googleapis/calendar";
import type { Prisma } from "@prisma/client";
import { OAuth2Client, JWT } from "googleapis-common";
import type { GaxiosResponse } from "googleapis-common";
import { OAuth2Client } from "googleapis-common";
import { RRule } from "rrule";
import { v4 as uuid } from "uuid";
@@ -12,6 +12,11 @@ import { CalendarCache } from "@calcom/features/calendar-cache/calendar-cache";
import type { FreeBusyArgs } from "@calcom/features/calendar-cache/calendar-cache.repository.interface";
import { getTimeMax, getTimeMin } from "@calcom/features/calendar-cache/lib/datesForCache";
import { getLocation, getRichDescription } from "@calcom/lib/CalEventParser";
import {
CalendarAppDomainWideDelegationClientIdNotAuthorizedError,
CalendarAppDomainWideDelegationInvalidGrantError,
CalendarAppDomainWideDelegationError,
} from "@calcom/lib/CalendarAppError";
import { uniqueBy } from "@calcom/lib/array";
import {
APP_CREDENTIAL_SHARING_ENABLED,
@@ -32,7 +37,7 @@ import type {
NewCalendarEventType,
} from "@calcom/types/Calendar";
import type { SelectedCalendarEventTypeIds } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarServiceWithEmail } from "@calcom/types/Credential";
import { invalidateCredential } from "../../_utils/invalidateCredential";
import { AxiosLikeResponseToFetchResponse } from "../../_utils/oauth/AxiosLikeResponseToFetchResponse";
@@ -70,10 +75,10 @@ export default class GoogleCalendarService implements Calendar {
private integrationName = "";
private auth: ReturnType<typeof this.initGoogleAuth>;
private log: typeof logger;
private credential: CredentialPayload;
private credential: CredentialForCalendarServiceWithEmail;
private myGoogleAuth!: MyGoogleAuth;
private oAuthManagerInstance!: OAuthManager;
constructor(credential: CredentialPayload) {
constructor(credential: CredentialForCalendarServiceWithEmail) {
this.integrationName = "google_calendar";
this.credential = credential;
this.auth = this.initGoogleAuth(credential);
@@ -91,7 +96,7 @@ export default class GoogleCalendarService implements Calendar {
return this.myGoogleAuth;
}
private initGoogleAuth = (credential: CredentialPayload) => {
private initGoogleAuth = (credential: CredentialForCalendarServiceWithEmail) => {
const currentTokenObject = getTokenObjectFromCredential(credential);
const auth = new OAuthManager({
// Keep it false because we are not using auth.request everywhere. That would be done later as it involves many google calendar sdk functionc calls and needs to be tested well.
@@ -175,7 +180,84 @@ export default class GoogleCalendarService implements Calendar {
};
};
private getAuthedCalendarFromDwd = async ({
domainWideDelegation,
emailToImpersonate,
}: {
emailToImpersonate: string;
domainWideDelegation: {
serviceAccountKey: {
client_email: string;
client_id: string;
private_key: string;
};
};
}) => {
const serviceAccountClientEmail = domainWideDelegation.serviceAccountKey.client_email;
const serviceAccountClientId = domainWideDelegation.serviceAccountKey.client_id;
const serviceAccountPrivateKey = domainWideDelegation.serviceAccountKey.private_key;
const authClient = new JWT({
email: serviceAccountClientEmail,
key: serviceAccountPrivateKey,
scopes: ["https://www.googleapis.com/auth/calendar"],
subject: emailToImpersonate,
});
try {
await authClient.authorize();
} catch (error) {
this.log.error("DWD: Error authorizing domain wide delegation", 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"
);
}
if ((error as any).response?.data?.error === "invalid_grant") {
throw new CalendarAppDomainWideDelegationInvalidGrantError(
"User might not exist in Google Workspace"
);
}
// Catch all error
throw new CalendarAppDomainWideDelegationError("Error authorizing domain wide delegation");
}
this.log.debug(
"Using domain wide delegation with service account email",
safeStringify({
serviceAccountClientEmail,
serviceAccountClientId,
emailToImpersonate,
})
);
return new calendar_v3.Calendar({
auth: authClient,
});
};
public authedCalendar = async () => {
let dwdAuthedCalendar;
if (this.credential.delegatedTo) {
if (!this.credential.user?.email) {
this.log.error("DWD: No email to impersonate found for domain wide delegation");
} else {
const oauthClientIdAliasRegex = /\+[a-zA-Z0-9]{25}/;
dwdAuthedCalendar = await this.getAuthedCalendarFromDwd({
domainWideDelegation: this.credential.delegatedTo,
emailToImpersonate: this.credential.user.email.replace(oauthClientIdAliasRegex, ""),
});
}
}
if (dwdAuthedCalendar) {
return dwdAuthedCalendar;
}
const myGoogleAuth = await this.auth.getMyGoogleAuthWithRefreshedToken();
const calendar = new calendar_v3.Calendar({
auth: myGoogleAuth,
@@ -183,7 +265,13 @@ export default class GoogleCalendarService implements Calendar {
return calendar;
};
private getAttendees = (event: CalendarEvent) => {
private getAttendees = ({
event,
hostExternalCalendarId,
}: {
event: CalendarEvent;
hostExternalCalendarId?: string;
}) => {
// When rescheduling events we know the external id of the calendar so we can just look for it in the destinationCalendar array.
const selectedHostDestinationCalendar = event.destinationCalendar?.find(
(cal) => cal.credentialId === this.credential.id
@@ -200,7 +288,7 @@ export default class GoogleCalendarService implements Calendar {
organizer: true,
// Tried changing the display name to the user but GCal will not let you do that. It will only display the name of the external calendar. Leaving this in just incase it works in the future.
displayName: event.organizer.name,
email: selectedHostDestinationCalendar?.externalId ?? event.organizer.email,
email: hostExternalCalendarId ?? selectedHostDestinationCalendar?.externalId ?? event.organizer.email,
},
...eventAttendees,
];
@@ -269,7 +357,11 @@ export default class GoogleCalendarService implements Calendar {
return res.data;
}
async createEvent(calEventRaw: CalendarEvent, credentialId: number): Promise<NewCalendarEventType> {
async createEvent(
calEventRaw: CalendarEvent,
credentialId: number,
externalCalendarId?: string
): Promise<NewCalendarEventType> {
this.log.debug("Creating event");
const formattedCalEvent = formatCalEvent(calEventRaw);
@@ -284,7 +376,7 @@ export default class GoogleCalendarService implements Calendar {
dateTime: formattedCalEvent.endTime,
timeZone: formattedCalEvent.organizer.timeZone,
},
attendees: this.getAttendees(formattedCalEvent),
attendees: this.getAttendees({ event: formattedCalEvent, hostExternalCalendarId: externalCalendarId }),
reminders: {
useDefault: true,
},
@@ -318,8 +410,9 @@ export default class GoogleCalendarService implements Calendar {
// Find in formattedCalEvent.destinationCalendar the one with the same credentialId
const selectedCalendar =
formattedCalEvent.destinationCalendar?.find((cal) => cal.credentialId === credentialId)?.externalId ||
"primary";
externalCalendarId ??
(formattedCalEvent.destinationCalendar?.find((cal) => cal.credentialId === credentialId)?.externalId ||
"primary");
try {
let event: calendar_v3.Schema$Event | undefined;
@@ -451,7 +544,7 @@ export default class GoogleCalendarService implements Calendar {
dateTime: formattedCalEvent.endTime,
timeZone: formattedCalEvent.organizer.timeZone,
},
attendees: this.getAttendees(formattedCalEvent),
attendees: this.getAttendees({ event: formattedCalEvent, hostExternalCalendarId: externalCalendarId }),
reminders: {
useDefault: true,
},
@@ -772,6 +865,13 @@ export default class GoogleCalendarService implements Calendar {
}
}
// It would error if the domain wide delegation is not set up correctly
async testDomainWideDelegationSetup() {
const calendar = await this.authedCalendar();
const cals = await calendar.calendarList.list({ fields: "items(id)" });
return !!cals.data.items;
}
/**
* It doesn't check if the subscription has expired or not.
* It just creates a new subscription.
@@ -4,7 +4,7 @@ import type { Page } from "@playwright/test";
import dayjs from "@calcom/dayjs";
import { APP_CREDENTIAL_SHARING_ENABLED } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarServiceWithEmail } from "@calcom/types/Credential";
import { test } from "@calcom/web/playwright/lib/fixtures";
import { selectSecondAvailableTimeSlotNextMonth } from "@calcom/web/playwright/lib/testUtils";
@@ -17,7 +17,7 @@ test.describe("Google Calendar", async () => {
// eslint-disable-next-line playwright/no-skipped-test
test.describe.skip("Test using the primary calendar", async () => {
let qaUsername: string;
let qaGCalCredential: CredentialPayload;
let qaGCalCredential: CredentialForCalendarServiceWithEmail;
test.beforeAll(async () => {
let runIntegrationTest = false;
const errorMessage = "Could not run test";
@@ -42,22 +42,25 @@ test.describe("Google Calendar", async () => {
test.skip(!process.env.E2E_TEST_CALCOM_QA_PASSWORD, "QA password not found");
if (process.env.E2E_TEST_CALCOM_QA_EMAIL && process.env.E2E_TEST_CALCOM_QA_PASSWORD) {
qaGCalCredential = await prisma.credential.findFirstOrThrow({
where: {
user: {
email: process.env.E2E_TEST_CALCOM_QA_EMAIL,
qaGCalCredential = {
...(await prisma.credential.findFirstOrThrow({
where: {
user: {
email: process.env.E2E_TEST_CALCOM_QA_EMAIL,
},
type: metadata.type,
},
type: metadata.type,
},
include: {
user: {
select: {
email: true,
include: {
user: {
select: {
email: true,
},
},
},
},
});
test.skip(!qaGCalCredential, "Google QA credential not found");
})),
delegatedTo: null,
} as CredentialForCalendarServiceWithEmail;
test.skip(!qaGCalCredential?.id, "Google QA credential not found");
const qaUserQuery = await prisma.user.findFirstOrThrow({
where: {
@@ -3,6 +3,10 @@ import type { DefaultBodyType } from "msw";
import dayjs from "@calcom/dayjs";
import { getLocation, getRichDescription } from "@calcom/lib/CalEventParser";
import {
CalendarAppDomainWideDelegationInvalidGrantError,
CalendarAppDomainWideDelegationConfigurationError,
} from "@calcom/lib/CalendarAppError";
import { handleErrorsJson, handleErrorsRaw } from "@calcom/lib/errors";
import logger from "@calcom/lib/logger";
import type { BufferedBusyTime } from "@calcom/types/BufferedBusyTime";
@@ -13,7 +17,7 @@ import type {
IntegrationCalendar,
NewCalendarEventType,
} from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarServiceWithTenantId } from "@calcom/types/Credential";
import { OAuthManager } from "../../_utils/oauth/OAuthManager";
import { getTokenObjectFromCredential } from "../../_utils/oauth/getTokenObjectFromCredential";
@@ -53,12 +57,12 @@ export default class Office365CalendarService implements Calendar {
private log: typeof logger;
private auth: OAuthManager;
private apiGraphUrl = "https://graph.microsoft.com/v1.0";
private credential: CredentialPayload;
private credential: CredentialForCalendarServiceWithTenantId;
private azureUserId?: string;
constructor(credential: CredentialPayload) {
constructor(credential: CredentialForCalendarServiceWithTenantId) {
this.integrationName = "office365_calendar";
const tokenResponse = getTokenObjectFromCredential(credential);
this.auth = new OAuthManager({
credentialSyncVariables: oAuthManagerHelper.credentialSyncVariables,
resourceOwner: {
@@ -68,20 +72,33 @@ export default class Office365CalendarService implements Calendar {
appSlug: metadata.slug,
currentTokenObject: tokenResponse,
fetchNewTokenObject: async ({ refreshToken }: { refreshToken: string | null }) => {
if (!refreshToken) {
const isDomainWideDelegated = Boolean(credential?.delegatedTo);
if (!isDomainWideDelegated && !refreshToken) {
return null;
}
const { client_id, client_secret } = await getOfficeAppKeys();
return await fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
const { client_id, client_secret } = await this.getAuthCredentials(isDomainWideDelegated);
const url = this.getAuthUrl(
isDomainWideDelegated,
credential?.delegatedTo?.serviceAccountKey?.tenant_id
);
const bodyParams = {
scope: isDomainWideDelegated
? "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 ?? "" }),
};
return fetch(url, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
scope: "User.Read Calendars.Read Calendars.ReadWrite",
client_id,
refresh_token: refreshToken,
grant_type: "refresh_token",
client_secret,
}),
body: new URLSearchParams(bodyParams),
});
},
isTokenObjectUnusable: async function () {
@@ -93,16 +110,138 @@ export default class Office365CalendarService implements Calendar {
// TODO: Implement this
return null;
},
invalidateTokenObject: () => oAuthManagerHelper.invalidateCredential(credential.id),
expireAccessToken: () => oAuthManagerHelper.markTokenAsExpired(credential),
updateTokenObject: (tokenObject) =>
oAuthManagerHelper.updateTokenObject({ tokenObject, credentialId: credential.id }),
updateTokenObject: (tokenObject) => {
if (!Boolean(credential.delegatedTo)) {
return oAuthManagerHelper.updateTokenObject({ tokenObject, credentialId: credential.id });
}
return Promise.resolve();
},
});
this.credential = credential;
this.log = logger.getSubLogger({ prefix: [`[[lib] ${this.integrationName}`] });
}
private getAuthUrl(delegatedTo: boolean, tenantId?: string): string {
if (delegatedTo) {
if (!tenantId) {
throw new CalendarAppDomainWideDelegationInvalidGrantError(
"Invalid DomainWideDelegation Settings: tenantId is missing"
);
}
return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
}
return "https://login.microsoftonline.com/common/oauth2/v2.0/token";
}
private async getAuthCredentials(isDomainWideDelegated: boolean) {
if (isDomainWideDelegated) {
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"
);
}
return { client_id, client_secret };
}
return getOfficeAppKeys();
}
private async getAzureUserId(credential: CredentialForCalendarServiceWithTenantId) {
if (this.azureUserId) return this.azureUserId;
const isDomainWideDelegated = Boolean(credential?.delegatedTo);
if (!isDomainWideDelegated) return;
const url = this.getAuthUrl(isDomainWideDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
const dwdClientId = credential.delegatedTo?.serviceAccountKey?.client_id;
const dwdClientSecret = credential.delegatedTo?.serviceAccountKey?.private_key;
if (!dwdClientId || !dwdClientSecret) {
throw new CalendarAppDomainWideDelegationConfigurationError(
"Domain Wide Delegated credential without clientId or Secret"
);
}
const loginResponse = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
scope: "https://graph.microsoft.com/.default",
client_id: dwdClientId,
grant_type: "client_credentials",
client_secret: dwdClientSecret,
}),
});
if (!this.azureUserId && credential?.delegatedTo) {
const clonedResponse = loginResponse.clone();
const parsedLoginResponse = await clonedResponse.json();
const token = parsedLoginResponse?.access_token;
const oauthClientIdAliasRegex = /\+[a-zA-Z0-9]{25}/;
const email = this.credential?.user?.email.replace(oauthClientIdAliasRegex, "");
const encodedFilter = encodeURIComponent(`mail eq '${email}'`);
const queryParams = `$filter=${encodedFilter}`;
const response = await fetch(`https://graph.microsoft.com/v1.0/users?${queryParams}`, {
method: "GET",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Bearer ${token}`,
},
});
const parsedBody = await response.json();
if (!parsedBody?.value?.[0]?.id) {
throw new CalendarAppDomainWideDelegationInvalidGrantError(
"User might not exist in Microsoft Azure Active Directory"
);
}
this.azureUserId = parsedBody.value[0].id;
}
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;
const url = this.getAuthUrl(
Boolean(this.credential?.delegatedTo),
this.credential?.delegatedTo?.serviceAccountKey?.tenant_id
);
if (!dwdClientId || !dwdClientSecret) {
return false;
}
const loginResponse = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
scope: "https://graph.microsoft.com/.default",
client_id: dwdClientId,
grant_type: "client_credentials",
client_secret: dwdClientSecret,
}),
});
const parsedLoginResponse = await loginResponse.json();
return Boolean(parsedLoginResponse?.access_token);
}
async getUserEndpoint(): Promise<string> {
const azureUserId = await this.getAzureUserId(this.credential);
return azureUserId ? `/users/${this.azureUserId}` : "/me";
}
async createEvent(event: CalendarEvent, credentialId: number): Promise<NewCalendarEventType> {
const mainHostDestinationCalendar = event.destinationCalendar
? event.destinationCalendar.find((cal) => cal.credentialId === credentialId) ??
@@ -110,8 +249,8 @@ export default class Office365CalendarService implements Calendar {
: undefined;
try {
const eventsUrl = mainHostDestinationCalendar?.externalId
? `/me/calendars/${mainHostDestinationCalendar?.externalId}/events`
: "/me/calendar/events";
? `${await this.getUserEndpoint()}/calendars/${mainHostDestinationCalendar?.externalId}/events`
: `${await this.getUserEndpoint()}/calendar/events`;
const response = await this.fetcher(eventsUrl, {
method: "POST",
@@ -130,7 +269,7 @@ export default class Office365CalendarService implements Calendar {
async updateEvent(uid: string, event: CalendarEvent): Promise<NewCalendarEventType> {
try {
const response = await this.fetcher(`/me/calendar/events/${uid}`, {
const response = await this.fetcher(`${await this.getUserEndpoint()}/calendar/events/${uid}`, {
method: "PATCH",
body: JSON.stringify(this.translateEvent(event)),
});
@@ -147,7 +286,7 @@ export default class Office365CalendarService implements Calendar {
async deleteEvent(uid: string): Promise<void> {
try {
const response = await this.fetcher(`/me/calendar/events/${uid}`, {
const response = await this.fetcher(`${await this.getUserEndpoint()}/calendar/events/${uid}`, {
method: "DELETE",
});
@@ -189,11 +328,12 @@ export default class Office365CalendarService implements Calendar {
const ids = await (selectedCalendarIds.length === 0
? this.listCalendars().then((cals) => cals.map((e_2) => e_2.externalId).filter(Boolean) || [])
: Promise.resolve(selectedCalendarIds));
const requests = ids.map((calendarId, id) => ({
const requestsPromises = ids.map(async (calendarId, id) => ({
id,
method: "GET",
url: `/me/calendars/${calendarId}/calendarView${filter}&${calendarSelectParams}`,
url: `${await this.getUserEndpoint()}/calendars/${calendarId}/calendarView${filter}&${calendarSelectParams}`,
}));
const requests = await Promise.all(requestsPromises);
const response = await this.apiGraphBatchCall(requests);
const responseBody = await this.handleErrorJsonOffice365Calendar(response);
let responseBatchApi: IBatchResponse = { responses: [] };
@@ -215,7 +355,6 @@ export default class Office365CalendarService implements Calendar {
return alreadySuccessResponse ? this.processBusyTimes(alreadySuccessResponse) : [];
} catch (err) {
console.log(err);
return Promise.reject([]);
}
}
@@ -227,7 +366,7 @@ export default class Office365CalendarService implements Calendar {
const calendarFilterParam = "$select=id,name,isDefaultCalendar,canEdit";
// Store @odata.nextLink if in response
let requestLink = `/me/calendars?${calendarFilterParam}`;
let requestLink = `${await this.getUserEndpoint()}/calendars?${calendarFilterParam}`;
while (!finishedParsingCalendars) {
const response = await this.fetcher(requestLink);
@@ -248,7 +387,7 @@ export default class Office365CalendarService implements Calendar {
}
}
const user = await this.fetcher("/me");
const user = await this.fetcher(`${await this.getUserEndpoint()}`);
const userResponseBody = await handleErrorsJson<User>(user);
const email = userResponseBody.mail ?? userResponseBody.userPrincipalName;
@@ -0,0 +1,29 @@
import type { AppMeta } from "@calcom/types/App";
import _package from "./package.json";
export const metadata = {
name: "Microsoft 365/Teams (Requires work/school account)",
description: _package.description,
appData: {
location: {
linkType: "dynamic",
type: "integrations:office365_video",
label: "MS Teams (Requires work/school account)",
},
},
type: "office365_video",
title: "MS Teams (Requires work/school account)",
variant: "conferencing",
category: "conferencing",
categories: ["conferencing"],
logo: "icon.svg",
publisher: "Cal.com",
slug: "msteams",
dirName: "office365video",
url: "https://www.microsoft.com/en-ca/microsoft-teams/group-chat-software",
email: "[email protected]",
isOAuth: true,
} as AppMeta;
export default metadata;
@@ -54,6 +54,7 @@ const testCredential = {
userId: 1,
user: { email: "[email protected]" },
teamId: 1,
delegatedTo: null,
};
describe("createMeeting", () => {
@@ -1,9 +1,13 @@
import { z } from "zod";
import {
CalendarAppDomainWideDelegationConfigurationError,
CalendarAppDomainWideDelegationInvalidGrantError,
} from "@calcom/lib/CalendarAppError";
import { handleErrorsRaw } from "@calcom/lib/errors";
import { HttpError } from "@calcom/lib/http-error";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarServiceWithTenantId } from "@calcom/types/Credential";
import type { PartialReference } from "@calcom/types/EventManager";
import type { VideoApiAdapter, VideoCallData } from "@calcom/types/VideoApiAdapter";
@@ -31,7 +35,9 @@ const getO365VideoAppKeys = async () => {
return getParsedAppKeysFromSlug(config.slug, o365VideoAppKeysSchema);
};
const TeamsVideoApiAdapter = (credential: CredentialPayload): VideoApiAdapter => {
const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenantId): VideoApiAdapter => {
console.log("TeamsVideoApiAdapter--credential: ", credential);
let azureUserId: string | null;
const tokenResponse = oAuthManagerHelper.getTokenObjectFromCredential(credential);
const auth = new OAuthManager({
@@ -43,19 +49,41 @@ const TeamsVideoApiAdapter = (credential: CredentialPayload): VideoApiAdapter =>
appSlug: config.slug,
currentTokenObject: tokenResponse,
fetchNewTokenObject: async ({ refreshToken }: { refreshToken: string | null }) => {
if (!refreshToken) {
const isDomainWideDelegated = Boolean(credential?.delegatedTo);
if (!isDomainWideDelegated && !refreshToken) {
return null;
}
const { client_id, client_secret } = await getO365VideoAppKeys();
return await fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
const credentials = isDomainWideDelegated
? {
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"
);
}
const url = getAuthUrl(isDomainWideDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
const scope = isDomainWideDelegated
? "https://graph.microsoft.com/.default"
: "User.Read Calendars.Read Calendars.ReadWrite";
const params: Record<string, string> = {
scope,
client_id: credentials.client_id || "",
client_secret: credentials.client_secret || "",
grant_type: isDomainWideDelegated ? "client_credentials" : "refresh_token",
...(isDomainWideDelegated ? {} : { refresh_token: refreshToken ?? "" }),
};
return await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id,
refresh_token: refreshToken,
grant_type: "refresh_token",
client_secret,
}),
body: new URLSearchParams(params),
});
},
isTokenObjectUnusable: async function () {
@@ -69,10 +97,27 @@ const TeamsVideoApiAdapter = (credential: CredentialPayload): VideoApiAdapter =>
},
invalidateTokenObject: () => oAuthManagerHelper.invalidateCredential(credential.id),
expireAccessToken: () => oAuthManagerHelper.markTokenAsExpired(credential),
updateTokenObject: (tokenObject) =>
oAuthManagerHelper.updateTokenObject({ tokenObject, credentialId: credential.id }),
updateTokenObject: (tokenObject) => {
if (!Boolean(credential.delegatedTo)) {
return oAuthManagerHelper.updateTokenObject({ tokenObject, credentialId: credential.id });
}
return Promise.resolve();
},
});
function getAuthUrl(delegatedTo: boolean, tenantId?: string): string {
if (delegatedTo) {
if (!tenantId) {
throw new CalendarAppDomainWideDelegationInvalidGrantError(
"Invalid DomainWideDelegation Settings: tenantId is missing"
);
}
return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
}
return "https://login.microsoftonline.com/common/oauth2/v2.0/token";
}
const translateEvent = (event: CalendarEvent) => {
return {
startDateTime: event.startTime,
@@ -81,6 +126,68 @@ const TeamsVideoApiAdapter = (credential: CredentialPayload): VideoApiAdapter =>
};
};
async function getAzureUserId(credential: CredentialForCalendarServiceWithTenantId) {
if (azureUserId) return azureUserId;
const isDomainWideDelegated = Boolean(credential?.delegatedTo);
if (!isDomainWideDelegated) return null;
const url = getAuthUrl(isDomainWideDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
const dwdClientId = credential.delegatedTo?.serviceAccountKey?.client_id;
const dwdClientSecret = credential.delegatedTo?.serviceAccountKey?.private_key;
if (!dwdClientId || !dwdClientSecret) {
throw new CalendarAppDomainWideDelegationConfigurationError(
"Domain Wide Delegated credential without clientId or Secret"
);
}
const loginResponse = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
scope: "https://graph.microsoft.com/.default",
client_id: dwdClientId,
grant_type: "client_credentials",
client_secret: dwdClientSecret,
}),
});
const clonedResponse = loginResponse.clone();
const parsedLoginResponse = await clonedResponse.json();
const token = parsedLoginResponse?.access_token;
const oauthClientIdAliasRegex = /\+[a-zA-Z0-9]{25}/;
const email = credential?.user?.email.replace(oauthClientIdAliasRegex, "");
const encodedFilter = encodeURIComponent(`mail eq '${email}'`);
const queryParams = `$filter=${encodedFilter}`;
const response = await fetch(`https://graph.microsoft.com/v1.0/users?${queryParams}`, {
method: "GET",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Bearer ${token}`,
},
});
const parsedBody = await response.json();
if (!parsedBody?.value?.[0]?.id) {
throw new CalendarAppDomainWideDelegationInvalidGrantError(
"User might not exist in Microsoft Azure Active Directory"
);
}
azureUserId = parsedBody.value[0].id;
return azureUserId;
}
async function getUserEndpoint(): Promise<string> {
const azureUserId = await getAzureUserId(credential);
return azureUserId
? `https://graph.microsoft.com/v1.0/users/${azureUserId}`
: "https://graph.microsoft.com/v1.0/me";
}
// Since the meeting link is not tied to an event we only need the create and update functions
return {
getAvailability: () => {
@@ -89,7 +196,7 @@ const TeamsVideoApiAdapter = (credential: CredentialPayload): VideoApiAdapter =>
updateMeeting: async (bookingRef: PartialReference, event: CalendarEvent) => {
const resultString = await auth
.requestRaw({
url: "https://graph.microsoft.com/v1.0/me/onlineMeetings",
url: `${await getUserEndpoint()}/onlineMeetings`,
options: {
method: "POST",
body: JSON.stringify(translateEvent(event)),
@@ -110,9 +217,14 @@ const TeamsVideoApiAdapter = (credential: CredentialPayload): VideoApiAdapter =>
return Promise.resolve([]);
},
createMeeting: async (event: CalendarEvent): Promise<VideoCallData> => {
console.log("=======>createMeeting: ");
const url = `${await getUserEndpoint()}/onlineMeetings`;
console.log("urllllllllllll: ", url);
console.log("translateEvent(event): ", translateEvent(event));
const resultString = await auth
.requestRaw({
url: "https://graph.microsoft.com/v1.0/me/onlineMeetings",
url,
options: {
method: "POST",
body: JSON.stringify(translateEvent(event)),
+26 -2
View File
@@ -3,6 +3,10 @@ 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";
import { prisma } from "@calcom/prisma";
import { AppCategories } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -27,7 +31,7 @@ export async function getLocationGroupedOptions(
// don't default to {}, when you do TS no longer determines the right types.
let idToSearchObject: Prisma.CredentialWhereInput;
let user = null;
if ("teamId" in userOrTeamId) {
const teamId = userOrTeamId.teamId;
// See if the team event belongs to an org
@@ -52,9 +56,14 @@ export async function getLocationGroupedOptions(
}
} else {
idToSearchObject = { userId: userOrTeamId.userId };
user = await prisma.user.findUnique({
where: {
id: userOrTeamId.userId,
},
});
}
const credentials = await prisma.credential.findMany({
const nonDwdCredentials = await prisma.credential.findMany({
where: {
...idToSearchObject,
app: {
@@ -73,6 +82,21 @@ 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,
},
});
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);
}
const integrations = await getEnabledAppsFromCredentials(credentials, { filterOnCredentials: true });
integrations.forEach((app) => {
+1 -1
View File
@@ -8,7 +8,7 @@
"@components/*": ["../../apps/web/components/*"],
/* A `package` should never import from `apps` ↓ */
"@lib/*": ["../../apps/web/lib/*"],
"@prisma/client/*": ["@calcom/prisma/client/*"]
"@prisma/client/*": ["@calcom/prisma/client/*"],
},
"resolveJsonModule": true,
"experimentalDecorators": true
+4 -2
View File
@@ -8,7 +8,7 @@ import logger from "@calcom/lib/logger";
import { getPiiFreeCredential } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import type { App, AppMeta } from "@calcom/types/App";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
export * from "./_utils/getEventTypeAppData";
@@ -33,7 +33,7 @@ const ALL_APPS_MAP = Object.keys(appStoreMetadata).reduce((store, key) => {
return store;
}, {} as Record<string, AppMeta>);
export type CredentialDataWithTeamName = CredentialPayload & {
export type CredentialDataWithTeamName = CredentialForCalendarService & {
team?: {
name: string;
} | null;
@@ -65,6 +65,8 @@ function getApps(credentials: CredentialDataWithTeamName[], filterOnCredentials?
teamId: null,
appId: appMeta.slug,
invalid: false,
delegatedTo: null,
delegatedToId: null,
team: {
name: "Global",
},
+3 -2
View File
@@ -4,7 +4,7 @@ import { getCalendarCredentials } from "./CalendarManager";
describe("CalendarManager tests", () => {
describe("fn: getCalendarCredentials", () => {
it("should only return credentials for calendar apps", () => {
it("should only return credentials for calendar apps", async () => {
const googleCalendarCredentials = {
id: "1",
appId: "google-calendar",
@@ -14,6 +14,7 @@ describe("CalendarManager tests", () => {
access_token: "google_calendar_key",
},
invalid: false,
delegatedTo: null,
};
const credentials = [
@@ -32,7 +33,7 @@ describe("CalendarManager tests", () => {
const calendarCredentials = getCalendarCredentials(credentials);
expect(calendarCredentials).toHaveLength(1);
expect(calendarCredentials[0].credential).toBe(googleCalendarCredentials);
expect(calendarCredentials[0].credential).toEqual(googleCalendarCredentials);
});
});
});
+34 -26
View File
@@ -5,6 +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 logger from "@calcom/lib/logger";
import { getPiiFreeCalendarEvent, getPiiFreeCredential } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -15,7 +17,7 @@ import type {
NewCalendarEventType,
SelectedCalendar,
} from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import type { EventResult } from "@calcom/types/EventManager";
import getCalendarsEvents from "./getCalendarsEvents";
@@ -23,7 +25,7 @@ import { getCalendarsEventsWithTimezones } from "./getCalendarsEvents";
const log = logger.getSubLogger({ prefix: ["CalendarManager"] });
export const getCalendarCredentials = (credentials: Array<CredentialPayload>) => {
export const getCalendarCredentials = (credentials: Array<CredentialForCalendarService>) => {
const calendarCredentials = getApps(credentials, true)
.filter((app) => app.type.endsWith("_calendar"))
.flatMap((app) => {
@@ -38,6 +40,10 @@ export const getCalendarCredentials = (credentials: Array<CredentialPayload>) =>
return calendarCredentials;
};
export const getCalendarCredentialsWithoutDwd = (credentials: CredentialPayload[]) => {
return getCalendarCredentials(buildNonDwdCredentials(credentials));
};
export const getConnectedCalendars = async (
calendarCredentials: ReturnType<typeof getCalendarCredentials>,
selectedCalendars: { externalId: string }[],
@@ -51,10 +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;
if (!calendar) {
return {
integration,
credentialId,
domainWideDelegationCredentialId,
};
}
const cals = await calendar.listCalendars();
@@ -67,6 +75,7 @@ export const getConnectedCalendars = async (
primary: cal.primary || null,
isSelected: selectedCalendars.some((selected) => selected.externalId === cal.externalId),
credentialId,
domainWideDelegationCredentialId,
};
}),
["primary"]
@@ -91,6 +100,7 @@ export const getConnectedCalendars = async (
return {
integration: cleanIntegrationKeys(integration),
credentialId,
domainWideDelegationCredentialId,
primary,
calendars,
};
@@ -104,11 +114,16 @@ export const getConnectedCalendars = async (
}
}
if (error instanceof CalendarAppDomainWideDelegationError) {
errorMessage = error.message;
}
log.error("getConnectedCalendars failed", safeStringify(error), safeStringify({ item }));
return {
integration: cleanIntegrationKeys(item.integration),
credentialId: item.credential.id,
domainWideDelegationCredentialId: item.credential.delegatedToId,
error: {
message: errorMessage,
},
@@ -126,7 +141,7 @@ export const getConnectedCalendars = async (
* @returns App
*/
const cleanIntegrationKeys = (
appIntegration: ReturnType<typeof getCalendarCredentials>[number]["integration"] & {
appIntegration: Awaited<ReturnType<typeof getCalendarCredentials>>[number]["integration"] & {
credentials?: Array<CredentialPayload>;
credential: CredentialPayload;
}
@@ -136,25 +151,12 @@ const cleanIntegrationKeys = (
return rest;
};
/**
* Get months between given dates
* @returns ["2023-04", "2024-05"]
*/
const getMonths = (dateFrom: string, dateTo: string): string[] => {
const months: string[] = [dayjs(dateFrom).format("YYYY-MM")];
for (
let i = 1;
dayjs(dateFrom).add(i, "month").isBefore(dateTo) ||
dayjs(dateFrom).add(i, "month").isSame(dateTo, "month");
i++
) {
months.push(dayjs(dateFrom).add(i, "month").format("YYYY-MM"));
}
return months;
};
export const getBusyCalendarTimes = async (
withCredentials: CredentialPayload[],
/**
* withCredentials can possibly have a duplicate credential in case DWD 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[],
dateFrom: string,
dateTo: string,
selectedCalendars: SelectedCalendar[],
@@ -187,7 +189,7 @@ export const getBusyCalendarTimes = async (
};
export const createEvent = async (
credential: CredentialPayload,
credential: CredentialForCalendarService,
calEvent: CalendarEvent,
externalId?: string
): Promise<EventResult<NewCalendarEventType>> => {
@@ -207,10 +209,14 @@ export const createEvent = async (
calEvent.additionalNotes = "Notes have been hidden by the organizer"; // TODO: i18n this string?
}
const externalCalendarIdWhenDwdCredentialIsChosen = credential.delegatedToId ? externalId : undefined;
// TODO: Surface success/error messages coming from apps to improve end user visibility
const creationResult = calendar
? await calendar
.createEvent(calEvent, credential.id)
// 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.
// Such logic shouldn't exist in CalendarService as it would be same for all calendar apps.
.createEvent(calEvent, credential.id, externalCalendarIdWhenDwdCredentialIsChosen)
.catch(async (error: { code: number; calError: string }) => {
success = false;
/**
@@ -225,7 +231,8 @@ export const createEvent = async (
}
log.error(
"createEvent failed",
safeStringify({ error, calEvent: getPiiFreeCalendarEvent(calEvent) })
safeStringify(error),
safeStringify({ calEvent: getPiiFreeCalendarEvent(calEvent) })
);
// @TODO: This code will be off till we can investigate an error with it
//https://github.com/calcom/cal.com/issues/3949
@@ -264,11 +271,12 @@ export const createEvent = async (
calWarnings: creationResult?.additionalInfo?.calWarnings || [],
externalId,
credentialId: credential.id,
delegatedToId: credential.delegatedToId ?? undefined,
};
};
export const updateEvent = async (
credential: CredentialPayload,
credential: CredentialForCalendarService,
calEvent: CalendarEvent,
bookingRefUid: string | null,
externalCalendarId: string | null
@@ -352,7 +360,7 @@ export const deleteEvent = async ({
event,
externalCalendarId,
}: {
credential: CredentialPayload;
credential: CredentialForCalendarService;
bookingRefUid: string;
event: CalendarEvent;
externalCalendarId?: string | null;
+104 -60
View File
@@ -20,12 +20,12 @@ import {
getPiiFreeCalendarEvent,
} from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import prisma from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { createdEventSchema } from "@calcom/prisma/zod-utils";
import type { EventTypeAppMetadataSchema } from "@calcom/prisma/zod-utils";
import type { AdditionalInformation, CalendarEvent, NewCalendarEventType } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { Event } from "@calcom/types/Event";
import type {
CreateUpdateResult,
@@ -47,17 +47,18 @@ interface HasId {
id: number;
}
// The options should have the slug of the apps the option is enabled for
interface AppOptions {
crm: {
skipContactCreation: string[];
};
}
const latestCredentialFirst = <T extends HasId>(a: T, b: T) => {
return b.id - a.id;
};
const delegatedCredentialFirst = <T extends { delegatedToId?: string | null }>(a: T, b: T) => {
return (b.delegatedToId ? 1 : 0) - (a.delegatedToId ? 1 : 0);
};
const delegatedCredentialLast = <T extends { delegatedToId?: string | null }>(a: T, b: T) => {
return (a.delegatedToId ? 1 : 0) - (b.delegatedToId ? 1 : 0);
};
export const getLocationRequestFromIntegration = (location: string) => {
const eventLocationType = getLocationFromApp(location);
if (eventLocationType) {
@@ -76,6 +77,21 @@ export const getLocationRequestFromIntegration = (location: string) => {
return null;
};
const getCredential = ({
id,
allCredentials,
}: {
id: {
domainWideDelegationCredentialId: string | null;
credentialId: number | null;
};
allCredentials: CredentialForCalendarService[];
}) => {
return id.domainWideDelegationCredentialId
? allCredentials.find((c) => c.delegatedToId === id.domainWideDelegationCredentialId)
: allCredentials.find((c) => c.id === id.credentialId);
};
export const processLocation = (event: CalendarEvent): CalendarEvent => {
// If location is set to an integration location
// Build proper transforms for evt object
@@ -91,8 +107,18 @@ export const processLocation = (event: CalendarEvent): CalendarEvent => {
return event;
};
/**
* Ensures invalid non-dwd credentialId isn't returned
*/
function getCredentialPayload(result: EventResult<Exclude<Event, AdditionalInformation>>) {
return {
credentialId: result?.credentialId && result.credentialId > 0 ? result.credentialId : undefined,
domainWideDelegationCredentialId: result?.delegatedToId || undefined,
};
}
export type EventManagerUser = {
credentials: CredentialPayload[];
credentials: CredentialForCalendarService[];
destinationCalendar: DestinationCalendar | null;
};
@@ -104,11 +130,10 @@ export type EventManagerInitParams = {
};
export default class EventManager {
calendarCredentials: CredentialPayload[];
videoCredentials: CredentialPayload[];
crmCredentials: CredentialPayload[];
calendarCredentials: CredentialForCalendarService[];
videoCredentials: CredentialForCalendarService[];
crmCredentials: CredentialForCalendarService[];
appOptions?: z.infer<typeof EventTypeAppMetadataSchema>;
/**
* Takes an array of credentials and initializes a new instance of the EventManager.
*
@@ -125,8 +150,14 @@ export default class EventManager {
// Backwards compatibility until CRM manager is implemented
(cred) => cred.type.endsWith("_calendar") && !cred.type.includes("other_calendar")
)
//see https://github.com/calcom/cal.com/issues/11671#issue-1923600672
.sort(latestCredentialFirst);
// see https://github.com/calcom/cal.com/issues/11671#issue-1923600672
// This sorting is mostly applicable for fallback which happens when there is no explicity destinationCalendar set. That could be true for really old accounts but not for new
.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.
.sort(delegatedCredentialLast);
this.videoCredentials = appCredentials
.filter((cred) => cred.type.endsWith("_video") || cred.type.endsWith("_conferencing"))
// Whenever a new video connection is added, latest credentials are added with the highest ID.
@@ -173,7 +204,7 @@ export default class EventManager {
const [mainHostDestinationCalendar] =
(evt.destinationCalendar as [undefined | NonNullable<typeof evt.destinationCalendar>[number]]) ?? [];
if (evt.location === MeetLocationType && mainHostDestinationCalendar?.integration !== "google_calendar") {
log.warn("Falling back to Cal Video integration as Google Calendar not installed");
log.warn("Falling back to Cal Video integration as Google Calendar is not set as destination calendar");
evt["location"] = "integrations:daily";
evt["conferenceCredentialId"] = undefined;
}
@@ -242,7 +273,7 @@ export default class EventManager {
meetingPassword: createdEventObj ? createdEventObj.password : result.createdEvent?.password,
meetingUrl: createdEventObj ? createdEventObj.onlineMeetingUrl : result.createdEvent?.url,
externalCalendarId: isCalendarType ? result.externalId : undefined,
credentialId: result?.credentialId || undefined,
...getCredentialPayload(result),
};
});
@@ -332,8 +363,10 @@ export default class EventManager {
const calendarCredential = await this.getCredentialAndWarnIfNotFound(
credentialId,
this.calendarCredentials,
credentialType
credentialType,
reference.domainWideDelegationCredentialId
);
if (calendarCredential) {
await deleteEvent({
credential: calendarCredential,
@@ -361,21 +394,20 @@ export default class EventManager {
private async getCredentialAndWarnIfNotFound(
credentialId: number | null | undefined,
credentials: CredentialPayload[],
type: string
credentials: CredentialForCalendarService[],
type: string,
domainWideDelegationCredentialId?: string | null
) {
if (domainWideDelegationCredentialId) {
return this.calendarCredentials.find((cred) => cred.delegatedToId === domainWideDelegationCredentialId);
}
const credential = credentials.find((cred) => cred.id === credentialId);
if (credential) {
return credential;
} else {
const credential =
typeof credentialId === "number" && credentialId > 0
? await prisma.credential.findUnique({
where: {
id: credentialId,
},
select: credentialForCalendarServiceSelect,
})
? await CredentialRepository.findCredentialForCalendarServiceById({ id: credentialId })
: // Fallback for zero or nullish credentialId which could be the case of Global App e.g. dailyVideo
this.videoCredentials.find((cred) => cred.type === type) ||
this.calendarCredentials.find((cred) => cred.type === type) ||
@@ -637,7 +669,7 @@ export default class EventManager {
const [credential] = this.calendarCredentials.filter((cred) => !cred.type.endsWith("other_calendar"));
if (credential) {
const createdEvent = await createEvent(credential, event);
log.silly("Created Calendar event", safeStringify({ createdEvent }));
log.silly("Created Calendar event using credential", safeStringify({ credential, createdEvent }));
if (createdEvent) {
createdEvents.push(createdEvent);
}
@@ -667,27 +699,43 @@ export default class EventManager {
for (const destination of destinationCalendars) {
if (eventCreated) break;
log.silly("Creating Calendar event", JSON.stringify({ destination }));
if (destination.credentialId) {
let credential = this.calendarCredentials.find((c) => c.id === destination.credentialId);
if (destination.credentialId || destination.domainWideDelegationCredentialId) {
let credential = getCredential({
id: {
credentialId: destination.credentialId,
domainWideDelegationCredentialId: destination.domainWideDelegationCredentialId,
},
allCredentials: this.calendarCredentials,
});
if (!credential) {
// Fetch credential from DB
const credentialFromDB = await prisma.credential.findUnique({
where: {
if (destination.credentialId) {
// Fetch credential from DB
const credentialFromDB = await CredentialRepository.findCredentialForCalendarServiceById({
id: destination.credentialId,
},
select: credentialForCalendarServiceSelect,
});
if (credentialFromDB && credentialFromDB.appId) {
credential = {
id: credentialFromDB.id,
type: credentialFromDB.type,
key: credentialFromDB.key,
userId: credentialFromDB.userId,
teamId: credentialFromDB.teamId,
invalid: credentialFromDB.invalid,
appId: credentialFromDB.appId,
user: credentialFromDB.user,
};
});
if (credentialFromDB && credentialFromDB.appId) {
credential = {
id: credentialFromDB.id,
type: credentialFromDB.type,
key: credentialFromDB.key,
userId: credentialFromDB.userId,
teamId: credentialFromDB.teamId,
invalid: credentialFromDB.invalid,
appId: credentialFromDB.appId,
user: credentialFromDB.user,
delegatedToId: credentialFromDB.delegatedToId,
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(
(cred) => !cred.type.endsWith("other_calendar") && !cred.delegatedToId
);
credential = firstNonDwdCalendarCredential;
}
}
if (credential) {
@@ -753,7 +801,7 @@ export default class EventManager {
* @private
*/
private getVideoCredential(event: CalendarEvent): CredentialPayload | undefined {
private getVideoCredential(event: CalendarEvent): CredentialForCalendarService | undefined {
if (!event.location) {
return undefined;
}
@@ -766,7 +814,7 @@ export default class EventManager {
(credential) => credential.id === event.conferenceCredentialId
);
} else {
videoCredential = this.videoCredentials.find((credential: CredentialPayload) =>
videoCredential = this.videoCredentials.find((credential: CredentialForCalendarService) =>
credential.type.includes(integrationName)
);
log.warn(
@@ -861,11 +909,8 @@ export default class EventManager {
)[0];
if (!credential) {
// Fetch credential from DB
const credentialFromDB = await prisma.credential.findUnique({
where: {
id: reference.credentialId,
},
select: credentialForCalendarServiceSelect,
const credentialFromDB = await CredentialRepository.findCredentialForCalendarServiceById({
id: reference.credentialId,
});
if (credentialFromDB && credentialFromDB.appId) {
credential = {
@@ -877,6 +922,8 @@ export default class EventManager {
invalid: credentialFromDB.invalid,
appId: credentialFromDB.appId,
user: credentialFromDB.user,
delegatedToId: credentialFromDB.delegatedToId,
delegatedTo: credentialFromDB.delegatedTo,
};
}
}
@@ -896,11 +943,8 @@ export default class EventManager {
const oldCalendarEvent = booking.references.find((reference) => reference.type.includes("_calendar"));
if (oldCalendarEvent?.credentialId) {
const calendarCredential = await prisma.credential.findUnique({
where: {
id: oldCalendarEvent.credentialId,
},
select: credentialForCalendarServiceSelect,
const calendarCredential = await CredentialRepository.findCredentialForCalendarServiceById({
id: oldCalendarEvent.credentialId,
});
const calendar = await getCalendar(calendarCredential);
await calendar?.deleteEvent(oldCalendarEvent.uid, event, oldCalendarEvent.externalCalendarId);
@@ -1061,7 +1105,7 @@ export default class EventManager {
}
}
private getAppOptionsFromEventMetadata(credential: CredentialPayload) {
private getAppOptionsFromEventMetadata(credential: CredentialForCalendarService) {
if (!this.appOptions || !credential.appId) return {};
if (credential.appId in this.appOptions)
+2 -2
View File
@@ -14,12 +14,12 @@ import type { SelectedCalendar } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
import { stringToDayjs } from "@calcom/prisma/zod-utils";
import type { EventBusyDetails, IntervalLimit } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import { getDefinedBufferTimes } from "../features/eventtypes/lib/getDefinedBufferTimes";
export async function getBusyTimes(params: {
credentials: CredentialPayload[];
credentials: CredentialForCalendarService[];
userId: number;
userEmail: string;
username: string;
+3 -4
View File
@@ -4,13 +4,12 @@ import { getPiiFreeCredential, getPiiFreeSelectedCalendar } from "@calcom/lib/pi
import { safeStringify } from "@calcom/lib/safeStringify";
import { performance } from "@calcom/lib/server/perfObserver";
import type { EventBusyDate, SelectedCalendar } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
const log = logger.getSubLogger({ prefix: ["getCalendarsEvents"] });
// only for Google Calendar for now
export const getCalendarsEventsWithTimezones = async (
withCredentials: CredentialPayload[],
withCredentials: CredentialForCalendarService[],
dateFrom: string,
dateTo: string,
selectedCalendars: SelectedCalendar[]
@@ -46,7 +45,7 @@ export const getCalendarsEventsWithTimezones = async (
};
const getCalendarsEvents = async (
withCredentials: CredentialPayload[],
withCredentials: CredentialForCalendarService[],
dateFrom: string,
dateTo: string,
selectedCalendars: SelectedCalendar[],
+2 -2
View File
@@ -19,8 +19,8 @@ import { ErrorCode } from "@calcom/lib/errorCodes";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { findUsersForAvailabilityCheck } from "@calcom/lib/server/findUsersForAvailabilityCheck";
import { EventTypeRepository } from "@calcom/lib/server/repository/eventType";
import { UserRepository } from "@calcom/lib/server/repository/user";
import prisma from "@calcom/prisma";
import { SchedulingType } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
@@ -152,7 +152,7 @@ const getUser = async (...args: Parameters<typeof _getUser>): Promise<ReturnType
};
const _getUser = async (where: Prisma.UserWhereInput) => {
return UserRepository.findForAvailabilityCheck({ where });
return findUsersForAvailabilityCheck({ where });
};
type GetUser = Awaited<ReturnType<typeof getUser>>;
@@ -12,6 +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 { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AppCategories } from "@calcom/prisma/enums";
import { type RouterOutputs } from "@calcom/trpc";
@@ -229,7 +230,7 @@ function ConnectOrDisconnectIntegrationMenuItem(props: {
<DropdownItem
color="destructive"
onClick={() => handleDisconnect(credentialId, app, teamId)}
disabled={isGlobal}
disabled={isGlobal || isDwdCredential({ credentialId })}
StartIcon="trash">
{t("remove_app")}
</DropdownItem>
@@ -2,6 +2,7 @@
import { useState } from "react";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import type { ButtonProps } from "@calcom/ui";
@@ -37,11 +38,14 @@ export default function DisconnectIntegration(props: {
},
});
// Such a credential is added in-memory and removed when Domain-wide delegation is disabled.
const disableDisconnect = isDwdCredential({ credentialId });
return (
<DisconnectIntegrationComponent
onDeletionConfirmation={() => mutation.mutate({ id: credentialId, ...(teamId ? { teamId } : {}) })}
isModalOpen={modalOpen}
onModalOpen={() => setModalOpen((prevValue) => !prevValue)}
disabled={disableDisconnect}
{...props}
/>
);
@@ -643,6 +643,7 @@ export const getOptions = ({
const gCalService = new GoogleCalendarService({
...gcalCredential,
user: null,
delegatedTo: null,
});
if (
@@ -1,5 +1,6 @@
import type z from "zod";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { UserRepository } from "@calcom/lib/server/repository/user";
import prisma from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
@@ -7,18 +8,20 @@ import { eventTypeAppMetadataOptionalSchema } from "@calcom/prisma/zod-utils";
import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { CredentialPayload } from "@calcom/types/Credential";
export type EventType = {
userId?: number | null;
team?: { id: number | null; parentId: number | null } | null;
parentId?: number | null;
metadata: z.infer<typeof EventTypeMetaDataSchema>;
} | null;
/**
* Gets credentials from the user, team, and org if applicable
*
*/
export const getAllCredentials = async (
user: { id: number; username: string | null; credentials: CredentialPayload[] },
eventType: {
userId?: number | null;
team?: { id: number | null; parentId: number | null } | null;
parentId?: number | null;
metadata: z.infer<typeof EventTypeMetaDataSchema>;
} | null
user: { id: number; username: string | null; email: string; credentials: CredentialPayload[] },
eventType: EventType
) => {
let allCredentials = user.credentials;
@@ -117,5 +120,9 @@ export const getAllCredentials = async (
}
});
return allCredentials;
const userWithDwdCredentials = await enrichUserWithDwdCredentialsWithoutOrgId({
user: { ...user, credentials: allCredentials },
});
return userWithDwdCredentials.credentials;
};
@@ -1,6 +1,8 @@
import async from "async";
import type { CredentialPayload } from "@calcom/types/Credential";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { buildAllCredentials } from "@calcom/lib/domainWideDelegation/server";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import { refreshCredential } from "./refreshCredential";
@@ -10,7 +12,14 @@ import { refreshCredential } from "./refreshCredential";
* @param credentials
*/
export async function refreshCredentials(
credentials: Array<CredentialPayload>
): Promise<Array<CredentialPayload>> {
return await async.mapLimit(credentials, 5, refreshCredential);
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 });
}
@@ -70,6 +70,7 @@ async function getBookingToDelete(id: number | undefined, uid: string | undefine
externalCalendarId: true,
credentialId: true,
thirdPartyRecurringEventId: true,
domainWideDelegationCredentialId: true,
},
},
payment: true,
@@ -47,8 +47,12 @@ import {
scheduleTrigger,
} from "@calcom/features/webhooks/lib/scheduleTrigger";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import { isRerouting, shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";
import { shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";
import { getDefaultEvent, getUsernameList } from "@calcom/lib/defaultEvents";
import {
enrichHostsWithDwdCredentials,
getFirstDwdConferencingCredentialAppLocation,
} from "@calcom/lib/domainWideDelegation/server";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { extractBaseEmail } from "@calcom/lib/extract-base-email";
@@ -76,6 +80,7 @@ import type { PlatformClientParams } from "@calcom/prisma/zod-utils";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import { getAllWorkflowsFromEventType } from "@calcom/trpc/server/routers/viewer/workflows/util";
import type { AdditionalInformation, AppsStatus, CalendarEvent, Person } from "@calcom/types/Calendar";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { EventResult, PartialReference } from "@calcom/types/EventManager";
import type { EventPayloadType, EventTypeInfo } from "../../webhooks/lib/sendPayload";
@@ -113,6 +118,10 @@ import handleSeats from "./handleSeats/handleSeats";
const translator = short();
const log = logger.getSubLogger({ prefix: ["[api] book:user"] });
type IsFixedAwareUserWithCredentials = Omit<IsFixedAwareUser, "credentials"> & {
credentials: CredentialForCalendarService[];
};
export const createLoggerWithEventDetails = (
eventTypeId: number,
reqBodyUser: string | string[] | undefined,
@@ -167,36 +176,6 @@ type BookingDataSchemaGetter =
| typeof getBookingDataSchema
| typeof import("@calcom/features/bookings/lib/getBookingDataSchemaForApi").default;
/**
* Adds the contact owner to be the only lucky user
* @returns
*/
function buildLuckyUsersWithJustContactOwner({
contactOwnerEmail,
availableUsers,
fixedUserPool,
}: {
contactOwnerEmail: string | null;
availableUsers: IsFixedAwareUser[];
fixedUserPool: IsFixedAwareUser[];
}) {
const luckyUsers: Awaited<ReturnType<typeof loadAndValidateUsers>>["qualifiedRRUsers"] = [];
if (!contactOwnerEmail) {
return luckyUsers;
}
const isContactOwnerAFixedHostAlready = fixedUserPool.some((user) => user.email === contactOwnerEmail);
if (isContactOwnerAFixedHostAlready) {
return luckyUsers;
}
const teamMember = availableUsers.find((user) => user.email === contactOwnerEmail);
if (teamMember) {
luckyUsers.push(teamMember);
}
return luckyUsers;
}
type CreatedBooking = Booking & { appsStatus?: AppsStatus[]; paymentUid?: string; paymentId?: number };
const buildDryRunBooking = ({
@@ -478,11 +457,6 @@ async function handler(
const contactOwnerFromReq = reqBody.teamMemberEmail ?? null;
const isReroutingCase = isRerouting({
rescheduleUid: reqBody.rescheduleUid ?? null,
routedTeamMemberIds: routedTeamMemberIds ?? null,
});
const skipContactOwner = shouldIgnoreContactOwner({
skipContactOwner: reqBody.skipContactOwner ?? null,
rescheduleUid: reqBody.rescheduleUid ?? null,
@@ -529,11 +503,13 @@ async function handler(
// We filter out users but ensure allHostUsers remain same.
let users = [...qualifiedRRUsers, ...additionalFallbackRRUsers, ...fixedUsers];
let { locationBodyString, organizerOrFirstDynamicGroupMemberDefaultLocationUrl } = getLocationValuesForDb(
const firstUser = users[0];
let { locationBodyString, organizerOrFirstDynamicGroupMemberDefaultLocationUrl } = getLocationValuesForDb({
dynamicUserList,
users,
location
);
location,
});
await monitorCallbackAsync(checkBookingAndDurationLimits, {
eventType,
@@ -565,11 +541,11 @@ async function handler(
//checks what users are available
if (isFirstSeat) {
const eventTypeWithUsers: getEventTypeResponse & {
users: IsFixedAwareUser[];
const eventTypeWithUsers: Omit<getEventTypeResponse, "users"> & {
users: IsFixedAwareUserWithCredentials[];
} = {
...eventType,
users: users as IsFixedAwareUser[],
users: users as IsFixedAwareUserWithCredentials[],
...(eventType.recurringEvent && {
recurringEvent: {
...eventType.recurringEvent,
@@ -583,7 +559,7 @@ async function handler(
eventType.schedulingType === SchedulingType.ROUND_ROBIN;
const fixedUsers = isTeamEvent
? eventTypeWithUsers.users.filter((user: IsFixedAwareUser) => user.isFixed)
? eventTypeWithUsers.users.filter((user: IsFixedAwareUserWithCredentials) => user.isFixed)
: [];
for (
@@ -609,6 +585,7 @@ async function handler(
);
}
} else {
eventTypeWithUsers.users[0].credentials;
await ensureAvailableUsers(
eventTypeWithUsers,
{
@@ -705,13 +682,19 @@ async function handler(
// freeUsers is ensured
const userIdsSet = new Set(users.map((user) => user.id));
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
memberId: eventTypeWithUsers.users[0].id ?? null,
teamId: eventType.teamId,
});
const newLuckyUser = await getLuckyUser({
// find a lucky user that is not already in the luckyUsers array
availableUsers: freeUsers,
allRRHosts: eventTypeWithUsers.hosts.filter(
(host) => !host.isFixed && userIdsSet.has(host.user.id)
), // users part of virtual queue
allRRHosts: (
await enrichHostsWithDwdCredentials({
orgId: firstUserOrgId ?? null,
hosts: eventTypeWithUsers.hosts,
})
).filter((host) => !host.isFixed && userIdsSet.has(host.user.id)),
eventType,
routingFormResponse,
});
@@ -825,6 +808,11 @@ async function handler(
locationBodyString = OrganizerDefaultConferencingAppType;
}
}
const organizationDefaultLocation = getFirstDwdConferencingCredentialAppLocation({
credentials: firstUser.credentials,
});
// use host default
if (locationBodyString == OrganizerDefaultConferencingAppType) {
const metadataParseResult = userMetadataSchema.safeParse(organizerUser.metadata);
@@ -836,6 +824,8 @@ async function handler(
organizerOrFirstDynamicGroupMemberDefaultLocationUrl =
organizerMetadata?.defaultConferencingApp?.appLink;
}
} else if (organizationDefaultLocation) {
locationBodyString = organizationDefaultLocation;
} else {
locationBodyString = "integrations:daily";
}
@@ -1294,7 +1284,7 @@ async function handler(
endTime: reqBody.end,
contactOwnerFromReq,
contactOwnerEmail,
allHostUsers: [...qualifiedRRUsers, ...additionalFallbackRRUsers, ...fixedUsers],
allHostUsers: users,
isManagedEventType,
});
booking = dryRunBooking;
@@ -49,7 +49,7 @@ const hasDateRangeForBooking = (
};
export async function ensureAvailableUsers(
eventType: getEventTypeResponse & {
eventType: Omit<getEventTypeResponse, "users"> & {
users: IsFixedAwareUser[];
},
input: { dateFrom: string; dateTo: string; timeZone: string; originalRescheduledBooking?: BookingType },
@@ -1,10 +1,12 @@
import { getFirstDwdConferencingCredentialAppLocation } from "@calcom/lib/domainWideDelegation/server";
import type { Prisma } from "@calcom/prisma/client";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { loadAndValidateUsers } from "./loadAndValidateUsers";
type Users = Awaited<ReturnType<typeof loadAndValidateUsers>>["qualifiedRRUsers"];
const sortUsersByDynamicList = (users: Users, dynamicUserList: string[]) => {
const sortUsersByDynamicList = <TUser extends { username: string | null }>(
users: TUser[],
dynamicUserList: string[]
) => {
return users.sort((a, b) => {
const aIndex = (a.username && dynamicUserList.indexOf(a.username)) || 0;
const bIndex = (b.username && dynamicUserList.indexOf(b.username)) || 0;
@@ -12,19 +14,41 @@ const sortUsersByDynamicList = (users: Users, dynamicUserList: string[]) => {
});
};
export const getLocationValuesForDb = (
dynamicUserList: string[],
users: Users,
locationBodyString: string
) => {
// TODO: It's definition should be moved to getLocationValueForDb
let organizerOrFirstDynamicGroupMemberDefaultLocationUrl;
if (dynamicUserList.length > 1) {
users = sortUsersByDynamicList(users, dynamicUserList);
const firstUsersMetadata = userMetadataSchema.parse(users[0].metadata);
locationBodyString = firstUsersMetadata?.defaultConferencingApp?.appLink || locationBodyString;
organizerOrFirstDynamicGroupMemberDefaultLocationUrl =
firstUsersMetadata?.defaultConferencingApp?.appLink;
export const getLocationValuesForDb = <
TUser extends {
username: string | null;
metadata: Prisma.JsonValue;
credentials: CredentialForCalendarService[];
}
return { locationBodyString, organizerOrFirstDynamicGroupMemberDefaultLocationUrl };
>({
dynamicUserList,
users,
location: locationBodyString,
}: {
dynamicUserList: string[];
users: TUser[];
location: string;
}) => {
const isDynamicGroupBookingCase = dynamicUserList.length > 1;
let firstDynamicGroupMemberDefaultLocationUrl;
// TODO: It's definition should be moved to getLocationValueForDb
if (isDynamicGroupBookingCase) {
users = sortUsersByDynamicList(users, dynamicUserList);
const firstDynamicGroupMember = users[0];
const firstDynamicGroupMemberMetadata = userMetadataSchema.parse(firstDynamicGroupMember.metadata);
const firstDynamicGroupMemberDwdConferencingAppLocation = getFirstDwdConferencingCredentialAppLocation({
credentials: firstDynamicGroupMember.credentials,
});
firstDynamicGroupMemberDefaultLocationUrl =
firstDynamicGroupMemberMetadata?.defaultConferencingApp?.appLink ||
firstDynamicGroupMemberDwdConferencingAppLocation;
locationBodyString = firstDynamicGroupMemberDefaultLocationUrl || locationBodyString;
}
return {
locationBodyString,
organizerOrFirstDynamicGroupMemberDefaultLocationUrl: firstDynamicGroupMemberDefaultLocationUrl,
};
};
@@ -2,7 +2,9 @@ import type { Prisma } from "@prisma/client";
import type { IncomingMessage } from "http";
import type { Logger } from "tslog";
import { findQualifiedHosts } from "@calcom/lib/bookings/findQualifiedHosts";
import { findQualifiedHostsWithDwdCredentials } from "@calcom/lib/bookings/findQualifiedHostsWithDwdCredentials";
import { enrichUsersWithDwdCredentials } from "@calcom/lib/domainWideDelegation/server";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { HttpError } from "@calcom/lib/http-error";
import { getPiiFreeUser } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -12,6 +14,7 @@ import { userSelect } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import { SchedulingType } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import { loadUsers } from "./loadUsers";
import type { NewBookingEventType } from "./types";
@@ -22,6 +25,13 @@ type Users = (Awaited<ReturnType<typeof loadUsers>>[number] & {
createdAt?: Date;
})[];
export type UsersWithDwdCredentials = (Omit<Awaited<ReturnType<typeof loadUsers>>[number], "credentials"> & {
isFixed?: boolean;
metadata?: Prisma.JsonValue;
createdAt?: Date;
credentials: CredentialForCalendarService[];
})[];
type EventType = Pick<
NewBookingEventType,
| "hosts"
@@ -36,6 +46,7 @@ type EventType = Pick<
| "rrSegmentQueryValue"
| "isRRWeightsEnabled"
| "rescheduleWithSameRoundRobinHost"
| "teamId"
>;
type InputProps = {
@@ -60,7 +71,11 @@ export async function loadAndValidateUsers({
contactOwnerEmail,
rescheduleUid,
routingFormResponse,
}: InputProps): Promise<{ qualifiedRRUsers: Users; additionalFallbackRRUsers: Users; fixedUsers: Users }> {
}: InputProps): Promise<{
qualifiedRRUsers: UsersWithDwdCredentials;
additionalFallbackRRUsers: UsersWithDwdCredentials;
fixedUsers: UsersWithDwdCredentials;
}> {
let users: Users = await loadUsers({
eventType,
dynamicUserList,
@@ -68,6 +83,7 @@ export async function loadAndValidateUsers({
routedTeamMemberIds,
contactOwnerEmail,
});
const isDynamicAllowed = !users.some((user) => !user.allowDynamicBooking);
if (!isDynamicAllowed && !eventTypeId) {
logger.warn({
@@ -109,32 +125,51 @@ export async function loadAndValidateUsers({
? false
: user.isFixed || eventType.schedulingType !== SchedulingType.ROUND_ROBIN,
}));
const { qualifiedRRHosts, allFallbackRRHosts, fixedHosts } = await findQualifiedHosts({
const { qualifiedRRHosts, allFallbackRRHosts, fixedHosts } = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: routedTeamMemberIds || [],
rescheduleUid,
contactOwnerEmail,
routingFormResponse,
});
const allQualifiedHostsHashMap = [...qualifiedRRHosts, ...(allFallbackRRHosts ?? []), ...fixedHosts].reduce(
(acc, host) => {
if (host.user.id) {
return { ...acc, [host.user.id]: host };
}
return acc;
},
{} as {
[key: number]: Awaited<
ReturnType<typeof findQualifiedHostsWithDwdCredentials>
>["qualifiedRRHosts"][number];
}
);
let qualifiedRRUsers: Users = [];
let allFallbackRRUsers: Users = [];
let fixedUsers: Users = [];
let qualifiedRRUsers: UsersWithDwdCredentials = [];
let allFallbackRRUsers: UsersWithDwdCredentials = [];
let fixedUsers: UsersWithDwdCredentials = [];
if (qualifiedRRHosts.length) {
// remove users that are not in the qualified hosts array
const qualifiedHostIds = new Set(qualifiedRRHosts.map((qualifiedHost) => qualifiedHost.user.id));
qualifiedRRUsers = users.filter((user) => qualifiedHostIds.has(user.id));
qualifiedRRUsers = users
.filter((user) => qualifiedHostIds.has(user.id))
.map((user) => ({ ...user, credentials: allQualifiedHostsHashMap[user.id].user.credentials }));
}
if (allFallbackRRHosts?.length) {
const fallbackHostIds = new Set(allFallbackRRHosts.map((fallbackHost) => fallbackHost.user.id));
allFallbackRRUsers = users.filter((user) => fallbackHostIds.has(user.id));
allFallbackRRUsers = users
.filter((user) => fallbackHostIds.has(user.id))
.map((user) => ({ ...user, credentials: allQualifiedHostsHashMap[user.id].user.credentials }));
}
if (fixedHosts?.length) {
const fixedHostIds = new Set(fixedHosts.map((fixedHost) => fixedHost.user.id));
fixedUsers = users.filter((user) => fixedHostIds.has(user.id));
fixedUsers = users
.filter((user) => fixedHostIds.has(user.id))
.map((user) => ({ ...user, credentials: allQualifiedHostsHashMap[user.id].user.credentials }));
}
logger.debug(
@@ -148,9 +183,26 @@ export async function loadAndValidateUsers({
(fallbackUser) => !qualifiedRRUsers.find((qualifiedUser) => qualifiedUser.id === fallbackUser.id)
);
if (!qualifiedRRUsers.length && !fixedUsers.length) {
const firstUser = users[0];
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
memberId: firstUser.id ?? null,
teamId: eventType.teamId,
});
const usersEnrichedWithDwd = await enrichUsersWithDwdCredentials({
orgId: firstUserOrgId ?? null,
users,
});
return {
qualifiedRRUsers,
additionalFallbackRRUsers, // without qualified
fixedUsers: usersEnrichedWithDwd,
};
}
return {
qualifiedRRUsers,
additionalFallbackRRUsers, // without qualified
fixedUsers: !qualifiedRRUsers.length && !fixedUsers.length ? users : fixedUsers,
fixedUsers,
};
}
@@ -0,0 +1,760 @@
/**
* These tests are integration tests that test the flow from receiving a api/book/event request and then verifying
* - database entries created in In-MEMORY DB using prismock
* - emails sent by checking the testEmails global variable
* - webhooks fired by mocking fetch
* - APIs of various apps called by mocking those apps' modules
*
* They don't intend to test what the apps logic should do, but rather test if the apps are called with the correct data. For testing that, once should write tests within each app.
*/
import {
createBookingScenario,
TestData,
getDate,
getOrganizer,
getBooker,
getScenarioData,
mockSuccessfulVideoMeetingCreation,
mockCalendarToHaveNoBusySlots,
BookingLocations,
createDwdCredential,
createOrganization,
buildDwdCredential,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { createMockNextJsRequest } from "@calcom/web/test/utils/bookingScenario/createMockNextJsRequest";
import {
expectWorkflowToBeTriggered,
expectSuccessfulBookingCreationEmails,
expectBookingToBeInDatabase,
expectBookingCreatedWebhookToHaveBeenFired,
expectSuccessfulCalendarEventCreationInCalendar,
expectICalUIDAsString,
expectBookingToNotHaveReference,
expectNoAttemptToCreateCalendarEvent,
} from "@calcom/web/test/utils/bookingScenario/expects";
import {
getMockRequestDataForBooking,
getMockRequestDataForDynamicGroupBooking,
} from "@calcom/web/test/utils/bookingScenario/getMockRequestDataForBooking";
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
import { describe, expect } from "vitest";
import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { BookingStatus } from "@calcom/prisma/enums";
import { MembershipRole } from "@calcom/prisma/enums";
import { test } from "@calcom/web/test/fixtures/fixtures";
// Local test runs sometime gets too slow
const timeout = process.env.CI ? 5000 : 20000;
describe("handleNewBooking", () => {
setupAndTeardown();
describe("Domain Wide Delegation", () => {
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
3. Should use Google Meet as the location even when not explicitly set.
`,
async ({ emails }) => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
});
const payloadToMakePartOfOrganization = [
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: org.id,
name: "Test Org",
slug: "testorg",
},
},
];
const booker = getBooker({
email: "[email protected]",
name: "Booker",
});
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
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
teams: payloadToMakePartOfOrganization,
// No regular credentials provided
credentials: [],
destinationCalendar: TestData.selectedCalendars.google,
});
const dwd = await createDwdCredential(org.id);
const payloadToCreateUserEventTypeForOrganizer = {
id: 1,
slotInterval: 30,
length: 30,
users: [
{
id: organizer.id,
},
],
};
await createBookingScenario(
getScenarioData({
webhooks: [
{
userId: organizer.id,
eventTriggers: ["BOOKING_CREATED"],
subscriberUrl: "http://my-webhook.example.com",
active: true,
eventTypeId: 1,
appId: null,
},
],
workflows: [
{
userId: organizer.id,
trigger: "NEW_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [1],
},
],
eventTypes: [payloadToCreateUserEventTypeForOrganizer],
organizer,
apps: [TestData.apps["daily-video"], TestData.apps["google-calendar"]],
})
);
// Mock a Scenario where iCalUID isn't returned by Google Calendar in which case booking UID is used as the ics UID
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
id: "GOOGLE_CALENDAR_EVENT_ID",
uid: "MOCK_ID",
appSpecificData: {
googleCalendar: {
hangoutLink: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
},
},
},
});
const mockBookingData = getMockRequestDataForBooking({
data: {
eventTypeId: 1,
responses: {
email: booker.email,
name: booker.name,
location: { optionValue: "", value: BookingLocations.GoogleMeet },
},
},
});
const { req } = createMockNextJsRequest({
method: "POST",
body: mockBookingData,
});
const createdBooking = await handleNewBooking(req);
expect(createdBooking.responses).toEqual(
expect.objectContaining({
email: booker.email,
name: booker.name,
})
);
expect(createdBooking).toEqual(
expect.objectContaining({
location: BookingLocations.GoogleMeet,
})
);
await expectBookingToBeInDatabase({
description: "",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uid: createdBooking.uid!,
eventTypeId: mockBookingData.eventTypeId,
status: BookingStatus.ACCEPTED,
references: [
{
type: appStoreMetadata.googlecalendar.type,
uid: "GOOGLE_CALENDAR_EVENT_ID",
meetingId: "GOOGLE_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
// Verify DWD credential was used
domainWideDelegationCredentialId: dwd.id,
},
],
iCalUID: createdBooking.iCalUID,
});
expectWorkflowToBeTriggered({ emailsToReceive: [organizer.email], emails });
expectSuccessfulCalendarEventCreationInCalendar(calendarMock, {
credential: buildDwdCredential({ serviceAccountKey: dwd.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,
});
const iCalUID = expectICalUIDAsString(createdBooking.iCalUID);
expectSuccessfulBookingCreationEmails({
booking: {
uid: createdBooking.uid!,
},
booker,
organizer,
emails,
iCalUID,
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
organizer,
location: BookingLocations.GoogleMeet,
subscriberUrl: "http://my-webhook.example.com",
videoCallUrl: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
});
},
timeout
);
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
`,
async ({ emails }) => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
});
const payloadToMakePartOfOrganization = [
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: org.id,
name: "Test Org",
slug: "testorg",
},
},
];
const booker = getBooker({
email: "[email protected]",
name: "Booker",
});
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
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
teams: payloadToMakePartOfOrganization,
// No regular credentials provided
credentials: [],
destinationCalendar: TestData.selectedCalendars.office365,
});
const dwd = await createDwdCredential(org.id, "office365");
const payloadToCreateUserEventTypeForOrganizer = {
id: 1,
slotInterval: 30,
length: 30,
users: [
{
id: organizer.id,
},
],
};
await createBookingScenario(
getScenarioData({
webhooks: [
{
userId: organizer.id,
eventTriggers: ["BOOKING_CREATED"],
subscriberUrl: "http://my-webhook.example.com",
active: true,
eventTypeId: 1,
appId: null,
},
],
workflows: [
{
userId: organizer.id,
trigger: "NEW_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [1],
},
],
eventTypes: [payloadToCreateUserEventTypeForOrganizer],
organizer,
apps: [TestData.apps["daily-video"], TestData.apps["office365-calendar"]],
})
);
mockSuccessfulVideoMeetingCreation({
metadataLookupKey: "dailyvideo",
videoMeetingData: {
id: "MOCK_ID",
password: "MOCK_PASS",
url: `http://mock-dailyvideo.example.com/meeting-1`,
},
});
// Mock a Scenario where iCalUID isn't returned by Google Calendar in which case booking UID is used as the ics UID
const calendarMock = mockCalendarToHaveNoBusySlots("office365calendar", {
create: {
id: "OFFICE_365_CALENDAR_EVENT_ID",
uid: "MOCK_ID",
appSpecificData: {
office365Calendar: {
url: "http://mock-dailyvideo.example.com/meeting-1",
},
},
},
});
const mockBookingData = getMockRequestDataForBooking({
data: {
eventTypeId: 1,
responses: {
email: booker.email,
name: booker.name,
location: { optionValue: "", value: BookingLocations.CalVideo },
},
},
});
const { req } = createMockNextJsRequest({
method: "POST",
body: mockBookingData,
});
const createdBooking = await handleNewBooking(req);
expect(createdBooking.responses).toEqual(
expect.objectContaining({
email: booker.email,
name: booker.name,
})
);
expect(createdBooking).toEqual(
expect.objectContaining({
location: BookingLocations.CalVideo,
})
);
console.log("createdBooking", createdBooking);
await expectBookingToBeInDatabase({
description: "",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uid: createdBooking.uid!,
eventTypeId: mockBookingData.eventTypeId,
status: BookingStatus.ACCEPTED,
references: [
{
type: appStoreMetadata.dailyvideo.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASS",
meetingUrl: "http://mock-dailyvideo.example.com/meeting-1",
},
{
type: appStoreMetadata.office365calendar.type,
uid: "OFFICE_365_CALENDAR_EVENT_ID",
meetingId: "OFFICE_365_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://UNUSED_URL",
// Verify DWD credential was used
domainWideDelegationCredentialId: dwd.id,
},
],
iCalUID: createdBooking.iCalUID,
});
expectWorkflowToBeTriggered({ emailsToReceive: [organizer.email], emails });
expectSuccessfulCalendarEventCreationInCalendar(calendarMock, {
credential: buildDwdCredential({ serviceAccountKey: dwd.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,
});
const iCalUID = expectICalUIDAsString(createdBooking.iCalUID);
expectSuccessfulBookingCreationEmails({
booking: {
uid: createdBooking.uid!,
},
booker,
organizer,
emails,
iCalUID,
calendarType: "office365_calendar",
});
expectBookingCreatedWebhookToHaveBeenFired({
booker,
organizer,
location: BookingLocations.CalVideo,
subscriberUrl: "http://my-webhook.example.com",
videoCallUrl: `http://app.cal.local:3000/video/${createdBooking.uid}`,
});
},
timeout
);
test(
`should fail calendar event creation when organizer isn't part of the organization of DWD Credential`,
async () => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
withTeam: true,
});
const anotherOrg = await createOrganization({
name: "Another Org",
slug: "anotherorg",
});
const payloadToMakePartOfOrganization = [
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: org.id,
name: "Test Org",
slug: "testorg",
},
},
];
const booker = getBooker({
email: "[email protected]",
name: "Booker",
});
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
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
teams: payloadToMakePartOfOrganization,
// No regular credentials provided
credentials: [],
});
await createDwdCredential(anotherOrg.id);
const payloadToCreateUserEventTypeForOrganizer = {
id: 1,
slotInterval: 30,
length: 30,
users: [
{
id: organizer.id,
},
],
};
await createBookingScenario(
getScenarioData({
webhooks: [
{
userId: organizer.id,
eventTriggers: ["BOOKING_CREATED"],
subscriberUrl: "http://my-webhook.example.com",
active: true,
eventTypeId: 1,
appId: null,
},
],
workflows: [
{
userId: organizer.id,
trigger: "NEW_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [1],
},
],
eventTypes: [payloadToCreateUserEventTypeForOrganizer],
organizer,
apps: [TestData.apps["daily-video"]],
})
);
mockSuccessfulVideoMeetingCreation({
metadataLookupKey: "dailyvideo",
videoMeetingData: {
id: "MOCK_ID",
password: "MOCK_PASS",
url: `http://mock-dailyvideo.example.com/meeting-1`,
},
});
// Mock a Scenario where iCalUID isn't returned by Google Calendar in which case booking UID is used as the ics UID
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
id: "GOOGLE_CALENDAR_EVENT_ID",
uid: "MOCK_ID",
appSpecificData: {
googleCalendar: {
hangoutLink: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
},
},
},
});
const mockBookingData = getMockRequestDataForBooking({
data: {
eventTypeId: 1,
responses: {
email: booker.email,
name: booker.name,
location: { optionValue: "", value: BookingLocations.CalVideo },
},
},
});
const { req } = createMockNextJsRequest({
method: "POST",
body: mockBookingData,
});
const createdBooking = await handleNewBooking(req);
expect(createdBooking.responses).toEqual(
expect.objectContaining({
email: booker.email,
name: booker.name,
})
);
expect(createdBooking).toEqual(
expect.objectContaining({
location: BookingLocations.CalVideo,
})
);
expectNoAttemptToCreateCalendarEvent(calendarMock);
await expectBookingToBeInDatabase({
description: "",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uid: createdBooking.uid!,
eventTypeId: mockBookingData.eventTypeId,
status: BookingStatus.ACCEPTED,
references: [
{
type: appStoreMetadata.dailyvideo.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASS",
meetingUrl: "http://mock-dailyvideo.example.com/meeting-1",
},
],
iCalUID: createdBooking.iCalUID,
});
// Could not create calendar-event
expectBookingToNotHaveReference(createdBooking, {
type: appStoreMetadata.googlecalendar.type,
uid: "GOOGLE_CALENDAR_EVENT_ID",
});
},
timeout
);
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
3. Should use Google Meet as the location even when not explicitly set.
`,
async () => {
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
});
const payloadToMakePartOfOrganization = [
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: org.id,
name: "Test Org",
slug: "testorg",
},
},
];
const booker = getBooker({
email: "[email protected]",
name: "Booker",
});
const groupUser1 = getOrganizer({
name: "group-user-1",
username: "group-user-1",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
selectedCalendars: [TestData.selectedCalendars.google],
teams: payloadToMakePartOfOrganization,
credentials: [],
destinationCalendar: TestData.selectedCalendars.google,
});
const groupUser2 = getOrganizer({
name: "group-user-2",
username: "group-user-2",
email: "[email protected]",
id: 102,
schedules: [TestData.schedules.IstWorkHours],
selectedCalendars: [TestData.selectedCalendars.google],
teams: payloadToMakePartOfOrganization,
credentials: [],
destinationCalendar: TestData.selectedCalendars.google,
});
const dwd = await createDwdCredential(org.id);
await createBookingScenario(
getScenarioData({
webhooks: [
{
userId: groupUser1.id,
eventTriggers: ["BOOKING_CREATED"],
subscriberUrl: "http://my-webhook.example.com",
active: true,
eventTypeId: 0,
appId: null,
},
],
workflows: [
{
userId: groupUser1.id,
trigger: "NEW_EVENT",
action: "EMAIL_HOST",
template: "REMINDER",
activeOn: [0],
},
],
eventTypes: [],
users: [groupUser1, groupUser2],
apps: [TestData.apps["daily-video"], TestData.apps["google-calendar"]],
})
);
// Mock a Scenario where iCalUID isn't returned by Google Calendar in which case booking UID is used as the ics UID
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
create: {
id: "GOOGLE_CALENDAR_EVENT_ID",
uid: "MOCK_ID",
appSpecificData: {
googleCalendar: {
hangoutLink: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
},
},
},
});
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const mockBookingData = getMockRequestDataForDynamicGroupBooking({
data: {
start: `${plus1DateString}T05:00:00.000Z`,
end: `${plus1DateString}T05:30:00.000Z`,
eventTypeId: 0,
eventTypeSlug: "group-user-1+group-user-2",
user: "group-user-1+group-user-2",
responses: {
email: booker.email,
name: booker.name,
// There is no location option during booking for Dynamic Group Bookings
// location: { optionValue: "", value: BookingLocations.CalVideo },
},
},
});
const { req } = createMockNextJsRequest({
method: "POST",
body: mockBookingData,
});
const createdBooking = await handleNewBooking(req);
expect(createdBooking.responses).toEqual(
expect.objectContaining({
email: booker.email,
name: booker.name,
})
);
expect(createdBooking).toEqual(
expect.objectContaining({
location: BookingLocations.GoogleMeet,
})
);
await expectBookingToBeInDatabase({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uid: createdBooking.uid!,
eventTypeId: null,
status: BookingStatus.ACCEPTED,
location: BookingLocations.GoogleMeet,
references: [
{
type: appStoreMetadata.googlecalendar.type,
uid: "GOOGLE_CALENDAR_EVENT_ID",
meetingId: "GOOGLE_CALENDAR_EVENT_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
// Verify DWD credential was used
domainWideDelegationCredentialId: dwd.id,
},
],
iCalUID: createdBooking.iCalUID,
});
},
timeout
);
});
});
@@ -7,7 +7,7 @@ import type { DefaultEvent } from "@calcom/lib/defaultEvents";
import type { PaymentAppData } from "@calcom/lib/getPaymentAppData";
import type { userSelect } from "@calcom/prisma";
import type { SelectedCalendar } from "@calcom/prisma/client";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { Booking } from "./createBooking";
import type {
@@ -55,7 +55,7 @@ export interface IEventTypePaymentCredentialType {
export type IsFixedAwareUser = User & {
isFixed: boolean;
credentials: CredentialPayload[];
credentials: CredentialForCalendarService[];
organization?: { slug: string };
priority?: number;
weight?: number;
@@ -5,6 +5,8 @@ import { updateMeeting } from "@calcom/core/videoClient";
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 { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -12,7 +14,6 @@ import { getTranslation } from "@calcom/lib/server/i18n";
import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import prisma from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { bookingCancelAttendeeSeatSchema } from "@calcom/prisma/zod-utils";
import type { EventTypeMetadata } from "@calcom/prisma/zod-utils";
import type { CalendarEvent } from "@calcom/types/Calendar";
@@ -67,6 +68,12 @@ async function cancelAttendeeSeat(
(req as NextApiRequest).statusCode = 200;
const attendee = bookingToDelete?.attendees.find((attendee) => attendee.id === seatReference.attendeeId);
const bookingToDeleteUser = bookingToDelete.user ?? null;
const dwdCredentials = bookingToDeleteUser
? await getAllDwdCredentialsForUser({
user: { email: bookingToDeleteUser.email, id: bookingToDeleteUser.id },
})
: [];
if (attendee) {
/* If there are references then we should update them as well */
@@ -74,12 +81,13 @@ async function cancelAttendeeSeat(
const integrationsToUpdate = [];
for (const reference of bookingToDelete.references) {
if (reference.credentialId) {
const credential = await prisma.credential.findUnique({
where: {
id: reference.credentialId,
if (reference.credentialId || reference.domainWideDelegationCredentialId) {
const credential = await getDwdOrFindRegularCredential({
id: {
credentialId: reference.credentialId,
domainWideDelegationCredentialId: reference.domainWideDelegationCredentialId,
},
select: credentialForCalendarServiceSelect,
dwdCredentials,
});
if (credential) {
@@ -3,9 +3,10 @@ import type { Attendee } from "@prisma/client";
// eslint-disable-next-line no-restricted-imports
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { deleteMeeting } from "@calcom/core/videoClient";
import { getAllDwdCredentialsForUser } from "@calcom/lib/domainWideDelegation/server";
import { getDwdOrFindRegularCredential } from "@calcom/lib/domainWideDelegation/server";
import prisma from "@calcom/prisma";
import { BookingStatus } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { OriginalRescheduledBooking } from "../../handleNewBooking/types";
@@ -18,16 +19,23 @@ const lastAttendeeDeleteBooking = async (
originalBookingEvt?: CalendarEvent
) => {
let deletedReferences = false;
const bookingUser = originalRescheduledBooking?.user;
const dwdCredentials = bookingUser
? await getAllDwdCredentialsForUser({
user: { email: bookingUser.email, id: bookingUser.id },
})
: [];
if ((!filteredAttendees || filteredAttendees.length === 0) && originalRescheduledBooking) {
const integrationsToDelete = [];
for (const reference of originalRescheduledBooking.references) {
if (reference.credentialId) {
const credential = await prisma.credential.findUnique({
where: {
id: reference.credentialId,
if (reference.credentialId || reference.domainWideDelegationCredentialId) {
const credential = await getDwdOrFindRegularCredential({
id: {
credentialId: reference.credentialId,
domainWideDelegationCredentialId: reference.domainWideDelegationCredentialId,
},
select: credentialForCalendarServiceSelect,
dwdCredentials,
});
if (credential) {
@@ -1,7 +1,6 @@
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import prisma from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
import type { Calendar } from "@calcom/types/Calendar";
import { CalendarCacheRepository } from "./calendar-cache.repository";
@@ -10,9 +9,8 @@ import { CalendarCacheRepositoryMock } from "./calendar-cache.repository.mock";
export class CalendarCache {
static async initFromCredentialId(credentialId: number): Promise<ICalendarCacheRepository> {
const credential = await prisma.credential.findUnique({
where: { id: credentialId },
select: credentialForCalendarServiceSelect,
const credential = await CredentialRepository.findCredentialForCalendarServiceById({
id: credentialId,
});
const calendar = await getCalendar(credential);
return await CalendarCache.init(calendar);
+13 -1
View File
@@ -17,6 +17,7 @@ export type ICalendarSwitchProps = {
isLastItemInList?: boolean;
destination?: boolean;
credentialId: number;
domainWideDelegationCredentialId: string | null;
eventTypeId: number | null;
disabled?: boolean;
};
@@ -28,7 +29,17 @@ type EventCalendarSwitchProps = ICalendarSwitchProps & {
};
const CalendarSwitch = (props: ICalendarSwitchProps) => {
const { title, externalId, type, isChecked, name, credentialId, eventTypeId, disabled } = props;
const {
title,
externalId,
type,
isChecked,
name,
credentialId,
domainWideDelegationCredentialId,
eventTypeId,
disabled,
} = props;
const [checkedInternal, setCheckedInternal] = useState(isChecked);
const utils = trpc.useUtils();
const { t } = useLocale();
@@ -37,6 +48,7 @@ const CalendarSwitch = (props: ICalendarSwitchProps) => {
const body = {
integration: type,
externalId: externalId,
...(domainWideDelegationCredentialId && { domainWideDelegationCredentialId }),
// new URLSearchParams does not accept numbers
credentialId: String(credentialId),
...(eventTypeId ? { eventTypeId: String(eventTypeId) } : {}),
@@ -8,6 +8,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 { deletePayment } from "@calcom/lib/payment/deletePayment";
import { getTranslation } from "@calcom/lib/server/i18n";
import { bookingMinimalSelect, prisma } from "@calcom/prisma";
@@ -429,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(credential);
const calendar = await getCalendar(buildNonDwdCredential(credential));
const calendars = await calendar?.listCalendars();
@@ -1,59 +0,0 @@
import type { Prisma } from "@prisma/client";
type DomainWideDelegationSafeSelect = {
id: string;
enabled: boolean;
domain: string;
createdAt: Date;
updatedAt: Date;
organizationId: number;
workspacePlatform: {
name: string;
slug: string;
};
};
export interface IDomainWideDelegationRepository {
create(args: {
domain: string;
enabled: boolean;
organizationId: number;
workspacePlatformId: number;
serviceAccountKey: Exclude<Prisma.JsonValue, null>;
}): Promise<DomainWideDelegationSafeSelect | null>;
findById(args: { id: string }): Promise<DomainWideDelegationSafeSelect | null>;
findByIdIncludeSensitiveServiceAccountKey(args: {
id: string;
}): Promise<(DomainWideDelegationSafeSelect & { serviceAccountKey: any }) | null>;
findUniqueByOrganizationMemberEmail(args: {
email: string;
}): Promise<DomainWideDelegationSafeSelect | null>;
findByUser(args: { user: { email: string } }): Promise<DomainWideDelegationSafeSelect | null>;
updateById(args: {
id: string;
data: Partial<{
workspacePlatformId: number;
domain: string;
enabled: boolean;
organizationId: number;
}>;
}): Promise<DomainWideDelegationSafeSelect | null>;
deleteById(args: { id: string }): Promise<any>;
findDelegationsWithServiceAccount(args: { organizationId: number }): Promise<
(DomainWideDelegationSafeSelect & {
workspacePlatform: {
id: number;
name: string;
slug: string;
};
serviceAccountKey: any;
})[]
>;
}
@@ -1,38 +0,0 @@
import { DomainWideDelegationRepository } from "@calcom/lib/server/repository/domainWideDelegation";
import prisma from "@calcom/prisma";
import { MockDomainWideDelegationRepository } from "./mock-domain-wide-delegation.repository";
export class DomainWideDelegation {
static async checkIfDwDIsEnabled(userId: number, teamId: number | null) {
if (!teamId) {
return false;
}
const teamFeature = await prisma.teamFeatures.findFirst({
where: {
teamId: teamId,
featureId: "domain-wide-delegation",
},
});
const membership = await prisma.membership.findFirst({
where: {
userId: userId,
teamId: teamId,
accepted: true,
},
});
return !!(teamFeature && membership);
}
static async init(userId: number, teamId: number | null) {
const domainWideDelegationEnabled = await this.checkIfDwDIsEnabled(userId, teamId);
if (!domainWideDelegationEnabled) {
return new MockDomainWideDelegationRepository();
}
return new DomainWideDelegationRepository();
}
}
@@ -1,59 +0,0 @@
import type { Prisma } from "@prisma/client";
import type { IDomainWideDelegationRepository } from "./domain-wide-delegation-repository.interface";
export class MockDomainWideDelegationRepository implements IDomainWideDelegationRepository {
async create(_data: {
domain: string;
enabled: boolean;
organizationId: number;
workspacePlatformId: number;
serviceAccountKey: Exclude<Prisma.JsonValue, null>;
}) {
return null;
}
async findById(_args: { id: string }) {
return null;
}
async findByIdIncludeSensitiveServiceAccountKey(_args: { id: string }) {
return null;
}
async findUniqueByOrganizationMemberEmail(_args: { email: string }) {
return null;
}
async findByUser(_args: { user: { email: string } }) {
return null;
}
static async findAllByDomain(_args: { domain: string }) {
return [];
}
static async findFirstByOrganizationId(_args: { organizationId: number }) {
return null;
}
async updateById(_args: {
id: string;
data: Partial<{
workspacePlatformId: number;
domain: string;
enabled: boolean;
organizationId: number;
}>;
}) {
return null;
}
async deleteById(_args: { id: string }) {
return null;
}
async findDelegationsWithServiceAccount(_args: { organizationId: number }) {
return [];
}
}
@@ -289,12 +289,12 @@ function PlatformListItem({ platform, onEdit, onToggle }: Pick<Props, "platform"
onClick: () => onEdit(platform, "meta"),
icon: "pencil",
},
{
id: "edit-service-account",
label: t("edit_service_account"),
onClick: () => onEdit(platform, "serviceAccount"),
icon: "pencil",
},
// {
// id: "edit-service-account",
// label: t("edit_service_account"),
// onClick: () => onEdit(platform, "serviceAccount"),
// icon: "pencil",
// },
]}
/>
</div>
@@ -305,7 +305,7 @@ function PlatformListItem({ platform, onEdit, onToggle }: Pick<Props, "platform"
function CreatePlatformDialog({ isOpen, onOpenChange }: Pick<Props, "isOpen" | "onOpenChange">) {
const { t } = useLocale();
type FormValues = { name: string; description: string; slug: string; defaultServiceAccountKey: string };
type FormValues = { name: string; description: string; slug: string; defaultServiceAccountKey?: string };
const form = useForm<FormValues>({
defaultValues: {
name: "",
@@ -318,7 +318,7 @@ function CreatePlatformDialog({ isOpen, onOpenChange }: Pick<Props, "isOpen" | "
name: z.string(),
description: z.string(),
slug: z.string(),
defaultServiceAccountKey: z.string(),
defaultServiceAccountKey: z.string().optional(),
})
),
});
@@ -337,16 +337,27 @@ function CreatePlatformDialog({ isOpen, onOpenChange }: Pick<Props, "isOpen" | "
});
const onSubmit: SubmitHandler<FormValues> = (values) => {
const parsedKey = JSON.parse(values.defaultServiceAccountKey);
const validatedKey = serviceAccountKeySchema.safeParse(parsedKey);
if (!validatedKey.success) {
form.setError("defaultServiceAccountKey", { message: t("invalid_service_account_key") });
return;
// Only validate service account key if it's provided
if (values.defaultServiceAccountKey) {
const parsedKey = JSON.parse(values.defaultServiceAccountKey);
const validatedKey = serviceAccountKeySchema.safeParse(parsedKey);
if (!validatedKey.success) {
form.setError("defaultServiceAccountKey", { message: t("invalid_service_account_key") });
return;
}
addMutation.mutate({
...values,
defaultServiceAccountKey: validatedKey.data,
});
} else {
// Submit without service account key
addMutation.mutate({
name: values.name,
description: values.description,
slug: values.slug,
enabled: true,
});
}
addMutation.mutate({
...values,
defaultServiceAccountKey: validatedKey.data,
});
};
return (
@@ -419,7 +430,7 @@ function PlatformFormFields({ isCreate }: Pick<Props, "isCreate">) {
<TextField required label={t("name")} {...form.register("name")} />
<TextAreaField required label={t("description")} {...form.register("description")} />
{isCreate && <TextField required label={t("slug")} {...form.register("slug")} />}
{isCreate && <ServiceAccountFields />}
{isCreate && false && <ServiceAccountFields />}
</div>
);
}
@@ -4,6 +4,8 @@ import { useState } from "react";
import { useForm, Controller, useFormContext } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { ServiceAccountKey } from "@calcom/lib/server/serviceAccountKey";
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc/react";
import {
DropdownActions,
@@ -13,6 +15,7 @@ import {
DialogFooter,
Form,
TextField,
TextAreaField,
SelectField,
showToast,
Badge,
@@ -90,6 +93,7 @@ function DelegationListItemActions({
{
id: "delete",
label: t("delete"),
disabled: true,
onClick: () => onDelete(delegation.id),
icon: "trash",
},
@@ -126,31 +130,65 @@ function DelegationListItem({ delegation, toggleDelegation, onEdit, onDelete }:
);
}
type CreateDelegationData = {
domain: string;
workspacePlatformSlug: string;
enabled: boolean;
serviceAccountKey: ServiceAccountKey;
};
type CreateDelegationFormData = Omit<CreateDelegationData, "serviceAccountKey"> & {
serviceAccountKey: string;
};
type EditDelegationData = {
id: string;
domain: string;
workspacePlatformSlug: string;
enabled: boolean;
};
function CreateDelegationDialog({
isOpen,
onClose,
onSubmit,
workspacePlatforms,
handleCreate,
}: {
isOpen: boolean;
onClose: () => void;
onSubmit: (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => void;
workspacePlatforms: WorkspacePlatform[];
handleCreate: (data: CreateDelegationData) => void;
}) {
const { t } = useLocale();
const form = useForm<{ domain: string; workspacePlatformSlug: string; enabled: boolean }>({
defaultValues: {
domain: "",
workspacePlatformSlug: "",
},
});
const form = useForm<CreateDelegationFormData>();
const handleSubmit = (values: CreateDelegationFormData) => {
try {
const parsedKey = JSON.parse(values.serviceAccountKey);
const validatedKey = serviceAccountKeySchema.safeParse(parsedKey);
if (!validatedKey.success) {
form.setError("serviceAccountKey", { message: t("invalid_service_account_key") });
return;
}
handleCreate({
...values,
serviceAccountKey: validatedKey.data,
});
} catch (e) {
console.log("error", e);
form.setError("serviceAccountKey", { message: t("invalid_service_account_key") });
return;
}
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent enableOverflow title={t("add_domain_wide_delegation")}>
<Form form={form} handleSubmit={onSubmit}>
<DelegationFormFields workspacePlatforms={workspacePlatforms} />
<Form form={form} handleSubmit={handleSubmit}>
<DelegationFormFields workspacePlatforms={workspacePlatforms} isCreate={true} />
<DialogFooter>
<Button type="button" color="secondary" onClick={onClose}>
{t("cancel")}
@@ -167,19 +205,20 @@ function EditDelegationDialog({
isOpen,
onClose,
delegation,
onSubmit,
workspacePlatforms,
handleEdit,
}: {
isOpen: boolean;
onClose: () => void;
delegation: DelegationItemProps["delegation"];
onSubmit: (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => void;
workspacePlatforms: WorkspacePlatform[];
handleEdit: (data: EditDelegationData) => void;
}) {
const { t } = useLocale();
const form = useForm<{ domain: string; workspacePlatformSlug: string; enabled: boolean }>({
const form = useForm<EditDelegationData>({
defaultValues: {
id: delegation.id,
domain: delegation.domain,
workspacePlatformSlug: delegation.workspacePlatform.slug,
},
@@ -188,8 +227,8 @@ function EditDelegationDialog({
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent title={t("edit_domain_wide_delegation")}>
<Form form={form} handleSubmit={onSubmit}>
<DelegationFormFields workspacePlatforms={workspacePlatforms} />
<Form form={form} handleSubmit={handleEdit}>
<DelegationFormFields workspacePlatforms={workspacePlatforms} isCreate={false} />
<DialogFooter>
<Button type="button" color="secondary" onClick={onClose}>
{t("cancel")}
@@ -202,7 +241,13 @@ function EditDelegationDialog({
);
}
function DelegationFormFields({ workspacePlatforms }: { workspacePlatforms: WorkspacePlatform[] }) {
function DelegationFormFields({
workspacePlatforms,
isCreate,
}: {
workspacePlatforms: WorkspacePlatform[];
isCreate: boolean;
}) {
const { t } = useLocale();
const form = useFormContext();
return (
@@ -225,44 +270,18 @@ function DelegationFormFields({ workspacePlatforms }: { workspacePlatforms: Work
);
}}
/>
{isCreate && (
<TextAreaField
required
label={t("service_account_key")}
placeholder="{...}"
{...form.register("serviceAccountKey")}
/>
)}
</div>
);
}
function CreateEditDelegationDialog({
isOpen,
onClose,
delegation,
onSubmit,
workspacePlatforms,
}: {
isOpen: boolean;
onClose: () => void;
delegation: DelegationItemProps["delegation"] | null;
onSubmit: (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => void;
workspacePlatforms: WorkspacePlatform[];
}) {
if (delegation) {
return (
<EditDelegationDialog
isOpen={isOpen}
onClose={onClose}
delegation={delegation}
onSubmit={onSubmit}
workspacePlatforms={workspacePlatforms}
/>
);
}
return (
<CreateDelegationDialog
isOpen={isOpen}
onClose={onClose}
onSubmit={onSubmit}
workspacePlatforms={workspacePlatforms}
/>
);
}
function DomainWideDelegationList() {
const { t } = useLocale();
const utils = trpc.useContext();
@@ -336,15 +355,24 @@ function DomainWideDelegationList() {
const onCreateClick = () => setCreateEditDialog({ isOpen: true, delegation: null });
const handleSubmit = (data: { domain: string; workspacePlatformSlug: string; enabled: boolean }) => {
if (createEditDialog.delegation) {
updateMutation.mutate({
id: createEditDialog.delegation.id,
...data,
});
} else {
createMutation.mutate(data);
const handleCreate = (data: CreateDelegationData) => {
createMutation.mutate({
domain: data.domain,
workspacePlatformSlug: data.workspacePlatformSlug,
serviceAccountKey: data.serviceAccountKey,
});
setCreateEditDialog({ isOpen: false, delegation: null });
};
const handleEdit = (data: EditDelegationData) => {
if (!createEditDialog.delegation) {
return;
}
updateMutation.mutate({
id: createEditDialog.delegation.id,
domain: data.domain,
workspacePlatformSlug: data.workspacePlatformSlug,
});
setCreateEditDialog({ isOpen: false, delegation: null });
};
@@ -398,13 +426,22 @@ function DomainWideDelegationList() {
/>
)}
<CreateEditDelegationDialog
isOpen={createEditDialog.isOpen}
onClose={() => setCreateEditDialog({ isOpen: false, delegation: null })}
delegation={createEditDialog.delegation}
onSubmit={handleSubmit}
workspacePlatforms={enabledWorkspacePlatforms}
/>
{createEditDialog.delegation ? (
<EditDelegationDialog
isOpen={createEditDialog.isOpen}
onClose={() => setCreateEditDialog({ isOpen: false, delegation: null })}
delegation={createEditDialog.delegation}
workspacePlatforms={enabledWorkspacePlatforms}
handleEdit={handleEdit}
/>
) : (
<CreateDelegationDialog
isOpen={createEditDialog.isOpen}
onClose={() => setCreateEditDialog({ isOpen: false, delegation: null })}
workspacePlatforms={enabledWorkspacePlatforms}
handleCreate={handleCreate}
/>
)}
</div>
);
}
@@ -5,6 +5,8 @@ import { metadata as GoogleMeetMetadata } from "@calcom/app-store/googlevideo/_m
import { MeetLocationType } from "@calcom/app-store/locations";
import EventManager from "@calcom/core/EventManager";
import type { EventManagerInitParams } from "@calcom/core/EventManager";
import { getAllCredentials } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import type { EventType } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
import { getVideoCallDetails } from "@calcom/features/bookings/lib/handleNewBooking/getVideoCallDetails";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import logger from "@calcom/lib/logger";
@@ -13,6 +15,17 @@ import { BookingReferenceRepository } from "@calcom/lib/server/repository/bookin
import { prisma } from "@calcom/prisma";
import type { CalendarEvent, AdditionalInformation } from "@calcom/types/Calendar";
type InitParams = {
user: {
id: number;
name: string | null;
email: string;
username: string | null;
} & EventManagerInitParams["user"];
eventTypeAppMetadata?: EventManagerInitParams["eventTypeAppMetadata"];
eventType: EventType;
};
export const handleRescheduleEventManager = async ({
evt,
rescheduleUid,
@@ -30,7 +43,7 @@ export const handleRescheduleEventManager = async ({
newBookingId?: number;
changedOrganizer?: boolean;
previousHostDestinationCalendar?: DestinationCalendar[] | null;
initParams: EventManagerInitParams;
initParams: InitParams;
bookingLocation: string | null;
bookingId: number;
bookingICalUID?: string | null;
@@ -40,7 +53,12 @@ export const handleRescheduleEventManager = async ({
prefix: ["handleRescheduleEventManager", `${bookingId}`],
});
const eventManager = new EventManager(initParams.user, initParams?.eventTypeAppMetadata);
const allCredentials = await getAllCredentials(initParams.user, initParams?.eventType);
const eventManager = new EventManager(
{ ...initParams.user, credentials: allCredentials },
initParams?.eventTypeAppMetadata
);
const updateManager = await eventManager.reschedule(
evt,
@@ -21,6 +21,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 { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
@@ -274,6 +275,10 @@ export const roundRobinManualReassignment = async ({
include: { user: { select: { email: true } } },
});
const newUserWithCredentials = await enrichUserWithDwdCredentialsWithoutOrgId({
user: { ...newUser, credentials },
});
const previousHostDestinationCalendar = hasOrganizerChanged
? await prisma.destinationCalendar.findFirst({
where: { userId: originalOrganizer.id },
@@ -287,7 +292,8 @@ export const roundRobinManualReassignment = async ({
changedOrganizer: hasOrganizerChanged,
previousHostDestinationCalendar: previousHostDestinationCalendar ? [previousHostDestinationCalendar] : [],
initParams: {
user: { ...newUser, credentials },
user: newUserWithCredentials,
eventType,
},
bookingId,
bookingLocation,
@@ -22,6 +22,10 @@ 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 {
enrichHostsWithDwdCredentials,
enrichUserWithDwdCredentialsWithoutOrgId,
} from "@calcom/lib/domainWideDelegation/server";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import logger from "@calcom/lib/logger";
import { getLuckyUser } from "@calcom/lib/server/getLuckyUser";
@@ -115,8 +119,12 @@ export const roundRobinReassignment = async ({
const previousRRHostT = await getTranslation(previousRRHost?.locale || "en", "common");
const eventTypeHosts = await enrichHostsWithDwdCredentials({
orgId,
hosts: eventType.hosts,
});
// Filter out the current attendees of the booking from the event type
const availableEventTypeUsers = eventType.hosts.reduce((availableUsers, host) => {
const availableEventTypeUsers = eventTypeHosts.reduce((availableUsers, host) => {
if (!attendeeEmailsSet.has(host.user.email) && host.user.email !== originalOrganizer.email) {
availableUsers.push({ ...host.user, isFixed: host.isFixed, priority: host?.priority ?? 2 });
}
@@ -136,7 +144,7 @@ export const roundRobinReassignment = async ({
const reassignedRRHost = await getLuckyUser({
availableUsers,
eventType,
allRRHosts: eventType.hosts.filter((host) => !host.isFixed), // todo: only use hosts from virtual queue
allRRHosts: eventTypeHosts.filter((host) => !host.isFixed), // todo: only use hosts from virtual queue
routingFormResponse: null,
});
@@ -312,6 +320,10 @@ export const roundRobinReassignment = async ({
},
});
const organizerWithCredentials = await enrichUserWithDwdCredentialsWithoutOrgId({
user: { ...organizer, credentials },
});
const { evtWithAdditionalInfo } = await handleRescheduleEventManager({
evt,
rescheduleUid: booking.uid,
@@ -319,7 +331,8 @@ export const roundRobinReassignment = async ({
changedOrganizer: hasOrganizerChanged,
previousHostDestinationCalendar: previousHostDestinationCalendar ? [previousHostDestinationCalendar] : [],
initParams: {
user: { ...organizer, credentials: [...credentials] },
user: organizerWithCredentials,
eventType,
},
bookingId,
bookingLocation,
+41
View File
@@ -0,0 +1,41 @@
export class CalendarAppError extends Error {
constructor(message: string) {
super(message);
this.name = "CalendarAppError";
}
}
export class CalendarAppDomainWideDelegationError extends CalendarAppError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationError";
}
}
export class CalendarAppDomainWideDelegationConfigurationError extends CalendarAppDomainWideDelegationError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationConfigurationError";
}
}
export class CalendarAppDomainWideDelegationInvalidGrantError extends CalendarAppDomainWideDelegationError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationInvalidGrantError";
}
}
export class CalendarAppDomainWideDelegationClientIdNotAuthorizedError extends CalendarAppDomainWideDelegationConfigurationError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationClientIdNotAuthorizedError";
}
}
export class CalendarAppDomainWideDelegationNotSetupError extends CalendarAppDomainWideDelegationConfigurationError {
constructor(message: string) {
super(message);
this.name = "CalendarAppDomainWideDelegationNotSetupError";
}
}
@@ -4,6 +4,8 @@ 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";
type EnabledApp = ReturnType<typeof getApps>[number] & { enabled: boolean };
/**
@@ -30,6 +32,10 @@ const getEnabledAppsFromCredentials = async (
},
} satisfies Prisma.AppWhereInput;
const dwdCredentialsWithAppId = credentials
.filter((credential) => isDwdCredential({ credentialId: credential.id }))
.filter((credential): credential is typeof credential & { appId: string } => credential.appId !== null);
if (filterOnCredentials) {
const userIds: number[] = [],
teamIds: number[] = [];
@@ -48,10 +54,23 @@ const getEnabledAppsFromCredentials = async (
...(filterOnIds.credentials.some.OR.length && filterOnIds),
};
const enabledApps = await prisma.app.findMany({
let enabledApps = await prisma.app.findMany({
where,
select: { slug: true, enabled: true },
});
const dwdSupportedEnabledApps = await prisma.app.findMany({
where: {
enabled: true,
slug: {
in: dwdCredentialsWithAppId.map((credential) => credential.appId),
},
},
select: { slug: true, enabled: true },
});
enabledApps = [...enabledApps, ...dwdSupportedEnabledApps];
const apps = getApps(credentials, filterOnCredentials);
const filteredApps = apps.reduce((reducedArray, app) => {
const appDbQuery = enabledApps.find((metadata) => metadata.slug === app.slug);
@@ -1,6 +1,6 @@
import logger from "@calcom/lib/logger";
import type { SelectedCalendar } from "@calcom/prisma/client";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import type { RoutingFormResponse } from "../server/getLuckyUser";
import { getOrderedListOfLuckyUsers } from "../server/getLuckyUser";
@@ -12,7 +12,7 @@ export const errorCodes = {
type BaseUser = {
id: number;
email: string;
credentials: CredentialPayload[];
credentials: CredentialForCalendarService[];
userLevelSelectedCalendars: SelectedCalendar[];
} & Record<string, unknown>;
@@ -6,7 +6,7 @@ import type { Mock } from "vitest";
import { SchedulingType } from "@calcom/prisma/enums";
import { filterHostsByLeadThreshold } from "./filterHostsByLeadThreshold";
import { findQualifiedHosts } from "./findQualifiedHosts";
import { findQualifiedHostsWithDwdCredentials } from "./findQualifiedHostsWithDwdCredentials";
import * as getRoutedUsers from "./getRoutedUsers";
// Mock the filterHostsByLeadThreshold function
@@ -21,7 +21,7 @@ afterEach(() => {
(filterHostsByLeadThreshold as Mock).mockClear();
});
describe("findQualifiedHosts", async () => {
describe("findQualifiedHostsWithDwdCredentials", async () => {
it("should return qualified hosts based on mock of filterHostsByLeadThreshold", async () => {
const hosts = [
{
@@ -88,7 +88,7 @@ describe("findQualifiedHosts", async () => {
};
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: null,
@@ -139,7 +139,7 @@ describe("findQualifiedHosts", async () => {
};
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: null,
@@ -225,7 +225,7 @@ describe("findQualifiedHosts", async () => {
};
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: null,
@@ -313,7 +313,7 @@ describe("findQualifiedHosts", async () => {
};
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [1],
rescheduleUid: null,
@@ -390,7 +390,7 @@ describe("findQualifiedHosts", async () => {
};
prismaMock.booking.findFirst.mockResolvedValue({ userId: 2 });
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [],
rescheduleUid: "recheduleUid",
@@ -464,12 +464,12 @@ describe("findQualifiedHosts", async () => {
},
};
vi.spyOn(getRoutedUsers, "findMatchingHostsWithEventSegment").mockImplementation(async () => [hosts[0]]);
const filterSpy = vi.spyOn(Array.prototype, "filter");
const findMatchingHostsSpy = vi
.spyOn(getRoutedUsers, "findMatchingHostsWithEventSegment")
.mockImplementation(async () => [hosts[0]]);
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [0, 1, 2],
rescheduleUid: null,
@@ -477,14 +477,23 @@ describe("findQualifiedHosts", async () => {
routingFormResponse: null,
});
// check if we returned early after segment matching only returned one host
expect(filterSpy).toHaveBeenCalledTimes(2);
// Verify the result
expect(result).toEqual({
qualifiedRRHosts: [hosts[0]],
fixedHosts: [],
});
// Verify that findMatchingHostsWithEventSegment was called with correct parameters
expect(findMatchingHostsSpy).toHaveBeenCalledWith({
eventType,
hosts: hosts.filter((host) => !host.isFixed), // Only round-robin hosts should be passed
});
// Verify that filterHostsByLeadThreshold was not called since we returned early
expect(filterHostsByLeadThreshold).not.toHaveBeenCalled();
// Verify that allFallbackRRHosts is not present in the result
expect(result).not.toHaveProperty("allFallbackRRHosts");
});
it("should filter for segment matching and routed team member ids", async () => {
@@ -553,7 +562,7 @@ describe("findQualifiedHosts", async () => {
]);
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [2, 3],
rescheduleUid: null,
@@ -652,7 +661,7 @@ describe("findQualifiedHosts", async () => {
(filterHostsByLeadThreshold as Mock).mockResolvedValue(rrHostsAfterFairness);
// Call the function under test
const result = await findQualifiedHosts({
const result = await findQualifiedHostsWithDwdCredentials({
eventType,
routedTeamMemberIds: [2, 3],
rescheduleUid: null,
@@ -1,8 +1,11 @@
import { findMatchingHostsWithEventSegment, getNormalizedHosts } from "@calcom/lib/bookings/getRoutedUsers";
import {
findMatchingHostsWithEventSegment,
getNormalizedHostsWithDwdCredentials,
} from "@calcom/lib/bookings/getRoutedUsers";
import type { EventType } from "@calcom/lib/bookings/getRoutedUsers";
import type { SelectedCalendar } from "@calcom/prisma/client";
import type { SchedulingType } from "@calcom/prisma/enums";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import type { RoutingFormResponse } from "../server/getLuckyUser";
import { filterHostsByLeadThreshold } from "./filterHostsByLeadThreshold";
@@ -43,7 +46,7 @@ const isFixedHost = <T extends { isFixed: boolean }>(host: T): host is T & { isF
return host.isFixed;
};
export const findQualifiedHosts = async <
export const findQualifiedHostsWithDwdCredentials = async <
T extends {
email: string;
id: number;
@@ -76,14 +79,14 @@ export const findQualifiedHosts = async <
createdAt: Date | null;
priority?: number | null;
weight?: number | null;
user: T;
user: Omit<T, "credentials"> & { credentials: CredentialForCalendarService[] };
}[];
fixedHosts: {
isFixed: boolean;
createdAt: Date | null;
priority?: number | null;
weight?: number | null;
user: T;
user: Omit<T, "credentials"> & { credentials: CredentialForCalendarService[] };
}[];
// all hosts we want to fallback to including the qualifiedRRHosts (fairness + crm contact owner)
allFallbackRRHosts?: {
@@ -91,10 +94,14 @@ export const findQualifiedHosts = async <
createdAt: Date | null;
priority?: number | null;
weight?: number | null;
user: T;
user: Omit<T, "credentials"> & { credentials: CredentialForCalendarService[] };
}[];
}> => {
const { hosts: normalizedHosts, fallbackHosts: fallbackUsers } = getNormalizedHosts({ eventType });
const { hosts: normalizedHosts, fallbackHosts: fallbackUsers } = await getNormalizedHostsWithDwdCredentials(
{
eventType,
}
);
// not a team event type, or some other reason - segment matching isn't necessary.
if (!normalizedHosts) {
const fixedHosts = fallbackUsers.filter(isFixedHost);
+63
View File
@@ -3,6 +3,10 @@ import { findTeamMembersMatchingAttributeLogic } from "@calcom/lib/raqb/findTeam
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
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 getOrgIdFromMemberOrTeamId from "../getOrgIdFromMemberOrTeamId";
const log = logger.getSubLogger({ prefix: ["[getRoutedUsers]"] });
@@ -113,6 +117,65 @@ export function getNormalizedHosts<User extends BaseUser, Host extends BaseHost<
};
}
}
type BaseUserWithCredentialPayload = BaseUser & { credentials: CredentialPayload[] };
export async function getNormalizedHostsWithDwdCredentials<
User extends BaseUserWithCredentialPayload,
Host extends BaseHost<User>
>({
eventType,
}: {
eventType: {
schedulingType: SchedulingType | null;
hosts?: Host[];
users: User[];
teamId?: number;
};
}) {
if (eventType.hosts?.length && eventType.schedulingType) {
const hostsWithoutDwd = eventType.hosts.map((host) => ({
isFixed: host.isFixed,
user: host.user,
priority: host.priority,
weight: host.weight,
createdAt: host.createdAt,
}));
const firstHost = hostsWithoutDwd[0];
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
memberId: firstHost?.user?.id ?? null,
teamId: eventType.teamId,
});
const hostsEnrichedWithDwd = await enrichHostsWithDwdCredentials({
orgId: firstUserOrgId ?? null,
hosts: hostsWithoutDwd ?? null,
});
return {
hosts: hostsEnrichedWithDwd,
fallbackHosts: null,
};
} else {
const hostsWithoutDwd = eventType.users.map((user) => {
return {
isFixed: !eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE,
email: user.email,
user: user,
createdAt: null,
};
});
const firstHost = hostsWithoutDwd[0];
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
memberId: firstHost?.user?.id ?? null,
teamId: eventType.teamId,
});
const hostsEnrichedWithDwd = await enrichHostsWithDwdCredentials({
orgId: firstUserOrgId ?? null,
hosts: hostsWithoutDwd ?? null,
});
return {
hosts: null,
fallbackHosts: hostsEnrichedWithDwd,
};
}
}
// We don't allow fixed hosts when segment matching is enabled
// If this ever changes, we need to update this function and return fixed hosts
+3
View File
@@ -142,6 +142,9 @@ export const CREDENTIAL_SYNC_SECRET_HEADER_NAME =
export const CREDENTIAL_SYNC_ENDPOINT = process.env.CALCOM_CREDENTIAL_SYNC_ENDPOINT;
// Service Account Encryption Key for encrypting/decrypting service account keys
export const SERVICE_ACCOUNT_ENCRYPTION_KEY = process.env.CALCOM_SERVICE_ACCOUNT_ENCRYPTION_KEY;
export const DEFAULT_LIGHT_BRAND_COLOR = "#292929";
export const DEFAULT_DARK_BRAND_COLOR = "#fafafa";
@@ -0,0 +1,27 @@
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;
})[];
};
@@ -0,0 +1,612 @@
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
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 { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import { SMSLockState } from "@calcom/prisma/enums";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import {
getAllDwdCredentialsForUser,
buildAllCredentials,
getDwdOrRegularCredential,
enrichUsersWithDwdCredentials,
enrichHostsWithDwdCredentials,
enrichUserWithDwdCredentialsWithoutOrgId,
enrichUserWithDwdConferencingCredentialsWithoutOrgId,
} from "./server";
// Mock OrganizationRepository
vi.mock("@calcom/lib/server/repository/organization", () => ({
OrganizationRepository: {
findByMemberEmail: vi.fn(),
},
}));
// Mock DomainWideDelegationRepository
vi.mock("@calcom/lib/server/repository/domainWideDelegation", () => ({
DomainWideDelegationRepository: {
findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey: vi.fn(),
findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey: vi.fn(),
},
}));
const mockUser = {
email: "[email protected]",
id: 123,
};
const mockServiceAccountKey: ServiceAccountKey = {
client_email: "[email protected]",
client_id: "123456789",
private_key: "-----BEGIN PRIVATE KEY-----\nMIIE....\n-----END PRIVATE KEY-----\n",
};
const mockWorkspacePlatform = {
name: "Test Platform",
slug: "google",
};
const mockDwd = {
id: "dwd-1",
enabled: true,
domain: "example.com",
organizationId: 1,
serviceAccountKey: mockServiceAccountKey,
workspacePlatform: mockWorkspacePlatform,
createdAt: new Date(),
updatedAt: new Date(),
};
// Mock organization data
const mockOrganization = {
id: 1,
name: "Test Org",
metadata: {},
bio: null,
timeZone: "UTC",
weekStart: "Monday",
hideBranding: false,
theme: null,
timeFormat: null,
brandColor: null,
darkBrandColor: null,
createdAt: new Date(),
includeManagedEventsInLimits: false,
smsLockState: SMSLockState.LOCKED,
smsLockReviewedByAdmin: false,
slug: "test-org",
logoUrl: null,
bannerUrl: null,
isPrivate: false,
isOrganization: true,
isOrganizationVerified: true,
isOrganizationConfigured: true,
isOrganizationAdminReviewed: true,
orgAutoAcceptEmail: "example.com",
orgProfileRedirectsToVerifiedDomain: false,
allowSEOIndexing: true,
calVideoLogo: null,
appLogo: null,
appIconLogo: null,
hideBookATeamMember: false,
hideTeam: false,
hideCalendarNotes: false,
eventTypeMatchParentTeam: false,
lockEventTypeCreationForUsers: false,
parentId: null,
pendingPayment: false,
isPlatform: false,
createdByOAuthClientId: null,
bookingLimits: null,
};
// Credential Builders
const buildDwdCredential = (overrides = {}) => ({
type: "google_calendar",
appId: "google-calendar",
id: -1,
delegatedToId: mockDwd.id,
userId: mockUser.id,
user: { email: mockUser.email },
key: { access_token: "NOOP_UNUSED_DELEGATION_TOKEN" },
invalid: false,
teamId: null,
team: null,
delegatedTo: {
serviceAccountKey: mockServiceAccountKey,
},
...overrides,
});
const buildDwdGoogleCalendarCredential = (overrides = {}) => ({
...buildDwdCredential({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
}),
...overrides,
});
const buildDwdGoogleMeetCredential = (overrides = {}) => ({
...buildDwdCredential({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
}),
...overrides,
});
const buildRegularCredential = (overrides = {}): CredentialForCalendarService => ({
type: "google_calendar",
appId: "google-calendar",
id: 1,
userId: mockUser.id,
user: { email: mockUser.email },
key: JSON.stringify(mockServiceAccountKey),
invalid: false,
teamId: null,
delegatedToId: null,
delegatedTo: null,
...overrides,
});
const buildRegularGoogleCalendarCredential = (overrides = {}): CredentialPayload => ({
...buildRegularCredential({
appId: "google-calendar",
type: "google_calendar",
}),
...overrides,
});
const buildMockWorkspacePlatform = (overrides: Partial<typeof mockWorkspacePlatform> = {}) => ({
name: "Test Platform",
slug: "google",
...overrides,
});
const buildMockDwd = (overrides: Partial<typeof mockDwd> = {}) => ({
...mockDwd,
workspacePlatform: buildMockWorkspacePlatform(overrides.workspacePlatform || {}),
...overrides,
});
describe("getAllDwdCredentialsForUser", () => {
setupAndTeardown();
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(OrganizationRepository.findByMemberEmail).mockResolvedValue(mockOrganization);
});
it("should return empty array when no DWD found", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await getAllDwdCredentialsForUser({ user: mockUser });
expect(result).toEqual([]);
});
it("should return empty array when DWD is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
const result = await getAllDwdCredentialsForUser({ user: mockUser });
expect(result).toEqual([]);
});
it("should return credentials for enabled Google DWD", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await getAllDwdCredentialsForUser({ user: mockUser });
expect(result).toHaveLength(2);
expect(result).toEqual([buildDwdGoogleCalendarCredential(), buildDwdGoogleMeetCredential()]);
});
it("should return empty array for non-Google platforms(as they are not supported yet)", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(
buildMockDwd({
workspacePlatform: {
name: "Microsoft",
slug: "microsoft",
},
})
);
const result = await getAllDwdCredentialsForUser({ user: mockUser });
expect(result).toEqual([]);
});
});
describe("buildAllCredentials", () => {
const mockDwdGoogleCalendarCred = buildDwdGoogleCalendarCredential();
const mockRegularGoogleCalendarCred = buildRegularGoogleCalendarCredential();
it("should combine DWD and regular credentials", () => {
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred],
existingCredentials: [mockRegularGoogleCalendarCred],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDwdGoogleCalendarCred);
expect(result).toContainEqual(mockRegularGoogleCalendarCred);
});
it("should deduplicate DWD credentials with same delegatedToId and appId", () => {
const duplicateDwdCredential = buildDwdGoogleCalendarCredential();
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred, duplicateDwdCredential],
existingCredentials: [],
});
expect(result).toHaveLength(1);
expect(result[0]).toEqual(mockDwdGoogleCalendarCred);
});
it("should keep DWD credentials with same delegatedToId but different appId", () => {
const differentAppDwdCredential = buildDwdGoogleMeetCredential();
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred, differentAppDwdCredential],
existingCredentials: [],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDwdGoogleCalendarCred);
expect(result).toContainEqual(differentAppDwdCredential);
});
it("should filter out DWD credentials from existingCredentials", () => {
const dwdCalendarCredential = buildRegularGoogleCalendarCredential({ id: -2 });
const result = buildAllCredentials({
dwdCredentials: [mockDwdGoogleCalendarCred],
existingCredentials: [mockRegularGoogleCalendarCred, dwdCalendarCredential],
});
expect(result).toHaveLength(2);
expect(result).toContainEqual(mockDwdGoogleCalendarCred);
expect(result).toContainEqual(mockRegularGoogleCalendarCred);
});
});
describe("getDwdOrRegularCredential", () => {
const mockDwdGoogleCalendarCred = buildDwdGoogleCalendarCredential();
const mockRegularGoogleCalendarCred = buildRegularGoogleCalendarCredential();
const credentials = [mockDwdGoogleCalendarCred, mockRegularGoogleCalendarCred];
it("should find DWD credential by dwdId", () => {
const result = getDwdOrRegularCredential({
credentials,
id: { credentialId: null, dwdId: mockDwd.id },
});
expect(result).toEqual(mockDwdGoogleCalendarCred);
});
it("should find regular credential by credentialId", () => {
const result = getDwdOrRegularCredential({
credentials,
id: { credentialId: mockRegularGoogleCalendarCred.id, dwdId: null },
});
expect(result).toEqual(mockRegularGoogleCalendarCred);
});
it("should return null when no matching credential found", () => {
const result = getDwdOrRegularCredential({
credentials,
id: { credentialId: 999, dwdId: null },
});
expect(result).toBeNull();
});
it("should not match null to null for delegatedToId", () => {
const result = getDwdOrRegularCredential({
credentials,
id: { credentialId: null, dwdId: null },
});
expect(result).toBeNull();
});
});
describe("enrichUsersWithDwdCredentials", () => {
const mockUsers = [
{
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
},
{
id: 456,
email: "[email protected]",
credentials: [buildRegularGoogleCalendarCredential({ id: 2 })],
},
];
beforeEach(() => {
vi.clearAllMocks();
});
it("should return users as is when orgId is null", async () => {
const result = await enrichUsersWithDwdCredentials({
orgId: null,
users: mockUsers,
});
expect(result).toEqual(
mockUsers.map((user) => ({
...user,
credentials: user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
}))
);
});
it("should enrich users with DWD credentials when available", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await enrichUsersWithDwdCredentials({
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).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
})
);
expect(enrichedUser.credentials).toContainEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
});
it("should not add DWD credentials when DWD is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
const result = await enrichUsersWithDwdCredentials({
orgId: 1,
users: mockUsers,
});
expect(result).toEqual(
mockUsers.map((user) => ({
...user,
credentials: user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
}))
);
});
});
describe("enrichHostsWithDwdCredentials", () => {
const mockHosts = [
{
user: {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
},
metadata: { key: "value" },
},
{
user: {
id: 456,
email: "[email protected]",
credentials: [buildRegularGoogleCalendarCredential({ id: 2 })],
},
metadata: { key: "value2" },
},
];
beforeEach(() => {
vi.clearAllMocks();
});
it("should return hosts as is when orgId is null", async () => {
const result = await enrichHostsWithDwdCredentials({
orgId: null,
hosts: mockHosts,
});
expect(result).toEqual(
mockHosts.map((host) => ({
...host,
user: {
...host.user,
credentials: host.user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
},
}))
);
});
it("should enrich hosts with DWD credentials when available", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await enrichHostsWithDwdCredentials({
orgId: 1,
hosts: mockHosts,
});
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).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
})
);
expect(enrichedHost.user.credentials).toContainEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
});
it("should not add DWD credentials when DWD is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
const result = await enrichHostsWithDwdCredentials({
orgId: 1,
hosts: mockHosts,
});
expect(result).toEqual(
mockHosts.map((host) => ({
...host,
user: {
...host.user,
credentials: host.user.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
},
}))
);
});
});
describe("enrichUserWithDwdCredentialsWithoutOrgId", () => {
const mockUserWithCredentials = {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
};
beforeEach(() => {
vi.clearAllMocks();
});
it("should enrich user with DWD credentials when available", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await enrichUserWithDwdCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result.credentials).toHaveLength(3); // 1 regular + 2 DWD (calendar + meet)
expect(result.credentials).toContainEqual(
expect.objectContaining({
type: googleCalendarMetadata.type,
appId: googleCalendarMetadata.slug,
})
);
expect(result.credentials).toContainEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
it("should not add DWD credentials when DWD is not found", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await enrichUserWithDwdCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result).toEqual({
...mockUserWithCredentials,
credentials: mockUserWithCredentials.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
});
});
it("should not add DWD credentials when DWD is disabled", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd({ enabled: false }));
const result = await enrichUserWithDwdCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result).toEqual({
...mockUserWithCredentials,
credentials: mockUserWithCredentials.credentials.map((cred) => ({
...cred,
delegatedTo: null,
delegatedToId: null,
})),
});
});
});
describe("enrichUserWithDwdConferencingCredentialsWithoutOrgId", () => {
const mockUserWithCredentials = {
...mockUser,
credentials: [buildRegularGoogleCalendarCredential()],
};
beforeEach(() => {
vi.clearAllMocks();
});
it("should only return conferencing credentials", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(buildMockDwd());
const result = await enrichUserWithDwdConferencingCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result.credentials).toHaveLength(1); // Only Google Meet
expect(result.credentials[0]).toEqual(
expect.objectContaining({
type: googleMeetMetadata.type,
appId: googleMeetMetadata.slug,
})
);
});
it("should return empty credentials array when no conferencing credentials found", async () => {
vi.mocked(
DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
).mockResolvedValue(null);
const result = await enrichUserWithDwdConferencingCredentialsWithoutOrgId({
user: mockUserWithCredentials,
});
expect(result.credentials).toEqual([]);
});
});
+459
View File
@@ -0,0 +1,459 @@
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { metadata as googleCalendarMetadata } from "@calcom/app-store/googlecalendar/_metadata";
import { metadata as googleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
import { metadata as office365CalendarMetaData } from "@calcom/app-store/office365calendar/_metadata";
import { metadata as office365VideoMetaData } from "@calcom/app-store/office365video/_metadata";
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 { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
import { buildNonDwdCredentials, isDwdCredential } from "./clientAndServer";
export { buildNonDwdCredentials, buildNonDwdCredential } 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 {
id: string;
workspacePlatform: {
slug: string;
};
serviceAccountKey: ServiceAccountKey | null;
}
interface DomainWideDelegationWithSensitiveServiceAccountKey extends DomainWideDelegation {
serviceAccountKey: ServiceAccountKey;
}
interface User {
email: string;
id: number;
}
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) => {
switch (slug) {
case GOOGLE_WORKSPACE_SLUG:
return isConferencing
? { type: googleMeetMetadata.type, appId: googleMeetMetadata.slug }
: { type: googleCalendarMetadata.type, appId: googleCalendarMetadata.slug };
case OFFICE365_WORKSPACE_SLUG:
return isConferencing
? { type: office365VideoMetaData.type, appId: office365VideoMetaData.slug }
: { type: office365CalendarMetaData.type, appId: office365CalendarMetaData.slug };
default:
throw new Error("App metadata does not exist");
}
};
const _isConferencingCredential = (credential: CredentialPayload) => {
return (
credential.type.endsWith("_video") ||
credential.type.endsWith("_conferencing") ||
credential.type.endsWith("_messaging")
);
};
const _buildCommonUserCredential = ({ dwd, user }: { dwd: DomainWideDelegation; user: User }) => {
return {
id: -1,
delegatedToId: dwd.id,
userId: user.id,
user: {
email: user.email,
},
key: {
access_token: "NOOP_UNUSED_DELEGATION_TOKEN",
},
invalid: false,
teamId: null,
team: null,
delegatedTo: dwd.serviceAccountKey
? {
serviceAccountKey: dwd.serviceAccountKey,
}
: null,
};
};
const _buildDwdCalendarCredential = ({ dwd, user }: { dwd: DomainWideDelegation; user: User }) => {
log.debug("buildDomainWideDelegationCredential", safeStringify({ dwd, user }));
// TODO: Build for other platforms as well
if (!isValidWorkspaceSlug(dwd.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
dwd.workspacePlatform.slug
}`
);
return null;
}
return {
...getDwdAppMetadata(dwd.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE, false),
..._buildCommonUserCredential({ dwd, user }),
};
};
const _buildDwdCalendarCredentialWithServiceAccountKey = ({
dwd,
user,
}: {
dwd: DomainWideDelegationWithSensitiveServiceAccountKey;
user: User;
}) => {
const credential = _buildDwdCalendarCredential({ dwd, user });
if (!credential) {
return null;
}
return {
...credential,
delegatedTo: {
serviceAccountKey: dwd.serviceAccountKey,
},
};
};
const _buildDwdConferencingCredential = ({ dwd, user }: { dwd: DomainWideDelegation; user: User }) => {
// TODO: Build for other platforms as well
if (!isValidWorkspaceSlug(dwd.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
dwd.workspacePlatform.slug
}`
);
return null;
}
return {
...getDwdAppMetadata(dwd.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE, true),
..._buildCommonUserCredential({ dwd, user }),
};
};
/**
* Gets calendar as well as conferencing credentials(stored in-memory) for the user from the corresponding enabled DomainWideDelegation.
*/
export async function getAllDwdCredentialsForUser({ 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({
email: user.email,
});
if (!dwd || !dwd.enabled) {
return [];
}
const domainWideDelegationCredentials = [
_buildDwdCalendarCredential({ dwd, user }),
_buildDwdConferencingCredential({ dwd, user }),
].filter((credential): credential is NonNullable<typeof credential> => credential !== null);
log.debug("Returned", safeStringify({ domainWideDelegationCredentials }));
return domainWideDelegationCredentials;
}
export async function getAllDwdCalendarCredentialsForUser({ user }: { user: { email: string; id: number } }) {
const dwdCredentials = await getAllDwdCredentialsForUser({ user });
return dwdCredentials.filter((credential) => credential.type.endsWith("_calendar"));
}
async function _getDwdCredentialsMapPerUser({
organizationId,
users,
}: {
organizationId: number | null;
users: User[];
}) {
const emptyMap = new Map<number, NonNullable<ReturnType<typeof _buildDwdCalendarCredential>>[]>();
if (!organizationId) {
return emptyMap;
}
const domain = users[0].email.split("@")[1];
log.debug("called with", safeStringify({ users }));
const dwd =
await DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
{
organizationId,
domain,
}
);
if (!dwd || !dwd.enabled) {
return emptyMap;
}
const credentialsByUserId = new Map<
number,
NonNullable<ReturnType<typeof _buildDwdCalendarCredential>>[]
>();
for (const user of users) {
const domainWideDelegationCredentials = [
_buildDwdCalendarCredential({ dwd, user }),
_buildDwdConferencingCredential({ dwd, user }),
].filter((credential): credential is NonNullable<typeof credential> => credential !== null);
log.debug("Returned for user", safeStringify({ user, domainWideDelegationCredentials }));
credentialsByUserId.set(user.id, domainWideDelegationCredentials);
}
return credentialsByUserId;
}
export async function checkIfSuccessfullyConfiguredInWorkspace({
dwd,
user,
}: {
dwd: DomainWideDelegationWithSensitiveServiceAccountKey;
user: User;
}) {
if (!isValidWorkspaceSlug(dwd.workspacePlatform.slug)) {
log.warn(
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
dwd.workspacePlatform.slug
}`
);
return false;
}
const credential = _buildDwdCalendarCredentialWithServiceAccountKey({
dwd,
user,
});
const calendar = await getCalendar(credential);
if (!calendar) {
throw new Error("Google Calendar App not found");
}
return await calendar?.testDomainWideDelegationSetup?.();
}
export async function getAllDwdCredentialsForUserByAppType({
user,
appType,
}: {
user: User;
appType: string;
}) {
const dwdCredentials = await getAllDwdCredentialsForUser({
user,
});
return dwdCredentials.filter((credential) => credential.type === appType);
}
export async function getAllDwdCredentialsForUserByAppSlug({
user,
appSlug,
}: {
user: User;
appSlug: string;
}) {
const dwdCredentials = await getAllDwdCredentialsForUser({ user });
return dwdCredentials.filter((credential) => credential.appId === appSlug);
}
type Host<TUser extends { id: number; email: string; credentials: CredentialPayload[] }> = {
user: TUser;
};
/**
* Prepares credentials for use by CalendarService and EventManager
* - Ensures no duplicate dwd credentials caused by enrichment at possibly multiple places
*/
export const buildAllCredentials = ({
dwdCredentials,
existingCredentials,
}: {
dwdCredentials: CredentialForCalendarService[];
existingCredentials: CredentialPayload[];
}) => {
const nonDwdCredentials = existingCredentials.filter((cred) => !isDwdCredential({ credentialId: cred.id }));
const allCredentials: CredentialForCalendarService[] = [
...dwdCredentials,
...buildNonDwdCredentials(nonDwdCredentials),
];
const uniqueAllCredentials = allCredentials.reduce((acc, credential) => {
if (!credential.delegatedToId) {
// Regular credential go as is
acc.push(credential);
return acc;
}
const existingDwdCredential = acc.find(
(c) => c.delegatedToId === credential.delegatedToId && c.appId === credential.appId
);
if (!existingDwdCredential) {
acc.push(credential);
}
return acc;
}, [] as typeof allCredentials);
return uniqueAllCredentials;
};
export async function enrichUsersWithDwdCredentials<
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({ orgId, users }: { orgId: number | null; users: TUser[] }) {
const dwdCredentialsMap = await _getDwdCredentialsMapPerUser({
organizationId: orgId,
users,
});
const enrichedUsers = users.map((user) => {
const { credentials, ...rest } = user;
const enrichedCredentials = buildAllCredentials({
dwdCredentials: dwdCredentialsMap.get(user.id) ?? [],
existingCredentials: credentials,
});
return {
...rest,
credentials: enrichedCredentials,
};
});
log.debug("enrichUsersWithDwdCredentials", safeStringify({ enrichedUsers, orgId }));
return enrichedUsers;
}
export const enrichHostsWithDwdCredentials = async <
THost extends Host<TUser>,
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({
orgId,
hosts,
}: {
orgId: number | null;
hosts: THost[];
}) => {
const dwdCredentialsMap = await _getDwdCredentialsMapPerUser({
organizationId: orgId,
users: hosts.map((host) => host.user),
});
const enrichedHosts = hosts.map((host) => {
const { credentials, ...restUser } = host.user;
return {
...host,
user: {
...restUser,
credentials: buildAllCredentials({
dwdCredentials: dwdCredentialsMap.get(restUser.id) ?? [],
existingCredentials: credentials,
}),
},
};
});
log.debug("enrichHostsWithDwdCredentials", safeStringify({ enrichedHosts, orgId }));
return enrichedHosts;
};
export const enrichUserWithDwdCredentialsWithoutOrgId = async <
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({
user,
}: {
user: TUser;
}) => {
const dwdCredentials = await getAllDwdCredentialsForUser({ user });
const { credentials, ...restUser } = user;
return {
...restUser,
credentials: buildAllCredentials({
dwdCredentials: dwdCredentials,
existingCredentials: credentials,
}),
};
};
export async function enrichUserWithDwdConferencingCredentialsWithoutOrgId<
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
>({ user }: { user: TUser }) {
const { credentials, ...restUser } = await enrichUserWithDwdCredentialsWithoutOrgId({ user });
return {
...restUser,
credentials: credentials.filter(_isConferencingCredential),
};
}
/**
* Either get DWD credential from dwdCredentials or find regular credential from Credential table
*/
export async function getDwdOrFindRegularCredential({
id,
dwdCredentials,
}: {
id: {
credentialId: number | null | undefined;
domainWideDelegationCredentialId: string | null | undefined;
};
dwdCredentials: CredentialForCalendarService[];
}) {
return id.domainWideDelegationCredentialId
? dwdCredentials.find((cred) => cred.delegatedToId === id.domainWideDelegationCredentialId)
: id.credentialId
? await CredentialRepository.findCredentialForCalendarServiceById({
id: id.credentialId,
})
: null;
}
/**
* Utility function to find a credential from a list of credentials, supporting both regular and DWD credentials
*/
export function getDwdOrRegularCredential<TCredential extends { delegatedToId?: string | null; id: number }>({
credentials,
id,
}: {
credentials: TCredential[];
id: { credentialId: number | null | undefined; dwdId: string | null | undefined };
}) {
return (
credentials.find((cred) => {
// Ensure that we don't match null to null
if (cred.delegatedToId) {
return cred.delegatedToId === id.dwdId;
} else if (id.credentialId) {
return cred.id === id.credentialId;
}
return false;
}) || null
);
}
export function getFirstDwdConferencingCredential({
credentials,
}: {
credentials: CredentialForCalendarService[];
}) {
return credentials.find((credential) => _isConferencingCredential(credential));
}
export function getFirstDwdConferencingCredentialAppLocation({
credentials,
}: {
credentials: CredentialForCalendarService[];
}) {
const dwdConferencingCredential = getFirstDwdConferencingCredential({ credentials });
if (dwdConferencingCredential?.appId === googleMeetMetadata.slug) {
return googleMeetMetadata.appData?.location?.type ?? null;
}
if (dwdConferencingCredential?.appId === office365VideoMetaData.slug) {
return office365VideoMetaData.appData?.location?.type ?? null;
}
return null;
}
+12 -4
View File
@@ -11,9 +11,10 @@ import { MembershipRole } from "@calcom/prisma/enums";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TeamQuery } from "@calcom/trpc/server/routers/loggedInViewer/integrations.handler";
import type { TIntegrationsInputSchema } from "@calcom/trpc/server/routers/loggedInViewer/integrations.schema";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { PaymentApp } from "@calcom/types/PaymentService";
import { buildNonDwdCredentials } from "./domainWideDelegation/clientAndServer";
export type ConnectedApps = Awaited<ReturnType<typeof getConnectedApps>>;
export async function getConnectedApps({
@@ -21,7 +22,7 @@ export async function getConnectedApps({
prisma,
input,
}: {
user: Pick<User, "id" | "name" | "avatarUrl"> & { avatar?: string };
user: Pick<User, "id" | "name" | "avatarUrl" | "email"> & { avatar?: string };
prisma: PrismaClient;
input: TIntegrationsInputSchema;
}) {
@@ -33,6 +34,7 @@ export async function getConnectedApps({
extendsFeature,
teamId,
sortByMostPopular,
sortByInstalledFirst,
appId,
} = input;
let credentials = await getUsersCredentials(user);
@@ -103,8 +105,8 @@ export async function getConnectedApps({
userTeams = [...teamsQuery, ...parentTeams];
const teamAppCredentials: CredentialPayload[] = userTeams.flatMap((teamApp) => {
return teamApp.credentials ? teamApp.credentials.flat() : [];
const teamAppCredentials = userTeams.flatMap((teamApp) => {
return teamApp.credentials ? buildNonDwdCredentials(teamApp.credentials.flat()) : [];
});
if (!includeTeamInstalledApps || teamId) {
credentials = teamAppCredentials;
@@ -226,6 +228,12 @@ export async function getConnectedApps({
});
}
if (sortByInstalledFirst) {
apps.sort((a, b) => {
return (a.isInstalled ? 0 : 1) - (b.isInstalled ? 0 : 1);
});
}
return {
items: apps,
};
@@ -1,4 +1,6 @@
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import logger from "@calcom/lib/logger";
import type { PrismaClient } from "@calcom/prisma";
import prisma from "@calcom/prisma";
@@ -14,7 +16,7 @@ const log = logger.getSubLogger({ prefix: ["getConnectedDestinationCalendarsAndE
type ReturnTypeGetConnectedCalendars = Awaited<ReturnType<typeof getConnectedCalendars>>;
type ConnectedCalendarsFromGetConnectedCalendars = ReturnTypeGetConnectedCalendars["connectedCalendars"];
export type UserWithCalendars = Pick<User, "id"> & {
export type UserWithCalendars = Pick<User, "id" | "email"> & {
allSelectedCalendars: Pick<SelectedCalendar, "externalId" | "integration" | "eventTypeId">[];
userLevelSelectedCalendars: Pick<SelectedCalendar, "externalId" | "integration" | "eventTypeId">[];
destinationCalendar: DestinationCalendar | null;
@@ -24,6 +26,51 @@ export type ConnectedDestinationCalendars = Awaited<
ReturnType<typeof getConnectedDestinationCalendarsAndEnsureDefaultsInDb>
>;
/**
* 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
*/
const _ensureNoConflictingNonDwdConnectedCalendar = <
T extends {
integration: { slug: string };
primary?: { email?: string | null | undefined } | undefined;
domainWideDelegationCredentialId?: string | null | undefined;
}
>({
connectedCalendars,
loggedInUser,
}: {
connectedCalendars: T[];
loggedInUser: { email: string };
}) => {
return connectedCalendars.filter((connectedCalendar, index, array) => {
const allCalendarsWithSameAppSlug = array.filter(
(cal) => cal.integration.slug === connectedCalendar.integration.slug
);
// If no other calendar with this slug, keep it
if (allCalendarsWithSameAppSlug.length === 1) return true;
const dwdCalendarsWithSameAppSlug = allCalendarsWithSameAppSlug.filter(
(cal) => cal.domainWideDelegationCredentialId
);
if (!dwdCalendarsWithSameAppSlug.length) {
return true;
}
if (connectedCalendar.domainWideDelegationCredentialId) {
return true;
}
// DWD Credential is always of the loggedInUser
if (!connectedCalendar.primary?.email || connectedCalendar.primary.email !== loggedInUser.email) {
return true;
}
return false;
});
};
async function handleNoConnectedCalendars(user: UserWithCalendars) {
log.debug(`No connected calendars, deleting destination calendar if it exists for user ${user.id}`);
@@ -69,6 +116,7 @@ async function handleNoDestinationCalendar({
integration = "",
externalId = "",
credentialId,
domainWideDelegationCredentialId,
email: primaryEmail,
} = connectedCalendars[0].primary ?? {};
@@ -91,8 +139,14 @@ async function handleNoDestinationCalendar({
userId: user.id,
integration,
externalId,
credentialId,
primaryEmail,
...(!isDwdCredential({ credentialId })
? {
credentialId,
}
: {
domainWideDelegationCredentialId,
}),
},
});
@@ -231,9 +285,13 @@ export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
select: credentialForCalendarServiceSelect,
});
const { credentials: allCredentials } = await enrichUserWithDwdCredentialsWithoutOrgId({
user: { id: user.id, email: user.email, credentials: userCredentials },
});
const selectedCalendars = getSelectedCalendars({ user, eventTypeId: eventTypeId ?? null });
// get user's credentials + their connected integrations
const calendarCredentials = getCalendarCredentials(userCredentials);
const calendarCredentials = getCalendarCredentials(allCredentials);
// get all the connected integrations' calendars (from third party)
const getConnectedCalendarsResult = await getConnectedCalendars(
@@ -305,8 +363,12 @@ export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
});
}
return {
const noConflictingNonDwdConnectedCalendars = _ensureNoConflictingNonDwdConnectedCalendar({
connectedCalendars,
loggedInUser: { email: user.email },
});
return {
connectedCalendars: noConflictingNonDwdConnectedCalendars,
destinationCalendar: {
...(user.destinationCalendar as DestinationCalendar),
...destinationCalendar,
+6 -2
View File
@@ -9,6 +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 { getBookerBaseUrl } from "../getBookerUrl/server";
async function getEventType(id: number) {
@@ -102,9 +103,12 @@ export async function getBooking(bookingId: number) {
const eventType = { ...eventTypeRaw, metadata: EventTypeMetaDataSchema.parse(eventTypeRaw?.metadata) };
const { user } = booking;
const { user: userWithoutDwdCredentials } = booking;
if (!user) throw new HttpCode({ statusCode: 204, message: "No user found" });
if (!userWithoutDwdCredentials) throw new HttpCode({ statusCode: 204, message: "No user found" });
const user = await enrichUserWithDwdCredentialsWithoutOrgId({
user: userWithoutDwdCredentials,
});
const t = await getTranslation(user.locale ?? "en", "common");
const attendeesListPromises = booking.attendees.map(async (attendee) => {
@@ -0,0 +1,28 @@
import { isDwdCredential } from "@calcom/lib/domainWideDelegation/clientAndServer";
export function buildCredentialPayloadForPrisma({
credentialId,
domainWideDelegationCredentialId,
}: {
credentialId: number | null | undefined;
domainWideDelegationCredentialId: string | null | undefined;
}) {
if (credentialId === undefined) {
return {
credentialId,
domainWideDelegationCredentialId,
};
}
if (isDwdCredential({ credentialId })) {
return {
credentialId: null,
domainWideDelegationCredentialId,
};
} else {
return {
credentialId,
domainWideDelegationCredentialId: null,
};
}
}
@@ -0,0 +1,29 @@
import type { Prisma } from "@prisma/client";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { availabilityUserSelect } from "@calcom/prisma";
import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { withSelectedCalendars } from "./withSelectedCalendars";
export async function findUsersForAvailabilityCheck({ where }: { where: Prisma.UserWhereInput }) {
const user = await prisma.user.findFirst({
where,
select: {
...availabilityUserSelect,
selectedCalendars: true,
credentials: {
select: credentialForCalendarServiceSelect,
},
},
});
if (!user) {
return null;
}
return await enrichUserWithDwdCredentialsWithoutOrgId({
user: withSelectedCalendars(user),
});
}
@@ -9,6 +9,7 @@ import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = {
id: SessionUser["id"];
email: SessionUser["email"];
metadata: SessionUser["metadata"];
};
+3 -3
View File
@@ -15,7 +15,7 @@ import type { SelectedCalendar } from "@calcom/prisma/client";
import type { AttributeType } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
import type { EventBusyDate } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { CredentialForCalendarService } from "@calcom/types/Credential";
import { mergeOverlappingRanges } from "../date-ranges";
@@ -69,7 +69,7 @@ interface GetLuckyUserParams<T extends PartialUser> {
user: {
id: number;
email: string;
credentials: CredentialPayload[];
credentials: CredentialForCalendarService[];
userLevelSelectedCalendars: SelectedCalendar[];
};
createdAt: Date;
@@ -381,7 +381,7 @@ async function getCurrentMonthCalendarBusyTimes(
usersWithCredentials: {
id: number;
email: string;
credentials: CredentialPayload[];
credentials: CredentialForCalendarService[];
userLevelSelectedCalendars: SelectedCalendar[];
}[]
): Promise<{ userId: number; busyTimes: (EventBusyDate & { timeZone?: string })[] }[]> {
+17 -3
View File
@@ -2,9 +2,14 @@ import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = { id: SessionUser["id"] };
import { enrichUserWithDwdCredentialsWithoutOrgId } from "../domainWideDelegation/server";
type SessionUser = NonNullable<TrpcSessionUser>;
type User = { id: SessionUser["id"]; email: SessionUser["email"] };
/**
* It includes in-memory DWD credentials as well.
*/
export async function getUsersCredentials(user: User) {
const credentials = await prisma.credential.findMany({
where: {
@@ -15,5 +20,14 @@ export async function getUsersCredentials(user: User) {
id: "asc",
},
});
return credentials;
const { credentials: allCredentials } = await enrichUserWithDwdCredentialsWithoutOrgId({
user: {
email: user.email,
id: user.id,
credentials,
},
});
return allCredentials;
}
@@ -0,0 +1,341 @@
import prismock from "../../../../../tests/libs/__mocks__/prisma";
import { describe, expect, it, beforeEach, vi } from "vitest";
import { encryptServiceAccountKey } from "@calcom/lib/server/serviceAccountKey";
import { DomainWideDelegationRepository } from "../domainWideDelegation";
import { OrganizationRepository } from "../organization";
vi.mock("../organization", () => ({
OrganizationRepository: {
findByMemberEmail: vi.fn(),
},
}));
// Mock service account key functions
vi.mock("@calcom/lib/crypto", async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const actual = await importOriginal<any>();
return {
...actual,
symmetricEncrypt: vi.fn((serviceAccountKey) => {
console.log({ mockEncrypted: serviceAccountKey });
return `encrypted(${serviceAccountKey})`;
}),
symmetricDecrypt: vi.fn((serviceAccountKey) => {
return serviceAccountKey.replace(/^encrypted\((.*)\)$/, "$1");
}),
};
});
// Test Data Helpers
const buildMockServiceAccountKey = () => ({
client_email: "[email protected]",
private_key: "private-key",
client_id: "client-id",
additional_field: "value",
});
const buildMockEncryptedServiceAccountKey = () => ({
client_email: "[email protected]",
client_id: "client-id",
encrypted_credentials: 'encrypted({"private_key":"private-key"})',
additional_field: "value",
});
const buildMockWorkspacePlatform = () => ({
id: 1,
name: "Test Platform",
slug: "test-platform",
});
const buildMockOrganization = () => ({
id: 1,
name: "Test Organization",
isOrganization: true,
});
const buildMockDomainWideDelegation = (overrides = {}) => ({
id: "test-id",
enabled: true,
domain: "example.com",
organizationId: 1,
workspacePlatformId: 1,
serviceAccountKey: buildMockServiceAccountKey(),
workspacePlatform: buildMockWorkspacePlatform(),
...overrides,
});
// Test Utilities
const createTestDomainWideDelegation = async (overrides = {}) => {
// Create organization first (as a team with isOrganization true)
await prismock.team.create({
data: buildMockOrganization(),
});
// Create workspace platform
await prismock.workspacePlatform.create({
data: buildMockWorkspacePlatform(),
});
const data = buildMockDomainWideDelegation(overrides);
return await prismock.domainWideDelegation.create({
data: {
...data,
serviceAccountKey: encryptServiceAccountKey(data.serviceAccountKey),
},
include: {
workspacePlatform: true,
},
});
};
const setupOrganizationMock = (returnValue: any) => {
vi.mocked(OrganizationRepository.findByMemberEmail).mockResolvedValue(returnValue);
};
describe("DomainWideDelegationRepository", () => {
beforeEach(() => {
prismock.domainWideDelegation.deleteMany();
prismock.workspacePlatform.deleteMany();
prismock.team.deleteMany();
vi.clearAllMocks();
});
describe("Service Account Key Access Control", () => {
beforeEach(async () => {
await createTestDomainWideDelegation();
});
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" });
expect(result).not.toHaveProperty("serviceAccountKey");
expect(result).toEqual(
expect.objectContaining({
id: "test-id",
enabled: true,
domain: "example.com",
})
);
});
});
describe("findAllByDomain", () => {
it("should not expose service account key in any of the results", async () => {
const results = await DomainWideDelegationRepository.findAllByDomain({ domain: "example.com" });
expect(results.length).toBeGreaterThan(0);
results.forEach((result) => {
expect(result).not.toHaveProperty("serviceAccountKey");
expect(result).toEqual(
expect.objectContaining({
domain: "example.com",
})
);
});
});
});
});
describe("Sensitive Methods (With Service Account Key)", () => {
describe("findByIdIncludeSensitiveServiceAccountKey", () => {
it("should expose valid service account key", async () => {
const result = await DomainWideDelegationRepository.findByIdIncludeSensitiveServiceAccountKey({
id: "test-id",
});
expect(result).toHaveProperty("serviceAccountKey");
expect(result?.serviceAccountKey).toEqual(buildMockServiceAccountKey());
});
});
describe("findByOrgIdIncludeSensitiveServiceAccountKey", () => {
it("should expose validated service account keys", async () => {
const results = await DomainWideDelegationRepository.findByOrgIdIncludeSensitiveServiceAccountKey({
organizationId: 1,
});
expect(results.length).toEqual(1);
const result = results[0];
expect(result).toHaveProperty("serviceAccountKey");
expect(result.serviceAccountKey).toEqual(buildMockEncryptedServiceAccountKey());
});
});
describe("findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey", () => {
it("should expose validated service account key", async () => {
const result =
await DomainWideDelegationRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
{
organizationId: 1,
domain: "example.com",
}
);
expect(result).toHaveProperty("serviceAccountKey");
expect(result?.serviceAccountKey).toEqual(buildMockServiceAccountKey());
});
});
describe("findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey", () => {
it("should return valid delegation when email exists in organization", async () => {
setupOrganizationMock({ id: 1 });
const result =
await DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
email: "[email protected]",
});
expect(result).toHaveProperty("serviceAccountKey");
expect(result?.serviceAccountKey).toEqual(buildMockServiceAccountKey());
expect(result?.domain).toBe("example.com");
});
it("should return null when email not found in any organization", async () => {
setupOrganizationMock(null);
const result =
await DomainWideDelegationRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
email: "[email protected]",
});
expect(result).toBeNull();
});
});
});
});
describe("CRUD Operations", () => {
describe("create", () => {
it("should store domain wide delegation with all required fields and establish connections", async () => {
// Create organization first (as a team with isOrganization true)
await prismock.team.create({
data: buildMockOrganization(),
});
// Create workspace platform
const workspacePlatform = await prismock.workspacePlatform.create({
data: buildMockWorkspacePlatform(),
});
const data = buildMockDomainWideDelegation();
delete data.id; // ID is auto-generated
delete data.workspacePlatform; // Don't include the relation in create
const result = await DomainWideDelegationRepository.create(data);
expect(result).toEqual({
id: expect.any(String),
domain: data.domain,
enabled: data.enabled,
createdAt: expect.any(Date),
updatedAt: null,
organizationId: data.organizationId,
workspacePlatform: {
name: workspacePlatform.name,
slug: workspacePlatform.slug,
},
});
});
});
describe("update", () => {
it("should modify workspace platform connection when workspacePlatformId is provided", async () => {
const created = await createTestDomainWideDelegation();
// Create new workspace platform
const newWorkspacePlatform = await prismock.workspacePlatform.create({
data: {
id: 2,
name: "New Platform",
slug: "new-platform",
},
});
const result = await DomainWideDelegationRepository.updateById({
id: created.id,
data: { workspacePlatformId: newWorkspacePlatform.id },
});
expect(result).toEqual({
id: created.id,
domain: created.domain,
enabled: created.enabled,
createdAt: expect.any(Date),
updatedAt: null,
organizationId: created.organizationId,
workspacePlatform: {
name: newWorkspacePlatform.name,
slug: newWorkspacePlatform.slug,
},
});
});
it("should modify organization connection when organizationId is provided", async () => {
const created = await createTestDomainWideDelegation();
// Create new organization (as a team with isOrganization true)
const newOrganization = await prismock.team.create({
data: {
id: 2,
name: "New Organization",
isOrganization: true,
},
});
const result = await DomainWideDelegationRepository.updateById({
id: created.id,
data: { organizationId: newOrganization.id },
});
expect(result).toEqual({
id: created.id,
domain: created.domain,
enabled: created.enabled,
createdAt: expect.any(Date),
updatedAt: null,
organizationId: newOrganization.id,
workspacePlatform: {
name: expect.any(String),
slug: expect.any(String),
},
});
});
it("should modify specified fields while preserving others", async () => {
const created = await createTestDomainWideDelegation();
const result = await DomainWideDelegationRepository.updateById({
id: created.id,
data: { enabled: false },
});
expect(result).toEqual(
expect.objectContaining({
id: created.id,
enabled: false, // Changed
domain: created.domain, // Preserved
})
);
});
});
describe("delete", () => {
it("should remove the domain wide delegation completely", async () => {
const created = await createTestDomainWideDelegation();
await DomainWideDelegationRepository.deleteById({ id: created.id });
const result = await prismock.domainWideDelegation.findUnique({
where: { id: created.id },
});
expect(result).toBeNull();
});
});
});
});
+33 -4
View File
@@ -1,5 +1,8 @@
import { prisma } from "@calcom/prisma";
import { safeCredentialSelect } from "@calcom/prisma/selects/credential";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import { buildNonDwdCredential } from "../../domainWideDelegation/server";
type CredentialCreateInput = {
type: string;
@@ -10,24 +13,36 @@ type CredentialCreateInput = {
export class CredentialRepository {
static async create(data: CredentialCreateInput) {
return await prisma.credential.create({ data: { ...data } });
const credential = await prisma.credential.create({ data: { ...data } });
return buildNonDwdCredential(credential);
}
static async findByAppIdAndUserId({ appId, userId }: { appId: string; userId: number }) {
const credential = await prisma.credential.findFirst({
where: {
appId,
userId,
},
});
return buildNonDwdCredential(credential);
}
/**
* Doesn't retrieve key field as that has credentials
*/
static async findFirstByIdWithUser({ id }: { id: number }) {
return await prisma.credential.findFirst({ where: { id }, select: safeCredentialSelect });
const credential = await prisma.credential.findFirst({ where: { id }, select: safeCredentialSelect });
return buildNonDwdCredential(credential);
}
/**
* Includes 'key' field which is sensitive data.
*/
static async findFirstByIdWithKeyAndUser({ id }: { id: number }) {
return await prisma.credential.findFirst({
const credential = await prisma.credential.findFirst({
where: { id },
select: { ...safeCredentialSelect, key: true },
});
return buildNonDwdCredential(credential);
}
static async findFirstByAppIdAndUserId({ appId, userId }: { appId: string; userId: number }) {
@@ -40,10 +55,24 @@ export class CredentialRepository {
}
static async findFirstByUserIdAndType({ userId, type }: { userId: number; type: string }) {
return await prisma.credential.findFirst({ where: { userId, type } });
const credential = await prisma.credential.findFirst({ where: { userId, type } });
return buildNonDwdCredential(credential);
}
static async deleteById({ id }: { id: number }) {
await prisma.credential.delete({ where: { id } });
}
static async findCredentialForCalendarServiceById({ id }: { id: number }) {
const dbCredential = await prisma.credential.findUnique({
where: { id },
select: credentialForCalendarServiceSelect,
});
if (!dbCredential) {
return dbCredential;
}
return buildNonDwdCredential(dbCredential);
}
}
@@ -2,6 +2,8 @@ import type { Prisma } from "@prisma/client";
import { prisma } from "@calcom/prisma";
import { buildCredentialPayloadForPrisma } from "../buildCredentialPayloadForCalendar";
export class DestinationCalendarRepository {
static async create(data: Prisma.DestinationCalendarCreateInput) {
return await prisma.destinationCalendar.create({
@@ -9,7 +11,7 @@ export class DestinationCalendarRepository {
});
}
static async getByUserId(userId: string) {
static async getByUserId(userId: number) {
return await prisma.destinationCalendar.findFirst({
where: {
userId,
@@ -24,4 +26,54 @@ export class DestinationCalendarRepository {
},
});
}
static async find({ where }: { where: Prisma.DestinationCalendarWhereInput }) {
return await prisma.destinationCalendar.findFirst({
where,
});
}
static async upsert({
where,
update,
create,
}: {
where: Prisma.DestinationCalendarUpsertArgs["where"];
update: {
integration?: string;
externalId?: string;
credentialId?: number | null;
primaryEmail?: string | null;
domainWideDelegationCredentialId?: string | null;
};
create: {
integration: string;
externalId: string;
credentialId: number | null;
primaryEmail?: string | null;
domainWideDelegationCredentialId?: string | null;
};
}) {
const credentialPayloadForUpdate = buildCredentialPayloadForPrisma({
credentialId: update.credentialId,
domainWideDelegationCredentialId: update.domainWideDelegationCredentialId,
});
const credentialPayloadForCreate = buildCredentialPayloadForPrisma({
credentialId: create.credentialId,
domainWideDelegationCredentialId: create.domainWideDelegationCredentialId,
});
return await prisma.destinationCalendar.upsert({
where,
update: {
...update,
...credentialPayloadForUpdate,
},
create: {
...create,
...credentialPayloadForCreate,
},
});
}
}
@@ -1,23 +1,18 @@
import type { Prisma } from "@prisma/client";
import z from "zod";
import type { IDomainWideDelegationRepository } from "@calcom/features/domain-wide-delegation/domain-wide-delegation-repository.interface";
import { getFeatureFlag } from "@calcom/features/flags/server/utils";
import logger from "@calcom/lib/logger";
import {
serviceAccountKeySchema,
type ServiceAccountKey,
type EncryptedServiceAccountKey,
encryptServiceAccountKey,
decryptServiceAccountKey,
} from "@calcom/lib/server/serviceAccountKey";
import { prisma } from "@calcom/prisma";
import { OrganizationRepository } from "./organization";
const serviceAccountKeySchema = z
.object({
client_email: z.string(),
private_key: z.string(),
client_id: z.string(),
})
.passthrough();
export type ServiceAccountKey = z.infer<typeof serviceAccountKeySchema>;
export type { ServiceAccountKey };
const repositoryLogger = logger.getSubLogger({ prefix: ["DomainWideDelegationRepository"] });
const domainWideDelegationSafeSelect = {
id: true,
@@ -39,28 +34,41 @@ const domainWideDelegationSelectIncludesServiceAccountKey = {
serviceAccountKey: true,
};
export class DomainWideDelegationRepository implements IDomainWideDelegationRepository {
export class DomainWideDelegationRepository {
private static encryptServiceAccountKey(serviceAccountKey: ServiceAccountKey): EncryptedServiceAccountKey {
return encryptServiceAccountKey(serviceAccountKey);
}
private static decryptServiceAccountKey(encryptedServiceAccountKey: Prisma.JsonValue): ServiceAccountKey {
return decryptServiceAccountKey(encryptedServiceAccountKey);
}
private static withParsedServiceAccountKey<T extends { serviceAccountKey: Prisma.JsonValue } | null>(
domainWideDelegation: T
) {
if (!domainWideDelegation) {
return null;
}
const parsedServiceAccountKey = serviceAccountKeySchema.safeParse(domainWideDelegation.serviceAccountKey);
const { serviceAccountKey, ...rest } = domainWideDelegation;
// Decrypt the service account key if it exists
const decryptedKey = this.decryptServiceAccountKey(serviceAccountKey);
const parsedServiceAccountKey = serviceAccountKeySchema.safeParse(decryptedKey);
return {
...domainWideDelegation,
...rest,
serviceAccountKey: parsedServiceAccountKey.success ? parsedServiceAccountKey.data : null,
};
}
async create(data: {
static async create(data: {
domain: string;
enabled: boolean;
organizationId: number;
workspacePlatformId: number;
serviceAccountKey: Exclude<Prisma.JsonValue, null>;
serviceAccountKey: ServiceAccountKey;
}) {
const encryptedKey = this.encryptServiceAccountKey(data.serviceAccountKey);
return await prisma.domainWideDelegation.create({
data: {
workspacePlatform: {
@@ -75,20 +83,34 @@ export class DomainWideDelegationRepository implements IDomainWideDelegationRepo
id: data.organizationId,
},
},
serviceAccountKey: data.serviceAccountKey,
serviceAccountKey: encryptedKey,
},
select: domainWideDelegationSafeSelect,
});
}
async findById({ id }: { id: string }) {
static async findById({ id }: { id: string }) {
return await prisma.domainWideDelegation.findUnique({
where: { id },
select: domainWideDelegationSafeSelect,
});
}
async findByIdIncludeSensitiveServiceAccountKey({ id }: { id: string }) {
static async findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey({
organizationId,
domain,
}: {
organizationId: number;
domain: string;
}) {
const dwd = await prisma.domainWideDelegation.findUnique({
where: { organizationId_domain: { organizationId, domain } },
select: domainWideDelegationSelectIncludesServiceAccountKey,
});
return DomainWideDelegationRepository.withParsedServiceAccountKey(dwd);
}
static async findByIdIncludeSensitiveServiceAccountKey({ id }: { id: string }) {
const domainWideDelegation = await prisma.domainWideDelegation.findUnique({
where: { id },
select: domainWideDelegationSelectIncludesServiceAccountKey,
@@ -97,8 +119,10 @@ export class DomainWideDelegationRepository implements IDomainWideDelegationRepo
return DomainWideDelegationRepository.withParsedServiceAccountKey(domainWideDelegation);
}
async findUniqueByOrganizationMemberEmail({ email }: { email: string }) {
const log = repositoryLogger.getSubLogger({ prefix: ["findUniqueByOrganizationMemberEmail"] });
static async findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({ email }: { email: string }) {
const log = repositoryLogger.getSubLogger({
prefix: ["findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey"],
});
log.debug("called with", { email });
const organization = await OrganizationRepository.findByMemberEmail({ email });
if (!organization) {
@@ -114,14 +138,10 @@ export class DomainWideDelegationRepository implements IDomainWideDelegationRepo
domain: emailDomain,
},
},
select: domainWideDelegationSafeSelect,
select: domainWideDelegationSelectIncludesServiceAccountKey,
});
return domainWideDelegation;
}
async findByUser({ user }: { user: { email: string } }) {
return await this.findUniqueByOrganizationMemberEmail({ email: user.email });
return DomainWideDelegationRepository.withParsedServiceAccountKey(domainWideDelegation);
}
static async findAllByDomain({ domain }: { domain: string }) {
@@ -131,19 +151,7 @@ export class DomainWideDelegationRepository implements IDomainWideDelegationRepo
});
}
static async findFirstByOrganizationId({ organizationId }: { organizationId: number }) {
const domainWideDelegationEnabled = await getFeatureFlag(prisma, "domain-wide-delegation");
if (!domainWideDelegationEnabled) {
return null;
}
return await prisma.domainWideDelegation.findFirst({
where: { organizationId },
select: domainWideDelegationSafeSelect,
});
}
async updateById({
static async updateById({
id,
data,
}: {
@@ -179,13 +187,13 @@ export class DomainWideDelegationRepository implements IDomainWideDelegationRepo
});
}
async deleteById({ id }: { id: string }) {
static async deleteById({ id }: { id: string }) {
return await prisma.domainWideDelegation.delete({
where: { id },
});
}
async findDelegationsWithServiceAccount({ organizationId }: { organizationId: number }) {
static async findByOrgIdIncludeSensitiveServiceAccountKey({ organizationId }: { organizationId: number }) {
return await prisma.domainWideDelegation.findMany({
where: { organizationId },
select: {
@@ -289,4 +289,154 @@ describe("SelectedCalendarRepository", () => {
});
});
});
describe("Domain Wide Delegation", () => {
it("should create a selected calendar with domainWideDelegationCredentialId", async () => {
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
domainWideDelegationCredentialId: "dwd-123",
};
const result = await SelectedCalendarRepository.create(data);
expect(result).toEqual(expect.objectContaining(data));
});
describe("upsert", () => {
describe("updation", () => {
it("should update existing record with domainWideDelegationCredentialId if credentialId is -1", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: -1,
domainWideDelegationCredentialId: "dwd-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);
});
it("should update existing record with credentialId if credentialId is valid(>0) even if domainWideDelegationCredentialId is set", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 2,
domainWideDelegationCredentialId: "dwd-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();
});
});
describe("creation", () => {
it("should create a new record with domainWideDelegationCredentialId if credentialId is -1", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
eventTypeId: null,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: -1,
domainWideDelegationCredentialId: "dwd-123",
};
// It will create a new record because of unique constraint violation
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).not.toBe(null);
expect(result.id).not.toBe(existingCalendar.id);
expect(result.credentialId).toBe(null);
expect(result.domainWideDelegationCredentialId).toBe(data.domainWideDelegationCredentialId);
});
});
it("shouldnt update existing domainWideDelegationCredentialId if upsert data doesn't have it", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
eventTypeId: null,
domainWideDelegationCredentialId: "dwd-123",
credentialId: 1,
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
credentialId: 1,
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(existingCalendar.credentialId);
expect(result.domainWideDelegationCredentialId).toBe(null);
});
it("shouldnt update domainWideDelegationCredentialId if it is undefined", async () => {
const initialData = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
eventTypeId: null,
domainWideDelegationCredentialId: "dwd-123",
};
const existingCalendar = await SelectedCalendarRepository.create(initialData);
const data = {
userId: 1,
integration: "google_calendar",
externalId: "[email protected]",
};
const result = await SelectedCalendarRepository.upsert(data);
expect(result.id).toBe(existingCalendar.id);
expect(result.credentialId).toBe(existingCalendar.credentialId);
expect(result.domainWideDelegationCredentialId).toBe(
existingCalendar.domainWideDelegationCredentialId
);
});
});
});
});
@@ -4,6 +4,8 @@ import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { SelectedCalendarEventTypeIds } from "@calcom/types/Calendar";
import { buildCredentialPayloadForPrisma } from "../buildCredentialPayloadForCalendar";
export type UpdateArguments = {
where: FindManyArgs["where"];
data: Prisma.SelectedCalendarUpdateManyArgs["data"];
@@ -78,19 +80,28 @@ export class SelectedCalendarRepository {
static async upsert(data: Prisma.SelectedCalendarUncheckedCreateInput) {
// userId_integration_externalId_eventTypeId is a unique constraint but with eventTypeId being nullable
// So, this unique constraint can't be used in upsert. Prisma doesn't allow that, So, we do create and update separately
const conflictingCalendar = await SelectedCalendarRepository.findConflicting(data);
const credentialPayload = buildCredentialPayloadForPrisma({
credentialId: data.credentialId,
domainWideDelegationCredentialId: data.domainWideDelegationCredentialId,
});
const newData = {
...data,
...credentialPayload,
};
const conflictingCalendar = await SelectedCalendarRepository.findConflicting(newData);
if (conflictingCalendar) {
return await prisma.selectedCalendar.update({
where: {
id: conflictingCalendar.id,
},
data,
data: newData,
});
}
return await prisma.selectedCalendar.create({
data,
data: newData,
});
}
+9 -48
View File
@@ -3,7 +3,6 @@ import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
import prisma from "@calcom/prisma";
import { availabilityUserSelect } from "@calcom/prisma";
import { Prisma } from "@calcom/prisma/client";
import type { User as UserType } from "@calcom/prisma/client";
import type { CreationSource } from "@calcom/prisma/enums";
@@ -13,9 +12,13 @@ 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 { withSelectedCalendars } from "../withSelectedCalendars";
import { ProfileRepository } from "./profile";
import { getParsedTeam } from "./teamUtils";
export type { UserWithLegacySelectedCalendars } from "../withSelectedCalendars";
export { withSelectedCalendars };
export type UserAdminTeams = number[];
const log = logger.getSubLogger({ prefix: ["[repository/user]"] });
@@ -74,32 +77,6 @@ const userSelect = Prisma.validator<Prisma.UserSelect>()({
teams: true,
});
export type UserWithLegacySelectedCalendars<TCalendar, TUser> = TUser & {
selectedCalendars: TCalendar[];
};
type UserWithSelectedCalendars<TCalendar, TUser> = Omit<TUser, "selectedCalendars"> & {
allSelectedCalendars: TCalendar[];
userLevelSelectedCalendars: TCalendar[];
};
export function withSelectedCalendars<
TCalendar extends {
eventTypeId: number | null;
},
TUser extends {
selectedCalendars: TCalendar[];
}
>(user: UserWithLegacySelectedCalendars<TCalendar, TUser>): UserWithSelectedCalendars<TCalendar, TUser> {
// We are renaming selectedCalendars to allSelectedCalendars to make it clear that it contains all the calendars including eventType calendars
const { selectedCalendars, ...restUser } = user;
return {
...restUser,
allSelectedCalendars: selectedCalendars,
userLevelSelectedCalendars: selectedCalendars.filter((calendar) => !calendar.eventTypeId),
};
}
export class UserRepository {
static async findTeamsByUserId({ userId }: { userId: UserType["id"] }) {
const teamMemberships = await prisma.membership.findMany({
@@ -806,27 +783,11 @@ export class UserRepository {
return null;
}
return withSelectedCalendars(user);
}
static async findForAvailabilityCheck({ where }: { where: Prisma.UserWhereInput }) {
const user = await prisma.user.findFirst({
where,
select: {
...availabilityUserSelect,
selectedCalendars: true,
credentials: {
select: credentialForCalendarServiceSelect,
},
},
});
if (!user) {
return null;
}
const userWithSelectedCalendars = withSelectedCalendars(user);
return userWithSelectedCalendars;
const { credentials, ...userWithSelectedCalendars } = withSelectedCalendars(user);
return {
...userWithSelectedCalendars,
credentials: buildNonDwdCredentials(credentials),
};
}
static async findUnlockedUserForSession({ userId }: { userId: number }) {
@@ -1,9 +1,10 @@
import type { Prisma } from "@prisma/client";
import { Prisma } from "@prisma/client";
import { prisma } from "@calcom/prisma";
import type { TServiceAccountKeySchema } from "@calcom/prisma/zod-utils";
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
type WorkspacePlatformServiceAccountKey = TServiceAccountKeySchema | null;
const safeWorkspacePlatformSelect = {
id: true,
name: true,
@@ -31,11 +32,19 @@ export class WorkspacePlatformRepository {
slug: string;
name: string;
description: string;
defaultServiceAccountKey: TServiceAccountKeySchema;
defaultServiceAccountKey?: WorkspacePlatformServiceAccountKey;
enabled: boolean;
}) {
const { defaultServiceAccountKey: _defaultServiceAccountKey, ...rest } = data;
const defaultServiceAccountKey =
_defaultServiceAccountKey === undefined || _defaultServiceAccountKey === null
? Prisma.JsonNull
: _defaultServiceAccountKey;
return await prisma.workspacePlatform.create({
data,
data: {
defaultServiceAccountKey,
...rest,
},
select: safeWorkspacePlatformSelect,
});
}
+74
View File
@@ -0,0 +1,74 @@
import type { Prisma } from "@prisma/client";
import { z } from "zod";
import { SERVICE_ACCOUNT_ENCRYPTION_KEY } from "@calcom/lib/constants";
import { symmetricEncrypt, symmetricDecrypt } from "@calcom/lib/crypto";
import { serviceAccountKeySchema } from "@calcom/prisma/zod-utils";
export type ServiceAccountKey = z.infer<typeof serviceAccountKeySchema>;
export { serviceAccountKeySchema };
// Schema for encrypted service account key (our storage format)
export const encryptedServiceAccountKeySchema = z
.object({
client_email: z.string().optional(),
client_id: z.string(),
encrypted_credentials: z.string(),
tenant_id: z.string().optional(),
})
.passthrough();
export type EncryptedServiceAccountKey = z.infer<typeof encryptedServiceAccountKeySchema>;
export function encryptServiceAccountKey(serviceAccountKey: ServiceAccountKey): EncryptedServiceAccountKey {
if (!SERVICE_ACCOUNT_ENCRYPTION_KEY) {
throw new Error("Service account encryption key is not set");
}
// Extract private_key to encrypt
const { private_key, ...rest } = serviceAccountKey;
const sensitiveData = { private_key };
// Create a new object with encrypted credentials
return {
...rest,
encrypted_credentials: symmetricEncrypt(JSON.stringify(sensitiveData), SERVICE_ACCOUNT_ENCRYPTION_KEY),
} as EncryptedServiceAccountKey;
}
export function decryptServiceAccountKey(encryptedServiceAccountKey: Prisma.JsonValue): ServiceAccountKey {
if (!SERVICE_ACCOUNT_ENCRYPTION_KEY) {
throw new Error("Service account encryption key is not set");
}
try {
// Parse and validate the encrypted format
const parsedEncrypted = encryptedServiceAccountKeySchema.safeParse(encryptedServiceAccountKey);
if (!parsedEncrypted.success) {
throw new Error(`Invalid service account key format: ${JSON.stringify(parsedEncrypted.error)}`);
}
const { encrypted_credentials, ...rest } = parsedEncrypted.data;
// Decrypt and parse the sensitive data
const decryptedData = JSON.parse(
symmetricDecrypt(encrypted_credentials, SERVICE_ACCOUNT_ENCRYPTION_KEY)
) as Record<string, string>;
// Reconstruct and validate the decrypted format
const decrypted = {
...rest,
...decryptedData,
};
const parsedDecrypted = serviceAccountKeySchema.safeParse(decrypted);
if (!parsedDecrypted.success) {
throw new Error("Invalid decrypted service account key format");
}
return parsedDecrypted.data;
} catch (error) {
if (error instanceof Error) {
throw new Error(`Failed to decrypt service account key: ${error.message}`);
}
throw new Error("Failed to decrypt service account key");
}
}
@@ -0,0 +1,25 @@
export type UserWithLegacySelectedCalendars<TCalendar, TUser> = TUser & {
selectedCalendars: TCalendar[];
};
type UserWithSelectedCalendars<TCalendar, TUser> = Omit<TUser, "selectedCalendars"> & {
allSelectedCalendars: TCalendar[];
userLevelSelectedCalendars: TCalendar[];
};
export function withSelectedCalendars<
TCalendar extends {
eventTypeId: number | null;
},
TUser extends {
selectedCalendars: TCalendar[];
}
>(user: UserWithLegacySelectedCalendars<TCalendar, TUser>): UserWithSelectedCalendars<TCalendar, TUser> {
// We are renaming selectedCalendars to allSelectedCalendars to make it clear that it contains all the calendars including eventType calendars
const { selectedCalendars, ...restUser } = user;
return {
...restUser,
allSelectedCalendars: selectedCalendars,
userLevelSelectedCalendars: selectedCalendars.filter((calendar) => !calendar.eventTypeId),
};
}
@@ -14,7 +14,11 @@ import { getPlaceholderContent } from "../lib/getPlaceholderContent";
export type DestinationCalendarProps = {
connectedCalendars: ConnectedDestinationCalendars["connectedCalendars"];
destinationCalendar: ConnectedDestinationCalendars["destinationCalendar"];
onChange: (value: { externalId: string; integration: string }) => void;
onChange: (value: {
externalId: string;
integration: string;
domainWideDelegationCredentialId?: string;
}) => void;
isPending?: boolean;
hidePlaceholder?: boolean;
value: string | undefined;
@@ -37,6 +41,7 @@ export const DestinationCalendarSelector = ({
value: string;
label: string;
subtitle: string;
domainWideDelegationCredentialId?: string;
} | null>(null);
useEffect(() => {
@@ -77,6 +82,7 @@ export const DestinationCalendarSelector = ({
selectedCalendar?.primary?.name
})`,
value: `${cal.integration}:${cal.externalId}`,
domainWideDelegationCredentialId: cal.domainWideDelegationCredentialId || undefined,
})),
})) ?? []
);
@@ -135,6 +141,7 @@ export const DestinationCalendarSelector = ({
onChange({
integration,
externalId,
domainWideDelegationCredentialId: newValue.domainWideDelegationCredentialId,
});
}}
isLoading={isPending}
@@ -38,8 +38,12 @@ export const DestinationCalendarSettingsPlatformWrapper = ({
value={calendars.data.destinationCalendar.externalId}
hidePlaceholder
hideAdvancedText
onChange={async ({ externalId, integration }) => {
await updateDestinationCalendars({ integration, externalId });
onChange={async ({ externalId, integration, domainWideDelegationCredentialId }) => {
await updateDestinationCalendars({
integration,
externalId,
domainWideDelegationCredentialId,
});
}}
isPending={isUpdatingCalendar}
/>
@@ -31,12 +31,23 @@ export const useAddSelectedCalendar = (
};
}>,
unknown,
{ credentialId: number; integration: string; externalId: string }
{
credentialId: number;
integration: string;
externalId: string;
domainWideDelegationCredentialId: string | null;
}
>({
mutationFn: (data) => {
return http.post(`/selected-calendars`, data).then((res) => {
return res.data;
});
const { domainWideDelegationCredentialId, ...rest } = data;
return http
.post(`/selected-calendars`, {
...rest,
...(domainWideDelegationCredentialId ? { domainWideDelegationCredentialId } : {}),
})
.then((res) => {
return res.data;
});
},
onSuccess: (data) => {
if (data.status === SUCCESS_STATUS) {
@@ -31,16 +31,25 @@ export const useRemoveSelectedCalendar = (
};
}>,
unknown,
{ credentialId: number; integration: string; externalId: string }
{
credentialId: number;
integration: string;
externalId: string;
domainWideDelegationCredentialId: string | null;
}
>({
mutationFn: (data) => {
const { credentialId, externalId, integration } = data;
const { credentialId, externalId, integration, domainWideDelegationCredentialId } = data;
return http
.delete(
`/selected-calendars?credentialId=${credentialId}&integration=${integration}&externalId=${encodeURIComponent(
externalId
)}`
)}${
domainWideDelegationCredentialId
? `&domainWideDelegationCredentialId=${domainWideDelegationCredentialId}`
: ""
}`
)
.then((res) => {
return res.data;
@@ -30,10 +30,11 @@ export const useUpdateDestinationCalendars = (
integration: string;
externalId: string;
credentialId: number | null;
domainWideDelegationCredentialId?: string;
};
}>,
unknown,
{ integration: string; externalId: string }
{ integration: string; externalId: string; domainWideDelegationCredentialId?: 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 && (
{allowDelete && !connectedCalendar.domainWideDelegationCredentialId && (
<PlatformDisconnectIntegration
credentialId={connectedCalendar.credentialId}
trashIcon
@@ -107,6 +107,10 @@ export const SelectedCalendarsSettingsPlatformWrapper = ({
isChecked={cal.isSelected}
destination={cal.externalId === destinationCalendarId}
credentialId={cal.credentialId}
domainWideDelegationCredentialId={
connectedCalendar.domainWideDelegationCredentialId
}
eventTypeId={null}
/>
);
})}
@@ -120,17 +124,19 @@ export const SelectedCalendarsSettingsPlatformWrapper = ({
key={`alert-${connectedCalendar.credentialId}`}
severity="warning"
title={t("something_went_wrong")}
message={<span>{t("calendar_error")}</span>}
message={<span>{connectedCalendar.error?.message || t("calendar_error")}</span>}
iconClassName="h-10 w-10 ml-2 mr-1 mt-0.5"
actions={
<div className="flex w-32 justify-end">
<PlatformDisconnectIntegration
credentialId={connectedCalendar.credentialId}
trashIcon
buttonProps={{ className: "border border-default" }}
slug={connectedCalendar.integration.slug}
/>
</div>
!Boolean(connectedCalendar.domainWideDelegationCredentialId) && (
<div className="flex w-32 justify-end">
<PlatformDisconnectIntegration
credentialId={connectedCalendar.credentialId}
trashIcon
buttonProps={{ className: "border border-default" }}
slug={connectedCalendar.integration.slug}
/>
</div>
)
}
/>
);
@@ -216,7 +222,7 @@ const PlatformDisconnectIntegration = (props: {
};
const PlatformCalendarSwitch = (props: ICalendarSwitchProps) => {
const { isChecked, title, credentialId, type, externalId } = props;
const { isChecked, title, credentialId, type, externalId, domainWideDelegationCredentialId } = props;
const [checkedInternal, setCheckedInternal] = useState(isChecked);
const { toast } = useToast();
@@ -249,9 +255,14 @@ const PlatformCalendarSwitch = (props: ICalendarSwitchProps) => {
externalId: string;
}) => {
if (isOn) {
await addSelectedCalendar({ credentialId, integration, externalId });
await addSelectedCalendar({ credentialId, integration, externalId, domainWideDelegationCredentialId });
} else {
await removeSelectedCalendar({ credentialId, integration, externalId });
await removeSelectedCalendar({
credentialId,
integration,
externalId,
domainWideDelegationCredentialId,
});
}
};
@@ -65,6 +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 &&
!disableConnectionModification && (
<div className="flex w-32 justify-end">
<DisconnectIntegration
@@ -93,6 +95,9 @@ const ConnectedCalendarList = ({
destination={cal.externalId === destinationCalendarId}
credentialId={cal.credentialId}
eventTypeId={shouldUseEventTypeScope ? eventTypeId : null}
domainWideDelegationCredentialId={
connectedCalendar.domainWideDelegationCredentialId
}
/>
))}
</ul>
@@ -117,14 +122,17 @@ const ConnectedCalendarList = ({
}
iconClassName="h-10 w-10 ml-2 mr-1 mt-0.5"
actions={
<div className="flex w-32 justify-end">
<DisconnectIntegration
credentialId={connectedCalendar.credentialId}
trashIcon
onSuccess={onChanged}
buttonProps={{ className: "border border-default" }}
/>
</div>
// DWD credential can't be disconnected
!connectedCalendar.domainWideDelegationCredentialId && (
<div className="flex w-32 justify-end">
<DisconnectIntegration
credentialId={connectedCalendar.credentialId}
trashIcon
onSuccess={onChanged}
buttonProps={{ className: "border border-default" }}
/>
</div>
)
}
/>
);
+40
View File
@@ -5,6 +5,7 @@ import { CalendarService as IcsFeedCalendarService } from "@calcom/app-store/ics
import type { CredentialOwner } from "@calcom/app-store/types";
import { getAppFromSlug } from "@calcom/app-store/utils";
import type { CredentialDataWithTeamName, LocationOption } from "@calcom/app-store/utils";
import getApps from "@calcom/app-store/utils";
import AttendeeCancelledEmail from "@calcom/emails/templates/attendee-cancelled-email";
import AttendeeDeclinedEmail from "@calcom/emails/templates/attendee-declined-email";
import AttendeeRequestEmail from "@calcom/emails/templates/attendee-request-email";
@@ -30,6 +31,20 @@ import * as instantMeetingMethods from "@calcom/features/instant-meeting/handleI
import getEnabledAppsFromCredentials from "@calcom/lib/apps/getEnabledAppsFromCredentials";
import getAllUserBookings from "@calcom/lib/bookings/getAllUserBookings";
import { symmetricEncrypt, symmetricDecrypt } from "@calcom/lib/crypto";
import {
getFirstDwdConferencingCredentialAppLocation,
getFirstDwdConferencingCredential,
getDwdOrRegularCredential,
getDwdOrFindRegularCredential,
enrichUserWithDwdConferencingCredentialsWithoutOrgId,
enrichUserWithDwdCredentialsWithoutOrgId,
enrichHostsWithDwdCredentials,
enrichUsersWithDwdCredentials,
buildAllCredentials,
getAllDwdCredentialsForUserByAppSlug,
getAllDwdCredentialsForUserByAppType,
checkIfSuccessfullyConfiguredInWorkspace,
} from "@calcom/lib/domainWideDelegation/server";
import getBulkEventTypes from "@calcom/lib/event-types/getBulkEventTypes";
import { getRoutedUrl } from "@calcom/lib/server/getRoutedUrl";
import { getTeamMemberEmailForResponseOrContactUsingUrlQuery } from "@calcom/lib/server/getTeamMemberEmailFromCrm";
@@ -39,6 +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 { getAvailableSlots } from "@calcom/trpc/server/routers/viewer/slots/util";
import {
createNewUsersConnectToOrgIfExists,
@@ -47,6 +63,25 @@ import {
import type { App } from "@calcom/types/App";
import type { CredentialPayload } from "@calcom/types/Credential";
export { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
export { getApps };
export {
getFirstDwdConferencingCredentialAppLocation,
getFirstDwdConferencingCredential,
getDwdOrRegularCredential,
getDwdOrFindRegularCredential,
enrichUserWithDwdConferencingCredentialsWithoutOrgId,
enrichUserWithDwdCredentialsWithoutOrgId,
enrichHostsWithDwdCredentials,
enrichUsersWithDwdCredentials,
buildAllCredentials,
getAllDwdCredentialsForUserByAppSlug,
getAllDwdCredentialsForUserByAppType,
checkIfSuccessfullyConfiguredInWorkspace,
};
export { slugify } from "@calcom/lib/slugify";
export { getBookingForReschedule };
export { updateScheduleHandler };
@@ -240,4 +275,9 @@ export { getRoutedUrl };
export { getTeamMemberEmailForResponseOrContactUsingUrlQuery };
export { addDwd };
export { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
export { toggleDwdEnabled } from "@calcom/trpc/server/routers/viewer/domainWideDelegation/toggleEnabled.handler";
export { encryptServiceAccountKey } from "@calcom/lib/server/serviceAccountKey";
export { createHandler as createApiKeyHandler } from "@calcom/trpc/server/routers/viewer/apiKeys/create.handler";
+4 -4
View File
@@ -809,14 +809,14 @@ export const bookingSeatDataSchema = z.object({
responses: bookingResponses,
});
// Schema for decrypted service account key
export const serviceAccountKeySchema = z
.object({
type: z.string(),
client_id: z.string(),
client_email: z.string(),
private_key: z.string(),
client_email: z.string().optional(),
client_id: z.string(),
tenant_id: z.string().optional(),
})
// There could be more properties available here by the Workspace platform(e.g. Google), we don't want to loose them but don't need them also at the moment
.passthrough();
export type TServiceAccountKeySchema = z.infer<typeof serviceAccountKeySchema>;
+1
View File
@@ -30,6 +30,7 @@ export const ENDPOINTS = [
"googleWorkspace",
"oAuth",
"attributes",
"domainWideDelegation",
"routingForms",
"domainWideDelegation",
] as const;
@@ -1,3 +1,4 @@
import { getAllDwdCredentialsForUserByAppType } from "@calcom/lib/domainWideDelegation/server";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -43,10 +44,15 @@ export const appCredentialsByTypeHandler = async ({ ctx, input }: AppCredentials
},
});
const dwdCredentials = await getAllDwdCredentialsForUserByAppType({
user: { id: user.id, email: user.email },
appType: input.appType,
});
// For app pages need to return which teams the user can install the app on
// return user.credentials.filter((app) => app.type == input.appType).map((credential) => credential.id);
return {
credentials,
credentials: [...dwdCredentials, ...credentials],
userAdminTeams: userAdminTeamsIds,
};
};
@@ -1,4 +1,5 @@
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
import { buildNonDwdCredentials } from "@calcom/lib/domainWideDelegation/server";
import { prisma } from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -23,7 +24,8 @@ const checkInvalidGoogleCalendarCredentials = async ({ ctx }: Props) => {
select: credentialForCalendarServiceSelect,
});
const calendarCredentials = getCalendarCredentials(userCredentials);
// TODO: Call top buildNonDwdCredentials here can be avoided by moving credential prisma query to repository.
const calendarCredentials = getCalendarCredentials(buildNonDwdCredentials(userCredentials));
const { connectedCalendars } = await getConnectedCalendars(
calendarCredentials,
@@ -10,6 +10,7 @@ export const ZIntegrationsInputSchema = z.object({
extendsFeature: z.literal("EventType").optional(),
teamId: z.union([z.number(), z.null()]).optional(),
sortByMostPopular: z.boolean().optional(),
sortByInstalledFirst: z.boolean().optional(),
categories: z.nativeEnum(AppCategories).array().optional(),
appId: z.string().optional(),
});
@@ -0,0 +1,208 @@
import prisma from "../../../../../tests/libs/__mocks__/prisma";
import {
createBookingScenario,
TestData,
getOrganizer,
getScenarioData,
createOrganization,
createDwdCredential,
} from "@calcom/web/test/utils/bookingScenario/bookingScenario";
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
import { describe, it, vi, expect } from "vitest";
import { getConnectedCalendars } from "@calcom/core/CalendarManager";
import { SchedulingType, MembershipRole } from "@calcom/prisma/enums";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../trpc";
import { setDestinationCalendarHandler } from "./setDestinationCalendar.handler";
vi.mock("@calcom/core/CalendarManager", () => ({
getConnectedCalendars: vi.fn(),
getCalendarCredentials: vi.fn().mockImplementation((creds) => creds),
}));
describe("setDestinationCalendarHandler", () => {
setupAndTeardown();
it("should successfully set destination calendar with DWD credentials", async () => {
const org = await createOrganization({
name: "Test Org",
slug: "testorg",
});
const childTeam = {
id: 202,
name: "Team 1",
slug: "team-1",
parentId: org.id,
};
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
teams: [
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: org.id,
name: "Test Org",
slug: "testorg",
},
},
{
membership: {
accepted: true,
role: MembershipRole.ADMIN,
},
team: {
id: childTeam.id,
name: "Team 1",
slug: "team-1",
parentId: org.id,
},
},
],
});
const dwd = await createDwdCredential(org.id);
const dwdCredentialId = dwd.id;
const testExternalId = "[email protected]";
// Mock the getConnectedCalendars response
(getConnectedCalendars as jest.Mock).mockResolvedValue({
connectedCalendars: [
{
calendars: [
{
externalId: organizer.email,
integration: "google_calendar",
readOnly: false,
primary: true,
email: organizer.email,
credentialId: -1,
domainWideDelegationCredentialId: dwdCredentialId,
},
{
externalId: testExternalId,
integration: "google_calendar",
readOnly: false,
primary: null,
email: organizer.email,
credentialId: -1,
domainWideDelegationCredentialId: dwdCredentialId,
},
],
},
],
});
await createBookingScenario(
getScenarioData(
{
organizer,
eventTypes: [
{
id: 1,
teamId: childTeam.id,
schedulingType: SchedulingType.ROUND_ROBIN,
length: 30,
hosts: [
{
userId: 101,
isFixed: false,
},
],
},
],
selectedCalendars: [
{
integration: "google_calendar",
externalId: testExternalId,
credentialId: null,
domainWideDelegationCredentialId: dwdCredentialId,
},
],
},
org
)
);
const ctx = {
user: {
id: organizer.id,
email: organizer.email,
selectedCalendars: [
{
integration: "google_calendar",
externalId: testExternalId,
credentialId: null,
domainWideDelegationCredentialId: dwdCredentialId,
},
],
} as NonNullable<TrpcSessionUser>,
};
await setDestinationCalendarHandler({
ctx,
input: {
integration: "google_calendar",
externalId: testExternalId,
},
});
// Verify the destination calendar was set correctly
const destinationCalendar = await prisma.destinationCalendar.findFirst({
where: {
userId: organizer.id,
},
});
expect(destinationCalendar).toEqual(
expect.objectContaining({
integration: "google_calendar",
externalId: testExternalId,
credentialId: null,
domainWideDelegationCredentialId: dwdCredentialId,
})
);
});
it("should throw error when calendar is not found", async () => {
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
});
const ctx = {
user: {
id: organizer.id,
email: organizer.email,
selectedCalendars: [],
} as NonNullable<TrpcSessionUser>,
};
await expect(
setDestinationCalendarHandler({
ctx,
input: {
integration: "google_calendar",
externalId: "non-existent-calendar",
eventTypeId: null,
},
})
).rejects.toThrow(
new TRPCError({ code: "BAD_REQUEST", message: "Could not find calendar non-existent-calendar" })
);
});
});
@@ -1,5 +1,6 @@
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/core/CalendarManager";
import { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
import { DestinationCalendarRepository } from "@calcom/lib/server/repository/destinationCalendar";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
@@ -10,6 +11,7 @@ import type { TSetDestinationCalendarInputSchema } from "./setDestinationCalenda
type SessionUser = NonNullable<TrpcSessionUser>;
type User = {
id: SessionUser["id"];
email: SessionUser["email"];
userLevelSelectedCalendars: SessionUser["userLevelSelectedCalendars"];
};
@@ -20,6 +22,35 @@ type SetDestinationCalendarOptions = {
input: TSetDestinationCalendarInputSchema;
};
type ConnectedCalendar = Awaited<ReturnType<typeof getConnectedCalendars>>["connectedCalendars"][number];
type ConnectedCalendarCalendar = NonNullable<ConnectedCalendar["calendars"]>[number];
export const getFirstConnectedCalendar = ({
connectedCalendars,
matcher,
}: {
connectedCalendars: ConnectedCalendar[];
matcher: (calendar: ConnectedCalendarCalendar) => boolean;
}) => {
const calendars = connectedCalendars.flatMap((c) => c.calendars ?? []);
const matchingCalendars = calendars.filter(matcher);
const dwdCredentialCalendar = matchingCalendars.find((cal) => !!cal.domainWideDelegationCredentialId);
// Prefer DWD credential calendar as there could be other one due to existing connections even after DWD is enabled.
if (dwdCredentialCalendar) {
return dwdCredentialCalendar;
} else {
return matchingCalendars[0];
}
};
/**
* It identifies the destination calendar by externalId, integration and eventTypeId and doesn't consider the `credentialId` or destinationCalendar.id
* Also, DestinationCalendar doesn't have unique constraint on externalId, integration and eventTypeId, so there could be multiple destinationCalendars with same externalId, integration and eventTypeId in DB.
* So, it could update any of the destinationCalendar when there are duplicates in DB. Ideally we should have unique constraint on externalId, integration and eventTypeId.
*
* With the addition of DWD credential, it adds another dimension to the problem.
* A user could have DWD and non-DWD credential for the same calendar and he might be selecting DWD credential connected calendar but it could still be set with nullish destinationCalendar.domainWideDelegationCredentialId.
*/
export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinationCalendarOptions) => {
const { user } = ctx;
const { integration, externalId, eventTypeId } = input;
@@ -29,19 +60,30 @@ export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinati
calendarCredentials,
user.userLevelSelectedCalendars
);
const allCals = connectedCalendars.map((cal) => cal.calendars ?? []).flat();
const credentialId = allCals.find(
(cal) => cal.externalId === externalId && cal.integration === integration && cal.readOnly === false
)?.credentialId;
const firstConnectedCalendar = getFirstConnectedCalendar({
connectedCalendars,
matcher: (cal) =>
cal.externalId === externalId && cal.integration === integration && cal.readOnly === false,
});
if (!credentialId) {
const { credentialId, domainWideDelegationCredentialId } = firstConnectedCalendar || {};
let where;
if (!credentialId && !domainWideDelegationCredentialId) {
throw new TRPCError({ code: "BAD_REQUEST", message: `Could not find calendar ${input.externalId}` });
}
const primaryEmail = allCals.find((cal) => cal.primary && cal.credentialId === credentialId)?.email ?? null;
let where;
const primaryEmail =
allCals.find(
(cal) =>
cal.primary &&
(cal.credentialId === credentialId ||
cal.domainWideDelegationCredentialId === domainWideDelegationCredentialId)
)?.email ?? null;
if (eventTypeId) {
if (
@@ -61,20 +103,22 @@ export const setDestinationCalendarHandler = async ({ ctx, input }: SetDestinati
where = { eventTypeId };
} else where = { userId: user.id };
await prisma.destinationCalendar.upsert({
await DestinationCalendarRepository.upsert({
where,
update: {
integration,
externalId,
credentialId,
primaryEmail,
credentialId,
domainWideDelegationCredentialId,
},
create: {
...where,
integration,
externalId,
credentialId,
primaryEmail,
credentialId,
domainWideDelegationCredentialId,
},
});
};
@@ -10,9 +10,9 @@ import { getFeatureFlag } from "@calcom/features/flags/server/utils";
import hasKeyInMetadata from "@calcom/lib/hasKeyInMetadata";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { uploadAvatar } from "@calcom/lib/server/avatar";
import { checkUsername } from "@calcom/lib/server/checkUsername";
import { getTranslation } from "@calcom/lib/server/i18n";
import { updateNewTeamMemberEventTypes } from "@calcom/lib/server/queries";
import { resizeBase64Image } from "@calcom/lib/server/resizeBase64Image";
import slugify from "@calcom/lib/slugify";
@@ -6,7 +6,7 @@ export const workspacePlatformCreateSchema = z.object({
slug: z.string().min(1),
name: z.string().min(1),
description: z.string().min(1),
defaultServiceAccountKey: serviceAccountKeySchema,
defaultServiceAccountKey: serviceAccountKeySchema.optional(),
enabled: z.boolean().optional().default(true),
});
@@ -1,4 +1,5 @@
import { getAppFromSlug } from "@calcom/app-store/utils";
import { getAllDwdCredentialsForUserByAppSlug } from "@calcom/lib/domainWideDelegation/server";
import { prisma } from "@calcom/prisma";
import type { TrpcSessionUser } from "../../../trpc";
@@ -18,14 +19,21 @@ export const queryForDependenciesHandler = async ({ ctx, input }: QueryForDepend
await Promise.all(
input.map(async (dependency) => {
const appInstalled = await prisma.credential.findFirst({
const appId = dependency;
const dbCredential = await prisma.credential.findFirst({
where: {
appId: dependency,
appId,
userId: ctx.user.id,
},
});
const app = await getAppFromSlug(dependency);
const dwdCredentials = await getAllDwdCredentialsForUserByAppSlug({
user: ctx.user,
appSlug: appId,
});
const appInstalled = !!dbCredential || !!dwdCredentials.length;
const app = getAppFromSlug(dependency);
dependencyData.push({ name: app?.name || dependency, slug: dependency, installed: !!appInstalled });
})
@@ -1,5 +1,6 @@
import { getBusyCalendarTimes } from "@calcom/core/CalendarManager";
import dayjs from "@calcom/dayjs";
import { enrichUserWithDwdCredentialsWithoutOrgId } from "@calcom/lib/domainWideDelegation/server";
import { prisma } from "@calcom/prisma";
import type { EventBusyDate } from "@calcom/types/Calendar";
@@ -29,7 +30,7 @@ export const calendarOverlayHandler = async ({ ctx, input }: ListOptions) => {
// To call getCalendar we need
// Ensure that the user has access to all of the credentialIds
const credentials = await prisma.credential.findMany({
const nonDwdCredentials = await prisma.credential.findMany({
where: {
id: {
in: uniqueCredentialIds,
@@ -52,6 +53,13 @@ export const calendarOverlayHandler = async ({ ctx, input }: ListOptions) => {
},
});
const { credentials } = await enrichUserWithDwdCredentialsWithoutOrgId({
user: {
...user,
credentials: nonDwdCredentials,
},
});
if (credentials.length !== uniqueCredentialIds.length) {
throw new TRPCError({
code: "UNAUTHORIZED",
@@ -2,8 +2,8 @@ import EventManager from "@calcom/core/EventManager";
import dayjs from "@calcom/dayjs";
import { sendAddGuestsEmails } from "@calcom/emails";
import { parseRecurringEvent } from "@calcom/lib";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
import { getTranslation } from "@calcom/lib/server/i18n";
import { isTeamAdmin, isTeamOwner } from "@calcom/lib/server/queries/teams";
import { prisma } from "@calcom/prisma";
import type { CalendarEvent } from "@calcom/types/Calendar";
@@ -15,8 +15,8 @@ import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
import { processPaymentRefund } from "@calcom/lib/payment/processPaymentRefund";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getUsersCredentials } from "@calcom/lib/server/getUsersCredentials";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import { prisma } from "@calcom/prisma";
import {
@@ -17,7 +17,6 @@ import type { Booking, BookingReference } from "@calcom/prisma/client";
import type { userMetadata } from "@calcom/prisma/zod-utils";
import type { EventTypeMetadata } from "@calcom/prisma/zod-utils";
import type { AdditionalInformation, CalendarEvent } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { PartialReference } from "@calcom/types/EventManager";
import type { Ensure } from "@calcom/types/utils";
@@ -126,12 +125,12 @@ async function getAllCredentials({
user,
conferenceCredentialId,
}: {
user: { id: number };
user: { id: number; email: string };
conferenceCredentialId: number | null;
}) {
const credentials = await getUsersCredentials(user);
let conferenceCredential: CredentialPayload | null = null;
let conferenceCredential;
if (conferenceCredentialId) {
conferenceCredential = await CredentialRepository.findFirstByIdWithKeyAndUser({
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more