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
@@ -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"];
|
||||
};
|
||||
|
||||
|
||||
@@ -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 })[] }[]> {
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user