feat: Domain-wide delegation for Google Calendar and Google Meet (#16622)
* Add endpoints for testing the flow * Add MVP * new route * Fixes * Fixes * Remove enable toggle support from domainWideDelegation * Fixes * Revert "Remove enable toggle support from domainWideDelegation" This reverts commit c29e729206cd1fa063f9c9ce0cf148ef1577d60b. * Revert yarn.lock * More fixes * Fix new workspace platform add * refactor: improvements * refactor: bug fixes and improvements * fix: type errors * fix: conflicts * chore: update test * fix: logic * chore: improvements * fix: toglle * fix: bugs * fix: type err * chore: check number type * fix: after conflicts * chore: fix type err * fix: type errors and tests * fix: tets * test * chore: remove unused * fix: google meet url on booking page and secondary calendar * fix: add property * fix: type err * fix: re assingment bug * fix: use getAllCredentials * chore: fix import * fix: installed count * fix: pass event type * fix: import * fix: [Stacked PR] Review fixes (#17958) * Review fixes * fix: destination calendar bug --------- Co-authored-by: Udit Takkar <[email protected]> * refactor: use repository * chore: remove duplicate * fix: More review fixes for domain wide delegation (#17969) * Reuse buildCredentialPayloadForCalendar * fixes --------- Co-authored-by: Udit Takkar <[email protected]> * fix ts error * Fix getSchedule not using dwd credentials (#17995) * fix: Remove direct DWD table access from google-calendar and remove delegatedToId column from Credential (#18015) * Remove fn rename to reduce number of files changed * chore: check feature globally * test: add unit tests * chore: move function * test: add booking test * wip * Remove domain-wide-delegation team feature flag * Make sure duplicate calendars are not shown due to DWD. Show DWD when there is conflict * Fix tests and their ts errors * Fix more tests * Move findUsersForAvailabilityCheck to separate file as it has AppStore dependency causing problem with Routing Forms. Build crashes * fix: Multiple calendar connections from Google not showing up in apps/installed * DestinationCalendar must have either credentialId or domainWideDeelgationId. Also handle the case when DWD is disabled and there was a non-dwd credential that could be used * Disable deletetion of DWD as it is destructive and prefer disabling instead * Show DWD credential calendars at the top * Fixed tests * Calendar Cache DWD support * Self-Review: Verify email required and add more selectedCalendar tests * Self Review: shorten names * Self ReviewL Dead code removal * Revert "Calendar Cache DWD support" This reverts commit 009f236470fa21eba5986117d4f6e4d4c5e38c34. * Some misc fixes * fixes * Performance improvememt in slots loading and booking * More cases for handling dwd credentials * simplify the logic. Ensure that EventManager and the modules below it in the flow have CredentialForCalendarService available * Fix tests * Fix installed/conferencing not showing gogole meet * Shorten name * Fix ApI v2 tests * Add some more tests * add getSchedule tests * Improve tests * Make Google Meet default when DWD for google is enabled * Enable feature flagging for DWD * chore: bump libraries * Encrypt serviceaccount private key * Fix ts errors * bump platform libraries * org add dwd * org add dwd * bump platform libraries * fix selected calendars * fix remove selected dwd calendar * remove oauthclient id aliad in authedCalendar * remove oauthclient id aliad in authedCalendar * refactor: OrganizationsDwdController * chore: export toggleDwdEnabled from platform-libraries * feat: v2 update (enable / disable) dwd * refactor: SelectedCalendarsController check if user belongs to dwd org & for not dwd use previous logic * wip: DestinationCalendar send domainWideDelegationCredentialId from frontend to api * try fix set destination calendar api v2 * fixup! try fix set destination calendar api v2 * setting google meet as default location working for dwd * bump platform libraries version * allow office 365 workspace slug * allow office 365 workspace slug * chore: v2 create dwd MS and Google service keys input * fix: CreateDwdInput serviceAccountKey * fix: CredentialForCalendarService type * fix: check workspace slug * feat: update serviceAccessKey of DWD * testing * fixup! testing * fix: getAuthUtl bug * fix: unit tests * fix: type err and unit test * fix: e2e test * fix: credentials bug and failing unit tests * Update CalendarService.ts * chore: refactor office365 calendar service and add testDomainWideDelegationSetup * fix: office365Calendar use correct clientId/Secret for DWD * fix: office365Calendar dwd no need refresh token * test: add unit test for outlook dwd and setup * feat: added dwd support for office365 calendar * feat: added dwd support for office365 video * test: finish test for outlook dwd * fix: create dialog bug * chore: remove console logs * fix: refreshToken bug * bump version libraries * refactor: fetch dwd credentials only in findQualifiedHosts * fixup! refactor: fetch dwd credentials only in findQualifiedHosts * fix: type err * fix: type err * fix: getUserDisplayName * fix: unit test * chore: bump platform lib --------- Co-authored-by: Syed Ali Shahbaz <[email protected]> Co-authored-by: Udit Takkar <[email protected]> Co-authored-by: Udit Takkar <[email protected]> Co-authored-by: Morgan Vernay <[email protected]> Co-authored-by: supalarry <[email protected]> Co-authored-by: Somay Chauhan <[email protected]> Co-authored-by: Morgan <[email protected]>
This commit is contained in:
173 files changed
+12277
-1137
No files matched your search
@@ -1,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,
|
||||
|
||||
@@ -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")) {
|
||||
|
||||
@@ -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;
|
||||
@@ -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)),
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user