feat: v2 managed organizations (#19341)

* refactor: allow non unique PlatformBilling customerId

* feat: add PlatformBilling managed organizations fields

* feat: ManagedOrganization table

* refactor: bill overdue based on teamId

* refactor: restructure organizations module

* wip: organizations endpoints

* Revert "wip: organizations endpoints"

This reverts commit 0e9e66fc74f31da436f12930c1b6597c650ed621.

* refactor: unique index for managed organizations

* wip: organizations endpoints

* wip: create managed organization

* remove unecessary membership check because we have guard

* feat: create managed org

* feat: get managed org and orgs

* feat: update and delete managed orgs

* wip: api key logic

* feat: allow variable api key length

* feat: refresh managed org api key

* feat: create managed org OAuth clients using api key

* finish merge main

* chore: bump platform libraries

* tests: fix and add more tests to api-auth.strategy.e2e

* refactor: dont request managed org slug and handle metadata as object

* revert: billing service and repository update overdue based on sub and customer ids

* refactor: v2 OAuth client permissions (#19501)

* refactor: v2 permissions as string array

* refactor: frontend work with permissions as string

* tests: test '*' permissions

* fix:managed org creator have profile & test can fetch oauth client

* fix: tests

* fix: OAuthClientCard on frontend

* fix: tests
This commit is contained in:
Lauris Skraucis authored and GitHub committed 2025-02-25 18:10:46 -07:00
1 parent e4ab8d87c4
commit a44bcafcf2
192 files changed
+9103 -619

No files matched your search

@@ -3,8 +3,7 @@ import { AppModule } from "@/app.module";
import { HttpExceptionFilter } from "@/filters/http-exception.filter";
import { PrismaExceptionFilter } from "@/filters/prisma-exception.filter";
import { AuthModule } from "@/modules/auth/auth.module";
import { NextAuthStrategy } from "@/modules/auth/strategies/next-auth/next-auth.strategy";
import { UpdateOAuthClientInput } from "@/modules/oauth-clients/inputs/update-oauth-client.input";
import { ApiAuthStrategy } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { OAuthClientModule } from "@/modules/oauth-clients/oauth-client.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { UsersModule } from "@/modules/users/users.module";
@@ -15,14 +14,27 @@ import { Membership, PlatformOAuthClient, Team, User } from "@prisma/client";
import * as request from "supertest";
import { PlatformBillingRepositoryFixture } from "test/fixtures/repository/billing.repository.fixture";
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { NextAuthMockStrategy } from "test/mocks/next-auth-mock.strategy";
import { ApiAuthMockStrategy } from "test/mocks/api-auth-mock.strategy";
import { randomString } from "test/utils/randomString";
import { withNextAuth } from "test/utils/withNextAuth";
import { withApiAuth } from "test/utils/withApiAuth";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { CreateOAuthClientInput } from "@calcom/platform-types";
import {
APPS_READ,
APPS_WRITE,
BOOKING_READ,
BOOKING_WRITE,
EVENT_TYPE_READ,
EVENT_TYPE_WRITE,
PROFILE_READ,
PROFILE_WRITE,
SCHEDULE_READ,
SCHEDULE_WRITE,
SUCCESS_STATUS,
} from "@calcom/platform-constants";
import type { CreateOAuthClientInput, UpdateOAuthClientInput } from "@calcom/platform-types";
import { ApiSuccessResponse } from "@calcom/platform-types";
describe("OAuth Clients Endpoints", () => {
@@ -72,15 +84,15 @@ describe("OAuth Clients Endpoints", () => {
const userEmail = `oauth-clients-user-${randomString()}@api.com`;
beforeAll(async () => {
const moduleRef = await withNextAuth(
const moduleRef = await withApiAuth(
userEmail,
Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter],
imports: [AppModule, OAuthClientModule, UsersModule, AuthModule, PrismaModule],
})
).compile();
const strategy = moduleRef.get(NextAuthStrategy);
expect(strategy).toBeInstanceOf(NextAuthMockStrategy);
const strategy = moduleRef.get(ApiAuthStrategy);
expect(strategy).toBeInstanceOf(ApiAuthMockStrategy);
usersFixtures = new UserRepositoryFixture(moduleRef);
membershipFixtures = new MembershipRepositoryFixture(moduleRef);
teamFixtures = new TeamRepositoryFixture(moduleRef);
@@ -123,6 +135,7 @@ describe("OAuth Clients Endpoints", () => {
let membershipFixtures: MembershipRepositoryFixture;
let teamFixtures: TeamRepositoryFixture;
let platformBillingRepositoryFixture: PlatformBillingRepositoryFixture;
let oAuthClientsRepositoryFixture: OAuthClientRepositoryFixture;
let user: User;
let org: Team;
@@ -130,19 +143,20 @@ describe("OAuth Clients Endpoints", () => {
const userEmail = `oauth-clients-user-${randomString()}@api.com`;
beforeAll(async () => {
const moduleRef = await withNextAuth(
const moduleRef = await withApiAuth(
userEmail,
Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter],
imports: [AppModule, OAuthClientModule, UsersModule, AuthModule, PrismaModule],
})
).compile();
const strategy = moduleRef.get(NextAuthStrategy);
expect(strategy).toBeInstanceOf(NextAuthMockStrategy);
const strategy = moduleRef.get(ApiAuthStrategy);
expect(strategy).toBeInstanceOf(ApiAuthMockStrategy);
usersFixtures = new UserRepositoryFixture(moduleRef);
membershipFixtures = new MembershipRepositoryFixture(moduleRef);
teamFixtures = new TeamRepositoryFixture(moduleRef);
platformBillingRepositoryFixture = new PlatformBillingRepositoryFixture(moduleRef);
oAuthClientsRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
user = await usersFixtures.create({
email: userEmail,
@@ -218,17 +232,17 @@ describe("OAuth Clients Endpoints", () => {
membership = await membershipFixtures.addUserToOrg(user, org, "ADMIN", true);
});
it(`/POST`, () => {
it(`/POST`, async () => {
const body: CreateOAuthClientInput = {
name: oAuthClientName,
redirectUris: ["http://test-oauth-client.com"],
permissions: 32,
permissions: ["BOOKING_READ", "PROFILE_WRITE"],
};
return request(app.getHttpServer())
.post("/api/v2/oauth-clients")
.send(body)
.expect(201)
.then((response) => {
.then(async (response) => {
const responseBody: ApiSuccessResponse<{ clientId: string; clientSecret: string }> =
response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
@@ -239,6 +253,9 @@ describe("OAuth Clients Endpoints", () => {
clientId: responseBody.data.clientId,
clientSecret: responseBody.data.clientSecret,
};
const dbOAuthClient = await oAuthClientsRepositoryFixture.get(client.clientId);
expect(dbOAuthClient).toBeDefined();
expect(dbOAuthClient?.permissions).toEqual(BOOKING_READ + PROFILE_WRITE);
});
});
it(`/GET`, () => {
@@ -291,7 +308,18 @@ describe("OAuth Clients Endpoints", () => {
let membership: Membership;
let client: { clientId: string; clientSecret: string };
const oAuthClientName = `oauth-clients-owner-${randomString()}`;
const oAuthClientPermissions = 32;
const oAuthClientPermissions: CreateOAuthClientInput["permissions"] = [
"EVENT_TYPE_READ",
"EVENT_TYPE_WRITE",
"BOOKING_READ",
"BOOKING_WRITE",
"SCHEDULE_READ",
"SCHEDULE_WRITE",
"APPS_READ",
"APPS_WRITE",
"PROFILE_READ",
"PROFILE_WRITE",
];
beforeAll(async () => {
membership = await membershipFixtures.addUserToOrg(user, org, "OWNER", true);
@@ -301,13 +329,13 @@ describe("OAuth Clients Endpoints", () => {
const body: CreateOAuthClientInput = {
name: oAuthClientName,
redirectUris: ["http://test-oauth-client.com"],
permissions: 32,
permissions: ["*"],
};
return request(app.getHttpServer())
.post("/api/v2/oauth-clients")
.send(body)
.expect(201)
.then((response) => {
.then(async (response) => {
const responseBody: ApiSuccessResponse<{ clientId: string; clientSecret: string }> =
response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
@@ -318,6 +346,20 @@ describe("OAuth Clients Endpoints", () => {
clientId: responseBody.data.clientId,
clientSecret: responseBody.data.clientSecret,
};
const dbOAuthClient = await oAuthClientsRepositoryFixture.get(client.clientId);
expect(dbOAuthClient).toBeDefined();
expect(dbOAuthClient?.permissions).toEqual(
EVENT_TYPE_READ +
EVENT_TYPE_WRITE +
BOOKING_READ +
BOOKING_WRITE +
SCHEDULE_READ +
SCHEDULE_WRITE +
APPS_READ +
APPS_WRITE +
PROFILE_READ +
PROFILE_WRITE
);
});
});
@@ -1,8 +1,7 @@
import { getEnv } from "@/env";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { GetOrgId } from "@/modules/auth/decorators/get-org-id/get-org-id.decorator";
import { MembershipRoles } from "@/modules/auth/decorators/roles/membership-roles.decorator";
import { NextAuthGuard } from "@/modules/auth/guards/next-auth/next-auth.guard";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { OrganizationRolesGuard } from "@/modules/auth/guards/organization-roles/organization-roles.guard";
import { GetManagedUsersOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/get-managed-users.output";
import { ManagedUserOutput } from "@/modules/oauth-clients/controllers/oauth-client-users/outputs/managed-user.output";
@@ -10,11 +9,9 @@ import { CreateOAuthClientResponseDto } from "@/modules/oauth-clients/controller
import { GetOAuthClientResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientResponse.dto";
import { GetOAuthClientsResponseDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientsResponse.dto";
import { OAuthClientGuard } from "@/modules/oauth-clients/guards/oauth-client-guard";
import { UpdateOAuthClientInput } from "@/modules/oauth-clients/inputs/update-oauth-client.input";
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
import { OrganizationsRepository } from "@/modules/organizations/organizations.repository";
import { UsersService } from "@/modules/users/services/users.service";
import { UserWithProfile } from "@/modules/users/users.repository";
import { OAuthClientsService } from "@/modules/oauth-clients/services/oauth-clients/oauth-clients.service";
import { OrganizationsRepository } from "@/modules/organizations/index/organizations.repository";
import { UsersRepository } from "@/modules/users/users.repository";
import {
Body,
@@ -33,15 +30,14 @@ import {
BadRequestException,
} from "@nestjs/common";
import {
ApiTags as DocsTags,
ApiExcludeController as DocsExcludeController,
ApiOperation as DocsOperation,
ApiCreatedResponse as DocsCreatedResponse,
ApiTags,
} from "@nestjs/swagger";
import { User, MembershipRole } from "@prisma/client";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { CreateOAuthClientInput } from "@calcom/platform-types";
import { CreateOAuthClientInput, UpdateOAuthClientInput } from "@calcom/platform-types";
import { Pagination } from "@calcom/platform-types";
const AUTH_DOCUMENTATION = `⚠️ First, this endpoint requires \`Cookie: next-auth.session-token=eyJhbGciOiJ\` header. Log into Cal web app using owner of organization that was created after visiting \`/settings/organizations/new\`, refresh swagger docs, and the cookie will be added to requests automatically to pass the NextAuthGuard.
@@ -51,15 +47,16 @@ Second, make sure that the logged in user has organizationId set to pass the Org
path: "/v2/oauth-clients",
version: API_VERSIONS_VALUES,
})
@UseGuards(NextAuthGuard, OrganizationRolesGuard)
@ApiTags("OAuth Clients")
@UseGuards(ApiAuthGuard, OrganizationRolesGuard)
export class OAuthClientsController {
private readonly logger = new Logger("OAuthClientController");
constructor(
private readonly oauthClientRepository: OAuthClientRepository,
private readonly oAuthClientsService: OAuthClientsService,
private readonly userRepository: UsersRepository,
private readonly teamsRepository: OrganizationsRepository,
private usersService: UsersService
private readonly teamsRepository: OrganizationsRepository
) {}
@Post("/")
@@ -71,10 +68,9 @@ export class OAuthClientsController {
type: CreateOAuthClientResponseDto,
})
async createOAuthClient(
@GetUser() user: UserWithProfile,
@GetOrgId() organizationId: number,
@Body() body: CreateOAuthClientInput
): Promise<CreateOAuthClientResponseDto> {
const organizationId = this.usersService.getUserMainOrgId(user) as number;
this.logger.log(
`For organisation ${organizationId} creating OAuth Client with data: ${JSON.stringify(body)}`
);
@@ -84,14 +80,11 @@ export class OAuthClientsController {
throw new BadRequestException("Team is not subscribed, cannot create an OAuth Client.");
}
const { id, secret } = await this.oauthClientRepository.createOAuthClient(organizationId, body);
const oAuthClientCredentials = await this.oAuthClientsService.createOAuthClient(organizationId, body);
return {
status: SUCCESS_STATUS,
data: {
clientId: id,
clientSecret: secret,
},
data: oAuthClientCredentials,
};
}
@@ -99,10 +92,8 @@ export class OAuthClientsController {
@HttpCode(HttpStatus.OK)
@MembershipRoles([MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER])
@DocsOperation({ description: AUTH_DOCUMENTATION })
async getOAuthClients(@GetUser() user: UserWithProfile): Promise<GetOAuthClientsResponseDto> {
const organizationId = this.usersService.getUserMainOrgId(user) as number;
const clients = await this.oauthClientRepository.getOrganizationOAuthClients(organizationId);
async getOAuthClients(@GetOrgId() organizationId: number): Promise<GetOAuthClientsResponseDto> {
const clients = await this.oAuthClientsService.getOAuthClients(organizationId);
return { status: SUCCESS_STATUS, data: clients };
}
@@ -112,11 +103,7 @@ export class OAuthClientsController {
@DocsOperation({ description: AUTH_DOCUMENTATION })
@UseGuards(OAuthClientGuard)
async getOAuthClientById(@Param("clientId") clientId: string): Promise<GetOAuthClientResponseDto> {
const client = await this.oauthClientRepository.getOAuthClient(clientId);
if (!client) {
throw new NotFoundException(`OAuth client with ID ${clientId} not found`);
}
const client = await this.oAuthClientsService.getOAuthClientById(clientId);
return { status: SUCCESS_STATUS, data: client };
}
@@ -149,8 +136,7 @@ export class OAuthClientsController {
@Body() body: UpdateOAuthClientInput
): Promise<GetOAuthClientResponseDto> {
this.logger.log(`For client ${clientId} updating OAuth Client with data: ${JSON.stringify(body)}`);
const client = await this.oauthClientRepository.updateOAuthClient(clientId, body);
const client = await this.oAuthClientsService.updateOAuthClient(clientId, body);
return { status: SUCCESS_STATUS, data: client };
}
@@ -161,7 +147,7 @@ export class OAuthClientsController {
@UseGuards(OAuthClientGuard)
async deleteOAuthClient(@Param("clientId") clientId: string): Promise<GetOAuthClientResponseDto> {
this.logger.log(`Deleting OAuth Client with ID: ${clientId}`);
const client = await this.oauthClientRepository.deleteOAuthClient(clientId);
const client = await this.oAuthClientsService.deleteOAuthClient(clientId);
return { status: SUCCESS_STATUS, data: client };
}
@@ -1,53 +1,9 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
IsArray,
ValidateNested,
IsEnum,
IsString,
IsNumber,
IsOptional,
IsDate,
IsNotEmptyObject,
} from "class-validator";
import { ValidateNested, IsEnum, IsNotEmptyObject } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
export class PlatformOAuthClientDto {
@ApiProperty({ example: "clsx38nbl0001vkhlwin9fmt0" })
@IsString()
id!: string;
@ApiProperty({ example: "MyClient" })
@IsString()
name!: string;
@ApiProperty({ example: "secretValue" })
@IsString()
secret!: string;
@ApiProperty({ example: 3 })
@IsNumber()
permissions!: number;
@ApiPropertyOptional({ example: "https://example.com/logo.png" })
@IsOptional()
@IsString()
logo!: string | null;
@ApiProperty({ example: ["https://example.com/callback"] })
@IsArray()
@IsString({ each: true })
redirectUris!: string[];
@ApiProperty({ example: 1 })
@IsNumber()
organizationId!: number;
@ApiProperty({ example: "2024-03-23T08:33:21.851Z", type: Date })
@IsDate()
createdAt!: Date;
}
import { PlatformOAuthClientDto } from "@calcom/platform-types";
export class GetOAuthClientResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@@ -1,9 +1,9 @@
import { PlatformOAuthClientDto } from "@/modules/oauth-clients/controllers/oauth-clients/responses/GetOAuthClientResponse.dto";
import { ApiProperty } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsArray, ValidateNested, IsEnum } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { PlatformOAuthClientDto } from "@calcom/platform-types";
export class GetOAuthClientsResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })