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 <udit222001@gmail.com>

* refactor: use repository

* chore: remove duplicate

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

* Reuse buildCredentialPayloadForCalendar

* fixes

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>

* 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 <52925846+alishaz-polymath@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: Udit Takkar <udit222001@gmail.com>
Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: supalarry <laurisskraucis@gmail.com>
Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
This commit is contained in:
173 files changed
+12277 -1137

No files matched your search

@@ -0,0 +1,34 @@
import {
GoogleServiceAccountKeyInput,
ServiceAccountKeyValidator,
MicrosoftServiceAccountKeyInput,
} from "@/modules/organizations/dwd/inputs/service-account-key.input";
import { ApiProperty, getSchemaPath } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsString, IsNotEmpty, ValidateNested, Validate } from "class-validator";
export class CreateDwdInput {
@IsString()
@IsNotEmpty()
@ApiProperty()
@Expose()
workspacePlatformSlug!: string;
@IsString()
@IsNotEmpty()
@ApiProperty()
@Expose()
domain!: string;
@Validate(ServiceAccountKeyValidator)
@ApiProperty({
type: [GoogleServiceAccountKeyInput, MicrosoftServiceAccountKeyInput],
oneOf: [
{ $ref: getSchemaPath(GoogleServiceAccountKeyInput) },
{ $ref: getSchemaPath(MicrosoftServiceAccountKeyInput) },
],
})
@Expose()
@Type(() => Object)
serviceAccountKey!: GoogleServiceAccountKeyInput | MicrosoftServiceAccountKeyInput;
}
@@ -0,0 +1,99 @@
import { ApiProperty } from "@nestjs/swagger";
import { Type, plainToClass, Expose } from "class-transformer";
import {
IsString,
IsNotEmpty,
ValidationOptions,
ValidatorConstraint,
ValidatorConstraintInterface,
validateSync,
} from "class-validator";
export class MicrosoftServiceAccountKeyInput {
@Expose()
@IsString()
@IsNotEmpty()
@ApiProperty()
private_key!: string;
@Expose()
@IsString()
@IsNotEmpty()
@ApiProperty()
tenant_id!: string;
@Expose()
@IsString()
@IsNotEmpty()
@ApiProperty()
client_id!: string;
}
export class GoogleServiceAccountKeyInput {
@Expose()
@IsString()
@IsNotEmpty()
@ApiProperty()
private_key!: string;
@Expose()
@IsString()
@IsNotEmpty()
@ApiProperty()
client_email!: string;
@Expose()
@IsString()
@IsNotEmpty()
@ApiProperty()
client_id!: string;
}
@ValidatorConstraint({ name: "isServiceAccountKey", async: false })
export class ServiceAccountKeyValidator implements ValidatorConstraintInterface {
validate(value: any) {
if (!value || typeof value !== "object") return false;
if ("client_email" in value) {
const googleKey = plainToClass(GoogleServiceAccountKeyInput, value, {
excludeExtraneousValues: true,
});
const googleErrors = validateSync(googleKey, {
whitelist: true,
forbidNonWhitelisted: true,
skipMissingProperties: false,
});
if (googleErrors.length === 0) return true;
this.errors = googleErrors;
return false;
}
if ("tenant_id" in value) {
const msKey = plainToClass(MicrosoftServiceAccountKeyInput, value, {
excludeExtraneousValues: true,
});
const msErrors = validateSync(msKey, {
whitelist: true,
forbidNonWhitelisted: true,
skipMissingProperties: false,
});
if (msErrors.length === 0) return true;
this.errors = msErrors;
return false;
}
return false;
}
private errors?: any[];
defaultMessage() {
if (this.errors?.length) {
return this.errors.map((error) => Object.values(error.constraints || {}).join(", ")).join("; ");
}
return "Service account key must be either a Google service account key (with client_email, private_key, client_id) or Microsoft service account key (with tenant_id, private_key, client_id)";
}
}
@@ -0,0 +1,29 @@
import {
GoogleServiceAccountKeyInput,
MicrosoftServiceAccountKeyInput,
ServiceAccountKeyValidator,
} from "@/modules/organizations/dwd/inputs/service-account-key.input";
import { ApiPropertyOptional, getSchemaPath } from "@nestjs/swagger";
import { Expose, plainToClass, Transform, Type } from "class-transformer";
import { IsBoolean, IsOptional, Validate, ValidateNested } from "class-validator";
export class UpdateDwdInput {
@IsBoolean()
@IsOptional()
@ApiPropertyOptional()
@Expose()
enabled?: boolean;
@IsOptional()
@Validate(ServiceAccountKeyValidator)
@ApiPropertyOptional({
type: [GoogleServiceAccountKeyInput, MicrosoftServiceAccountKeyInput],
oneOf: [
{ $ref: getSchemaPath(GoogleServiceAccountKeyInput) },
{ $ref: getSchemaPath(MicrosoftServiceAccountKeyInput) },
],
})
@Expose()
@Type(() => Object)
serviceAccountKey?: GoogleServiceAccountKeyInput | MicrosoftServiceAccountKeyInput;
}
@@ -0,0 +1,76 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.decorator";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Roles } from "@/modules/auth/decorators/roles/roles.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { PlatformPlanGuard } from "@/modules/auth/guards/billing/platform-plan.guard";
import { IsAdminAPIEnabledGuard } from "@/modules/auth/guards/organizations/is-admin-api-enabled.guard";
import { IsOrgGuard } from "@/modules/auth/guards/organizations/is-org.guard";
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
import { UpdateDwdInput } from "@/modules/organizations/dwd/inputs/update-dwd.input";
import { CreateDwdOutput } from "@/modules/organizations/dwd/outputs/create-dwd.output";
import { DwdOutput } from "@/modules/organizations/dwd/outputs/dwd.output";
import { UpdateDwdOutput } from "@/modules/organizations/dwd/outputs/update-dwd.output";
import { OrganizationsDwdService } from "@/modules/organizations/dwd/services/organizations-dwd.service";
import {
Controller,
UseGuards,
Param,
ParseIntPipe,
Post,
Body,
HttpCode,
HttpStatus,
Patch,
} from "@nestjs/common";
import { ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { User } from "@prisma/client";
import { plainToClass } from "class-transformer";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { CreateDwdInput } from "./inputs/create-dwd.input";
@Controller({
path: "/v2/organizations/:orgId/delegation-credentials",
version: API_VERSIONS_VALUES,
})
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, PlatformPlanGuard, IsAdminAPIEnabledGuard)
@DocsTags("Orgs / Delegation Credentials")
export class OrganizationsDwdController {
constructor(private readonly dwdService: OrganizationsDwdService) {}
@Post("/")
@HttpCode(HttpStatus.CREATED)
@Roles("ORG_ADMIN")
@PlatformPlan("SCALE")
@ApiOperation({ summary: "Save delegation credentials for your organization." })
async createDwd(
@Param("orgId", ParseIntPipe) orgId: number,
@GetUser() dwdServiceAccountUser: User,
@Body() body: CreateDwdInput
): Promise<CreateDwdOutput> {
const dwd = await this.dwdService.createDwd(orgId, dwdServiceAccountUser, body);
return {
status: SUCCESS_STATUS,
data: plainToClass(DwdOutput, dwd, { strategy: "excludeAll" }),
};
}
@Patch("/:credentialId")
@Roles("ORG_ADMIN")
@PlatformPlan("SCALE")
@ApiOperation({ summary: "Update delegation credentials of your organization." })
async updateDwd(
@Param("orgId", ParseIntPipe) orgId: number,
@GetUser() dwdServiceAccountUser: User,
@Body() body: UpdateDwdInput,
@Param("credentialId") credentialId: string
): Promise<UpdateDwdOutput> {
const dwd = await this.dwdService.updateDwd(orgId, credentialId, dwdServiceAccountUser, body);
return {
status: SUCCESS_STATUS,
data: plainToClass(DwdOutput, dwd, { strategy: "excludeAll" }),
};
}
}
@@ -0,0 +1,17 @@
import { MembershipsModule } from "@/modules/memberships/memberships.module";
import { OrganizationsDwdController } from "@/modules/organizations/dwd/organizations-dwd.controller";
import { OrganizationsDwdRepository } from "@/modules/organizations/dwd/organizations-dwd.repository";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { RedisModule } from "@/modules/redis/redis.module";
import { StripeModule } from "@/modules/stripe/stripe.module";
import { Module } from "@nestjs/common";
import { OrganizationsDwdService } from "./services/organizations-dwd.service";
@Module({
imports: [PrismaModule, StripeModule, RedisModule, MembershipsModule],
providers: [OrganizationsDwdService, OrganizationsDwdRepository, OrganizationsRepository],
controllers: [OrganizationsDwdController],
})
export class OrganizationsDwdModule {}
@@ -0,0 +1,28 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { Injectable } from "@nestjs/common";
import { Prisma } from "@calcom/prisma/client";
@Injectable()
export class OrganizationsDwdRepository {
constructor(private readonly dbRead: PrismaReadService) {}
async findById(dwdId: string) {
return this.dbRead.prisma.domainWideDelegation.findUnique({ where: { id: dwdId } });
}
async findByIdWithWorkspacePlatform(dwdId: string) {
return this.dbRead.prisma.domainWideDelegation.findUnique({
where: { id: dwdId },
include: { workspacePlatform: true },
});
}
async updateIncludeWorkspacePlatform(dwdId: string, data: Prisma.DomainWideDelegationUncheckedUpdateInput) {
return this.dbRead.prisma.domainWideDelegation.update({
where: { id: dwdId },
data,
include: { workspacePlatform: true },
});
}
}
@@ -0,0 +1,20 @@
import { DwdOutput } from "@/modules/organizations/dwd/outputs/dwd.output";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class CreateDwdOutput {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({
type: DwdOutput,
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => DwdOutput)
data!: DwdOutput;
}
@@ -0,0 +1,56 @@
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsBoolean, IsDate, IsInt, IsObject, IsString, ValidateNested } from "class-validator";
class WorkspacePlatformDto {
@ApiProperty()
@IsString()
@Expose()
name!: string;
@ApiProperty()
@IsString()
@Expose()
slug!: string;
}
export class DwdOutput {
@ApiProperty()
@IsString()
@Expose()
id!: string;
@ApiProperty()
@IsBoolean()
@Expose()
enabled!: boolean;
@ApiProperty()
@IsString()
@Expose()
domain!: string;
@ApiProperty()
@IsInt()
@Expose()
organizationId!: number;
@ApiProperty({ type: WorkspacePlatformDto })
@Type(() => WorkspacePlatformDto)
@IsObject()
@ValidateNested()
@Expose()
workspacePlatform!: WorkspacePlatformDto;
@ApiProperty()
@Type(() => Date)
@IsDate()
@Expose()
createdAt!: Date;
@ApiProperty()
@Type(() => Date)
@IsDate()
@Expose()
updatedAt!: Date;
}
@@ -0,0 +1,20 @@
import { DwdOutput } from "@/modules/organizations/dwd/outputs/dwd.output";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class UpdateDwdOutput {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({
type: DwdOutput,
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => DwdOutput)
data!: DwdOutput;
}
@@ -0,0 +1,62 @@
import { CreateDwdInput } from "@/modules/organizations/dwd/inputs/create-dwd.input";
import {
GoogleServiceAccountKeyInput,
MicrosoftServiceAccountKeyInput,
} from "@/modules/organizations/dwd/inputs/service-account-key.input";
import { UpdateDwdInput } from "@/modules/organizations/dwd/inputs/update-dwd.input";
import { OrganizationsDwdRepository } from "@/modules/organizations/dwd/organizations-dwd.repository";
import { DwdOutput } from "@/modules/organizations/dwd/outputs/dwd.output";
import { Injectable, NotFoundException } from "@nestjs/common";
import { User } from "@prisma/client";
import { addDwd, toggleDwdEnabled, encryptServiceAccountKey } from "@calcom/platform-libraries";
@Injectable()
export class OrganizationsDwdService {
constructor(private readonly organizationsDwdRepository: OrganizationsDwdRepository) {}
async createDwd(orgId: number, dwdServiceAccountUser: User, body: CreateDwdInput) {
console.log("asap body", JSON.stringify(body, null, 2));
const dwd = await addDwd({
input: body,
ctx: { user: { id: dwdServiceAccountUser.id, organizationId: orgId } },
});
return dwd;
}
async updateDwd(orgId: number, dwdId: string, dwdServiceAccountUser: User, body: UpdateDwdInput) {
if (body.enabled !== undefined) {
await this.updateDwdEnabled(orgId, dwdId, dwdServiceAccountUser, body.enabled);
}
if (body.serviceAccountKey !== undefined) {
await this.updateDwdServiceAccountKey(dwdId, body.serviceAccountKey);
}
const dwd = await this.organizationsDwdRepository.findByIdWithWorkspacePlatform(dwdId);
if (!dwd) {
throw new NotFoundException(`DWD with id ${dwdId} not found`);
}
return dwd;
}
async updateDwdEnabled(orgId: number, dwdId: string, dwdServiceAccountUser: User, enabled: boolean) {
const handlerUser = {
id: dwdServiceAccountUser.id,
email: dwdServiceAccountUser.email,
organizationId: orgId,
};
const handlerBody = { id: dwdId, enabled };
const dwd = await toggleDwdEnabled(handlerUser, handlerBody);
return dwd;
}
async updateDwdServiceAccountKey(
dwdId: string,
serviceAccountKey: GoogleServiceAccountKeyInput | MicrosoftServiceAccountKeyInput
) {
const encryptedServiceAccountKey = encryptServiceAccountKey(serviceAccountKey);
const dwd = await this.organizationsDwdRepository.updateIncludeWorkspacePlatform(dwdId, {
serviceAccountKey: encryptedServiceAccountKey,
});
return dwd;
}
}
@@ -11,6 +11,7 @@ import { OrganizationAttributesService } from "@/modules/organizations/attribute
import { OrganizationAttributeOptionRepository } from "@/modules/organizations/attributes/options/organization-attribute-options.repository";
import { OrganizationsAttributesOptionsController } from "@/modules/organizations/attributes/options/organizations-attributes-options.controller";
import { OrganizationAttributeOptionService } from "@/modules/organizations/attributes/options/services/organization-attributes-option.service";
import { OrganizationsDwdModule } from "@/modules/organizations/dwd/organizations-dwd.module";
import { OrganizationsEventTypesController } from "@/modules/organizations/event-types/organizations-event-types.controller";
import { OrganizationsEventTypesRepository } from "@/modules/organizations/event-types/organizations-event-types.repository";
import { OutputTeamEventTypesResponsePipe } from "@/modules/organizations/event-types/pipes/team-event-types-response.transformer";
@@ -64,6 +65,7 @@ import { Module } from "@nestjs/common";
EventTypesModule_2024_06_14,
TeamsEventTypesModule,
TeamsModule,
OrganizationsDwdModule,
OrganizationsOrganizationsModule,
OrganizationsTeamsRoutingFormsModule,
],