Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Org Webhooks API V2 #16274

Merged
merged 22 commits into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationsWebhooksRepository } from "@/modules/organizations/repositories/organizations-webhooks.repository";
import { RedisService } from "@/modules/redis/redis.service";
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from "@nestjs/common";
import { Request } from "express";

import { Team } from "@calcom/prisma/client";

type CachedData = {
org?: Team;
canAccess?: boolean;
};

@Injectable()
export class IsWebhookInOrg implements CanActivate {
constructor(
private organizationsRepository: OrganizationsRepository,
private organizationsWebhooksRepository: OrganizationsWebhooksRepository,
private readonly redisService: RedisService
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
let canAccess = false;
const request = context.switchToHttp().getRequest<Request & { organization: Team }>();
const webhookId: string = request.params.webhookId;
const organizationId: string = request.params.orgId;

if (!organizationId) {
throw new ForbiddenException("No organization id found in request params.");
}
if (!webhookId) {
throw new ForbiddenException("No webhook id found in request params.");
}

const REDIS_CACHE_KEY = `apiv2:org:${webhookId}:guard:isWebhookInOrg`;
const cachedData = await this.redisService.redis.get(REDIS_CACHE_KEY);

if (cachedData) {
const { org: cachedOrg, canAccess: cachedCanAccess } = JSON.parse(cachedData) as CachedData;
if (cachedOrg?.id === Number(organizationId) && cachedCanAccess !== undefined) {
request.organization = cachedOrg;
return cachedCanAccess;
}
}

const org = await this.organizationsRepository.findById(Number(organizationId));

if (org?.isOrganization) {
const isWebhookInOrg = await this.organizationsWebhooksRepository.findOrgWebhook(
Number(organizationId),
webhookId
);
if (isWebhookInOrg) canAccess = true;
}

if (org) {
await this.redisService.redis.set(
REDIS_CACHE_KEY,
JSON.stringify({ org: org, canAccess } satisfies CachedData),
"EX",
300
);
}

return canAccess;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.decorator";
import { GetMembership } from "@/modules/auth/decorators/get-membership/get-membership.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";
Expand Down Expand Up @@ -36,7 +35,6 @@ import { plainToClass } from "class-transformer";

import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { SkipTakePagination } from "@calcom/platform-types";
import { Membership } from "@calcom/prisma/client";

@Controller({
path: "/v2/organizations/:orgId/memberships",
Expand Down Expand Up @@ -89,7 +87,11 @@ export class OrganizationsMembershipsController {
@UseGuards(IsMembershipInOrg)
@Get("/:membershipId")
@HttpCode(HttpStatus.OK)
async getUserSchedule(@GetMembership() membership: Membership): Promise<GetOrgMembership> {
async getOrgMembership(
alishaz-polymath marked this conversation as resolved.
Show resolved Hide resolved
@Param("orgId", ParseIntPipe) orgId: number,
@Param("membershipId", ParseIntPipe) membershipId: number
): Promise<GetOrgMembership> {
const membership = await this.organizationsMembershipService.getOrgMembership(orgId, membershipId);
return {
status: SUCCESS_STATUS,
data: plainToClass(OrgMembershipOutputDto, membership, { strategy: "excludeAll" }),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { PlatformPlan } from "@/modules/auth/decorators/billing/platform-plan.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 { IsWebhookInOrg } from "@/modules/auth/guards/organizations/is-webhook-in-org.guard";
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
import { OrganizationsWebhooksService } from "@/modules/organizations/services/organizations-webhooks.service";
import { CreateWebhookInputDto } from "@/modules/webhooks/inputs/webhook.input";
import { UpdateWebhookInputDto } from "@/modules/webhooks/inputs/webhook.input";
import {
TeamWebhookOutputDto as OrgWebhookOutputDto,
TeamWebhookOutputResponseDto as OrgWebhookOutputResponseDto,
TeamWebhooksOutputResponseDto as OrgWebhooksOutputResponseDto,
} from "@/modules/webhooks/outputs/team-webhook.output";
import {
Controller,
UseGuards,
Get,
Param,
ParseIntPipe,
Query,
Delete,
Patch,
Post,
Body,
HttpCode,
HttpStatus,
} from "@nestjs/common";
import { ApiTags as DocsTags } from "@nestjs/swagger";
import { plainToClass } from "class-transformer";

import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { SkipTakePagination } from "@calcom/platform-types";

@Controller({
path: "/v2/organizations/:orgId/webhooks",
version: API_VERSIONS_VALUES,
})
@UseGuards(ApiAuthGuard, IsOrgGuard, RolesGuard, PlatformPlanGuard, IsAdminAPIEnabledGuard)
@DocsTags("Organizations Webhooks")
export class OrganizationsWebhooksController {
constructor(private organizationsWebhooksService: OrganizationsWebhooksService) {}

@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@Get("/")
@HttpCode(HttpStatus.OK)
async getAllOrgWebhooks(
@Param("orgId", ParseIntPipe) orgId: number,
@Query() queryParams: SkipTakePagination
): Promise<OrgWebhooksOutputResponseDto> {
const { skip, take } = queryParams;
const webhooks = await this.organizationsWebhooksService.getPaginatedOrgWebhooks(
orgId,
skip ?? 0,
take ?? 250
);
return {
status: SUCCESS_STATUS,
data: webhooks.map((webhook) => plainToClass(OrgWebhookOutputDto, webhook, { strategy: "excludeAll" })),
};
}

@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@Post("/")
@HttpCode(HttpStatus.CREATED)
async createOrgWebhook(
@Param("orgId", ParseIntPipe) orgId: number,
@Body() body: CreateWebhookInputDto
): Promise<OrgWebhookOutputResponseDto> {
const webhook = await this.organizationsWebhooksService.createOrgWebhook(orgId, body);
alishaz-polymath marked this conversation as resolved.
Show resolved Hide resolved
return {
status: SUCCESS_STATUS,
data: plainToClass(OrgWebhookOutputDto, webhook, { strategy: "excludeAll" }),
};
}

@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@UseGuards(IsWebhookInOrg)
@Get("/:webhookId")
@HttpCode(HttpStatus.OK)
async getOrgWebhook(
@Param("orgId", ParseIntPipe) orgId: number,
@Param("webhookId", ParseIntPipe) webhookId: string
): Promise<OrgWebhookOutputResponseDto> {
const webhook = await this.organizationsWebhooksService.getOrgWebhook(orgId, webhookId);
return {
status: SUCCESS_STATUS,
data: plainToClass(OrgWebhookOutputDto, webhook, { strategy: "excludeAll" }),
};
}

@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@UseGuards(IsWebhookInOrg)
@Delete("/:webhookId")
@HttpCode(HttpStatus.OK)
async deleteOrgWebhook(
@Param("orgId", ParseIntPipe) orgId: number,
@Param("webhookId", ParseIntPipe) webhookId: string
): Promise<OrgWebhookOutputResponseDto> {
const webhook = await this.organizationsWebhooksService.deleteOrgWebhook(orgId, webhookId);
return {
status: SUCCESS_STATUS,
data: plainToClass(OrgWebhookOutputDto, webhook, { strategy: "excludeAll" }),
};
}

@Roles("ORG_ADMIN")
@PlatformPlan("ESSENTIALS")
@UseGuards(IsWebhookInOrg)
@Patch("/:webhookId")
@HttpCode(HttpStatus.OK)
async updateOrgWebhook(
@Param("orgId", ParseIntPipe) orgId: number,
@Param("webhookId", ParseIntPipe) webhookId: string,
@Body() body: UpdateWebhookInputDto
): Promise<OrgWebhookOutputResponseDto> {
const webhook = await this.organizationsWebhooksService.updateOrgWebhook(orgId, webhookId, body);
alishaz-polymath marked this conversation as resolved.
Show resolved Hide resolved
return {
status: SUCCESS_STATUS,
data: plainToClass(OrgWebhookOutputDto, webhook, { strategy: "excludeAll" }),
};
}
}
8 changes: 8 additions & 0 deletions apps/api/v2/src/modules/organizations/organizations.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ import { OrganizationsSchedulesController } from "@/modules/organizations/contro
import { OrganizationsTeamsMembershipsController } from "@/modules/organizations/controllers/teams/memberships/organizations-teams-memberships.controller";
import { OrganizationsTeamsController } from "@/modules/organizations/controllers/teams/organizations-teams.controller";
import { OrganizationsUsersController } from "@/modules/organizations/controllers/users/organizations-users.controller";
import { OrganizationsWebhooksController } from "@/modules/organizations/controllers/webhooks/organizations-webhooks.controller";
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { OrganizationsEventTypesRepository } from "@/modules/organizations/repositories/organizations-event-types.repository";
import { OrganizationsMembershipRepository } from "@/modules/organizations/repositories/organizations-membership.repository";
import { OrganizationSchedulesRepository } from "@/modules/organizations/repositories/organizations-schedules.repository";
import { OrganizationsTeamsMembershipsRepository } from "@/modules/organizations/repositories/organizations-teams-memberships.repository";
import { OrganizationsTeamsRepository } from "@/modules/organizations/repositories/organizations-teams.repository";
import { OrganizationsUsersRepository } from "@/modules/organizations/repositories/organizations-users.repository";
import { OrganizationsWebhooksRepository } from "@/modules/organizations/repositories/organizations-webhooks.repository";
import { InputOrganizationsEventTypesService } from "@/modules/organizations/services/event-types/input.service";
import { OrganizationsEventTypesService } from "@/modules/organizations/services/event-types/organizations-event-types.service";
import { OutputOrganizationsEventTypesService } from "@/modules/organizations/services/event-types/output.service";
Expand All @@ -24,6 +26,7 @@ import { OrganizationsSchedulesService } from "@/modules/organizations/services/
import { OrganizationsTeamsMembershipsService } from "@/modules/organizations/services/organizations-teams-memberships.service";
import { OrganizationsTeamsService } from "@/modules/organizations/services/organizations-teams.service";
import { OrganizationsUsersService } from "@/modules/organizations/services/organizations-users-service";
import { OrganizationsWebhooksService } from "@/modules/organizations/services/organizations-webhooks.service";
import { OrganizationsService } from "@/modules/organizations/services/organizations.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { RedisModule } from "@/modules/redis/redis.module";
Expand Down Expand Up @@ -60,6 +63,8 @@ import { Module } from "@nestjs/common";
OrganizationsEventTypesRepository,
OrganizationsTeamsMembershipsRepository,
OrganizationsTeamsMembershipsService,
OrganizationsWebhooksRepository,
OrganizationsWebhooksService,
],
exports: [
OrganizationsService,
Expand All @@ -71,6 +76,8 @@ import { Module } from "@nestjs/common";
OrganizationsMembershipService,
OrganizationsTeamsMembershipsRepository,
OrganizationsTeamsMembershipsService,
OrganizationsWebhooksRepository,
OrganizationsWebhooksService,
],
controllers: [
OrganizationsTeamsController,
Expand All @@ -79,6 +86,7 @@ import { Module } from "@nestjs/common";
OrganizationsMembershipsController,
OrganizationsEventTypesController,
OrganizationsTeamsMembershipsController,
OrganizationsWebhooksController,
],
})
export class OrganizationsModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import {
CreateWebhookInputDto as CreateOrgWebhookDto,
UpdateWebhookInputDto as UpdateOrgWebhookDto,
} from "@/modules/webhooks/inputs/webhook.input";
import { Injectable } from "@nestjs/common";
import { v4 } from "uuid";

@Injectable()
export class OrganizationsWebhooksRepository {
constructor(private readonly dbRead: PrismaReadService) {}

async findOrgWebhook(organizationId: number, webhookId: string) {
return this.dbRead.prisma.webhook.findUnique({
where: {
id: webhookId,
teamId: organizationId,
},
});
}

async findOrgWebhooks(organizationId: number) {
return this.dbRead.prisma.webhook.findMany({
where: {
teamId: organizationId,
},
});
}

async deleteOrgWebhook(organizationId: number, webhookId: string) {
return this.dbRead.prisma.webhook.delete({
where: {
id: webhookId,
teamId: organizationId,
},
});
}

async createOrgWebhook(organizationId: number, data: CreateOrgWebhookDto) {
return this.dbRead.prisma.webhook.create({
data: { ...data, teamId: organizationId, id: v4() },
});
}

async updateOrgWebhook(organizationId: number, webhookId: string, data: UpdateOrgWebhookDto) {
return this.dbRead.prisma.webhook.update({
data: { ...data },
where: { id: webhookId, teamId: organizationId },
});
}

async findOrgWebhooksPaginated(organizationId: number, skip: number, take: number) {
return this.dbRead.prisma.webhook.findMany({
where: {
teamId: organizationId,
},
skip,
take,
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { OrganizationsWebhooksRepository } from "@/modules/organizations/repositories/organizations-webhooks.repository";
import {
CreateWebhookInputDto as CreateOrgWebhookDto,
UpdateWebhookInputDto as UpdateOrgWebhookDto,
} from "@/modules/webhooks/inputs/webhook.input";
import { Injectable } from "@nestjs/common";

@Injectable()
export class OrganizationsWebhooksService {
constructor(private readonly organizationsWebhooksRepository: OrganizationsWebhooksRepository) {}

async getPaginatedOrgWebhooks(organizationId: number, skip = 0, take = 250) {
const webhooks = await this.organizationsWebhooksRepository.findOrgWebhooksPaginated(
organizationId,
skip,
take
);
return webhooks;
}

async getOrgWebhook(organizationId: number, webhookId: string) {
const webhook = await this.organizationsWebhooksRepository.findOrgWebhook(organizationId, webhookId);
return webhook;
}

async deleteOrgWebhook(organizationId: number, webhookId: string) {
const webhook = await this.organizationsWebhooksRepository.deleteOrgWebhook(organizationId, webhookId);
return webhook;
}

async updateOrgWebhook(organizationId: number, webhookId: string, data: UpdateOrgWebhookDto) {
const team = await this.organizationsWebhooksRepository.updateOrgWebhook(organizationId, webhookId, data);
return team;
}

async createOrgWebhook(organizationId: number, data: CreateOrgWebhookDto) {
const webhook = await this.organizationsWebhooksRepository.createOrgWebhook(organizationId, data);
return webhook;
}
}
Loading
Loading