chore: auth on api-v2 with api-key (#15455)
* chore: enable apiv2 auth with api keys * chore: enable apiv2 auth with api keys * chore: enable apiv2 auth with api keys * chore: enable apiv2 auth with api keys * chore: enable apiv2 auth with api keys * fixup! chore: enable apiv2 auth with api keys * fixup! Merge branch 'chore-apiv2-auth-api-key' of github.com:calcom/cal.com into chore-apiv2-auth-api-key * fixup! fixup! Merge branch 'chore-apiv2-auth-api-key' of github.com:calcom/cal.com into chore-apiv2-auth-api-key * fixup! fixup! fixup! Merge branch 'chore-apiv2-auth-api-key' of github.com:calcom/cal.com into chore-apiv2-auth-api-key
This commit is contained in:
1 parent
c5a83f4df2
commit
9a473d5b55
49 files changed
+583
-430
No files matched your search
@@ -0,0 +1,16 @@
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class ApiKeyRepository {
|
||||
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
|
||||
|
||||
async getApiKeyFromHash(hashedKey: string) {
|
||||
return this.dbRead.prisma.apiKey.findUnique({
|
||||
where: {
|
||||
hashedKey,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { ApiKeyService } from "@/modules/api-key/api-key.service";
|
||||
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
providers: [ApiKeyService],
|
||||
exports: [ApiKeyService],
|
||||
providers: [ApiKeyRepository],
|
||||
exports: [ApiKeyRepository],
|
||||
})
|
||||
export class ApiKeyModule {}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { hashAPIKey } from "@/lib/api-key";
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import type { Request } from "express";
|
||||
|
||||
@Injectable()
|
||||
export class ApiKeyService {
|
||||
constructor(private readonly dbRead: PrismaReadService) {}
|
||||
|
||||
async retrieveApiKey(request: Request) {
|
||||
const apiKey = request.get("Authorization")?.replace("Bearer ", "");
|
||||
|
||||
if (!apiKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hashedKey = hashAPIKey(apiKey.replace("cal_", ""));
|
||||
|
||||
return this.dbRead.prisma.apiKey.findUniqueOrThrow({
|
||||
where: {
|
||||
hashedKey,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { ApiKeyModule } from "@/modules/api-key/api-key.module";
|
||||
import { AccessTokenGuard } from "@/modules/auth/guards/access-token/access-token.guard";
|
||||
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||
import { NextAuthGuard } from "@/modules/auth/guards/next-auth/next-auth.guard";
|
||||
import { AccessTokenStrategy } from "@/modules/auth/strategies/access-token/access-token.strategy";
|
||||
import { ApiKeyAuthStrategy } from "@/modules/auth/strategies/api-key-auth/api-key-auth.strategy";
|
||||
import { ApiAuthStrategy } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
|
||||
import { NextAuthStrategy } from "@/modules/auth/strategies/next-auth/next-auth.strategy";
|
||||
import { DeploymentsModule } from "@/modules/deployments/deployments.module";
|
||||
import { MembershipsModule } from "@/modules/memberships/memberships.module";
|
||||
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
|
||||
import { RedisModule } from "@/modules/redis/redis.module";
|
||||
@@ -13,15 +13,16 @@ import { Module } from "@nestjs/common";
|
||||
import { PassportModule } from "@nestjs/passport";
|
||||
|
||||
@Module({
|
||||
imports: [PassportModule, RedisModule, ApiKeyModule, UsersModule, MembershipsModule, TokensModule],
|
||||
providers: [
|
||||
ApiKeyAuthStrategy,
|
||||
NextAuthGuard,
|
||||
NextAuthStrategy,
|
||||
AccessTokenGuard,
|
||||
AccessTokenStrategy,
|
||||
OAuthFlowService,
|
||||
imports: [
|
||||
PassportModule,
|
||||
RedisModule,
|
||||
ApiKeyModule,
|
||||
UsersModule,
|
||||
MembershipsModule,
|
||||
TokensModule,
|
||||
DeploymentsModule,
|
||||
],
|
||||
exports: [NextAuthGuard, AccessTokenGuard],
|
||||
providers: [NextAuthGuard, NextAuthStrategy, ApiAuthGuard, ApiAuthStrategy, OAuthFlowService],
|
||||
exports: [NextAuthGuard, ApiAuthGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -1,26 +1,33 @@
|
||||
import { UserWithProfile } from "@/modules/users/users.repository";
|
||||
import { ExecutionContext } from "@nestjs/common";
|
||||
import { createParamDecorator } from "@nestjs/common";
|
||||
import { User } from "@prisma/client";
|
||||
|
||||
export const GetUser = createParamDecorator<keyof User | (keyof User)[], ExecutionContext>((data, ctx) => {
|
||||
export type GetUserReturnType = UserWithProfile & { isSystemAdmin: boolean };
|
||||
|
||||
export const GetUser = createParamDecorator<
|
||||
keyof GetUserReturnType | (keyof GetUserReturnType)[],
|
||||
ExecutionContext
|
||||
>((data, ctx) => {
|
||||
const request = ctx.switchToHttp().getRequest();
|
||||
const user = request.user as User;
|
||||
const user = request.user as GetUserReturnType;
|
||||
|
||||
if (!user) {
|
||||
throw new Error("GetUser decorator : User not found");
|
||||
}
|
||||
|
||||
user.isSystemAdmin = user.role === "ADMIN";
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
return data.reduce((prev, curr) => {
|
||||
return {
|
||||
...prev,
|
||||
[curr]: request.user[curr],
|
||||
[curr]: user[curr],
|
||||
};
|
||||
}, {});
|
||||
}
|
||||
|
||||
if (data) {
|
||||
return request.user[data];
|
||||
return user[data];
|
||||
}
|
||||
|
||||
return user;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { AuthGuard } from "@nestjs/passport";
|
||||
|
||||
export class AccessTokenGuard extends AuthGuard("access-token") {
|
||||
export class ApiAuthGuard extends AuthGuard("api-auth") {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
File renamed without changes.
@@ -1,6 +1,7 @@
|
||||
import { TokensRepository } from "@/modules/tokens/tokens.repository";
|
||||
import { createMock } from "@golevelup/ts-jest";
|
||||
import { ExecutionContext } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
|
||||
import { APPS_WRITE, SCHEDULE_READ, SCHEDULE_WRITE } from "@calcom/platform-constants";
|
||||
@@ -13,7 +14,7 @@ describe("PermissionsGuard", () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
reflector = new Reflector();
|
||||
guard = new PermissionsGuard(reflector, createMock<TokensRepository>());
|
||||
guard = new PermissionsGuard(reflector, createMock<TokensRepository>(), createMock<ConfigService>());
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { isApiKey } from "@/lib/api-key";
|
||||
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
|
||||
import { TokensRepository } from "@/modules/tokens/tokens.repository";
|
||||
import { Injectable, CanActivate, ExecutionContext } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
|
||||
import { hasPermissions } from "@calcom/platform-utils";
|
||||
|
||||
@Injectable()
|
||||
export class PermissionsGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector, private tokensRepository: TokensRepository) {}
|
||||
constructor(
|
||||
private reflector: Reflector,
|
||||
private tokensRepository: TokensRepository,
|
||||
private readonly config: ConfigService
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const requiredPermissions = this.reflector.get(Permissions, context.getHandler());
|
||||
@@ -17,13 +23,18 @@ export class PermissionsGuard implements CanActivate {
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const accessToken = request.get("Authorization")?.replace("Bearer ", "");
|
||||
const authString = request.get("Authorization")?.replace("Bearer ", "");
|
||||
|
||||
if (!accessToken) {
|
||||
if (!authString) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const oAuthClientPermissions = await this.getOAuthClientPermissions(accessToken);
|
||||
// only check permissions for accessTokens attached to an oAuth Client
|
||||
if (isApiKey(authString, this.config.get("api.apiKeyPrefix") ?? "cal_")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const oAuthClientPermissions = await this.getOAuthClientPermissions(authString);
|
||||
|
||||
if (!oAuthClientPermissions) {
|
||||
return false;
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
import { BaseStrategy } from "@/lib/passport/strategies/types";
|
||||
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
|
||||
import { TokensRepository } from "@/modules/tokens/tokens.repository";
|
||||
import { UserWithProfile, UsersRepository } from "@/modules/users/users.repository";
|
||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import type { Request } from "express";
|
||||
|
||||
import { INVALID_ACCESS_TOKEN } from "@calcom/platform-constants";
|
||||
|
||||
@Injectable()
|
||||
export class AccessTokenStrategy extends PassportStrategy(BaseStrategy, "access-token") {
|
||||
constructor(
|
||||
private readonly oauthFlowService: OAuthFlowService,
|
||||
private readonly tokensRepository: TokensRepository,
|
||||
private readonly userRepository: UsersRepository
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async authenticate(request: Request) {
|
||||
try {
|
||||
const accessToken = request.get("Authorization")?.replace("Bearer ", "");
|
||||
const requestOrigin = request.get("Origin");
|
||||
|
||||
if (!accessToken) {
|
||||
throw new UnauthorizedException(INVALID_ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
const accessTokenValid = await this.oauthFlowService.validateAccessToken(accessToken);
|
||||
if (!accessTokenValid) {
|
||||
throw new UnauthorizedException(INVALID_ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
const client = await this.tokensRepository.getAccessTokenClient(accessToken);
|
||||
if (!client) {
|
||||
throw new UnauthorizedException("OAuth client not found given the access token");
|
||||
}
|
||||
|
||||
if (requestOrigin && !client.redirectUris.some((uri) => uri.startsWith(requestOrigin))) {
|
||||
throw new UnauthorizedException(
|
||||
`Invalid request origin - please open https://app.cal.com/settings/platform and add the origin '${requestOrigin}' to the 'Redirect uris' of your OAuth client.`
|
||||
);
|
||||
}
|
||||
|
||||
const ownerId = await this.tokensRepository.getAccessTokenOwnerId(accessToken);
|
||||
|
||||
if (!ownerId) {
|
||||
throw new UnauthorizedException(INVALID_ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
const user: UserWithProfile | null = await this.userRepository.findByIdWithProfile(ownerId);
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException(INVALID_ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
return this.success(user);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return this.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import appConfig from "@/config/app";
|
||||
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
|
||||
import { DeploymentsRepository } from "@/modules/deployments/deployments.repository";
|
||||
import { DeploymentsService } from "@/modules/deployments/deployments.service";
|
||||
import { JwtService } from "@/modules/jwt/jwt.service";
|
||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { TokensRepository } from "@/modules/tokens/tokens.repository";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { ExecutionContext, HttpException } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { ConfigModule } from "@nestjs/config";
|
||||
import { JwtService as NestJwtService } from "@nestjs/jwt";
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { PlatformOAuthClient, Team, User } from "@prisma/client";
|
||||
import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture";
|
||||
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
|
||||
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
|
||||
import { TokensRepositoryFixture } from "test/fixtures/repository/tokens.repository.fixture";
|
||||
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
||||
import { MockedRedisService } from "test/mocks/mock-redis-service";
|
||||
|
||||
import { ApiAuthStrategy } from "./api-auth.strategy";
|
||||
|
||||
describe("ApiAuthStrategy", () => {
|
||||
let strategy: ApiAuthStrategy;
|
||||
let userRepositoryFixture: UserRepositoryFixture;
|
||||
let tokensRepositoryFixture: TokensRepositoryFixture;
|
||||
let teamRepositoryFixture: TeamRepositoryFixture;
|
||||
let organization: Team;
|
||||
let oAuthClient: PlatformOAuthClient;
|
||||
let apiKeysRepositoryFixture: ApiKeysRepositoryFixture;
|
||||
let oAuthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
||||
const validApiKeyEmail = "[email protected]";
|
||||
const validAccessTokenEmail = "[email protected]";
|
||||
let validApiKeyUser: User;
|
||||
let validAccessTokenUser: User;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
ignoreEnvFile: true,
|
||||
isGlobal: true,
|
||||
load: [appConfig],
|
||||
}),
|
||||
],
|
||||
providers: [
|
||||
MockedRedisService,
|
||||
ApiAuthStrategy,
|
||||
ConfigService,
|
||||
OAuthFlowService,
|
||||
UsersRepository,
|
||||
ApiKeyRepository,
|
||||
DeploymentsService,
|
||||
OAuthClientRepository,
|
||||
PrismaReadService,
|
||||
PrismaWriteService,
|
||||
TokensRepository,
|
||||
JwtService,
|
||||
DeploymentsRepository,
|
||||
NestJwtService,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
strategy = module.get<ApiAuthStrategy>(ApiAuthStrategy);
|
||||
userRepositoryFixture = new UserRepositoryFixture(module);
|
||||
tokensRepositoryFixture = new TokensRepositoryFixture(module);
|
||||
apiKeysRepositoryFixture = new ApiKeysRepositoryFixture(module);
|
||||
teamRepositoryFixture = new TeamRepositoryFixture(module);
|
||||
oAuthClientRepositoryFixture = new OAuthClientRepositoryFixture(module);
|
||||
organization = await teamRepositoryFixture.create({ name: "organization" });
|
||||
validApiKeyUser = await userRepositoryFixture.create({
|
||||
email: validApiKeyEmail,
|
||||
});
|
||||
validAccessTokenUser = await userRepositoryFixture.create({
|
||||
email: validAccessTokenEmail,
|
||||
});
|
||||
const data = {
|
||||
logo: "logo-url",
|
||||
name: "name",
|
||||
redirectUris: ["http://localhost:3000"],
|
||||
permissions: 32,
|
||||
};
|
||||
oAuthClient = await oAuthClientRepositoryFixture.create(organization.id, data, "secret");
|
||||
});
|
||||
|
||||
describe("authenticate with strategy", () => {
|
||||
it("should return user associated with valid access token", async () => {
|
||||
console.log("HERERERER");
|
||||
const { accessToken } = await tokensRepositoryFixture.createTokens(
|
||||
validAccessTokenUser.id,
|
||||
oAuthClient.id
|
||||
);
|
||||
|
||||
console.log("Access token", accessToken);
|
||||
|
||||
const context: ExecutionContext = {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => ({
|
||||
headers: {
|
||||
authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
get: (key: string) =>
|
||||
({ Authorization: `Bearer ${accessToken}`, origin: "http://localhost:3000" }[key]),
|
||||
}),
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
const request = context.switchToHttp().getRequest();
|
||||
|
||||
const user = await strategy.authenticate(request);
|
||||
|
||||
await expect(user.id).toEqual(validAccessTokenUser.id);
|
||||
});
|
||||
|
||||
it("should return user associated with valid api key", async () => {
|
||||
const now = new Date();
|
||||
now.setDate(now.getDate() + 1);
|
||||
const { keyString } = await apiKeysRepositoryFixture.createApiKey(validApiKeyUser.id, now);
|
||||
|
||||
const context: ExecutionContext = {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => ({
|
||||
headers: {
|
||||
authorization: `Bearer cal_test_${keyString}`,
|
||||
},
|
||||
get: (key: string) =>
|
||||
({ Authorization: `Bearer cal_test_${keyString}`, origin: "http://localhost:3000" }[key]),
|
||||
}),
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
const request = context.switchToHttp().getRequest();
|
||||
|
||||
const user = await strategy.authenticate(request);
|
||||
|
||||
expect(user.id).toEqual(validApiKeyUser.id);
|
||||
});
|
||||
|
||||
it("should throw 401 if api key is invalid", async () => {
|
||||
const context: ExecutionContext = {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => ({
|
||||
headers: {
|
||||
authorization: `Bearer cal_test_}`,
|
||||
},
|
||||
get: (key: string) =>
|
||||
({ Authorization: `Bearer cal_test_badkey1234`, origin: "http://localhost:3000" }[key]),
|
||||
}),
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
const request = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
await strategy.authenticate(request);
|
||||
} catch (error) {
|
||||
if (error instanceof HttpException) {
|
||||
expect(error.getStatus()).toEqual(401);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("should throw 401 if Authorization header does not contain auth token", async () => {
|
||||
const context: ExecutionContext = {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => ({
|
||||
get: (key: string) => ({ Authorization: ``, origin: "http://localhost:3000" }[key]),
|
||||
}),
|
||||
}),
|
||||
} as ExecutionContext;
|
||||
const request = context.switchToHttp().getRequest();
|
||||
|
||||
try {
|
||||
await strategy.authenticate(request);
|
||||
} catch (error) {
|
||||
if (error instanceof HttpException) {
|
||||
expect(error.getStatus()).toEqual(401);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { hashAPIKey, isApiKey, stripApiKey } from "@/lib/api-key";
|
||||
import { BaseStrategy } from "@/lib/passport/strategies/types";
|
||||
import { ApiKeyRepository } from "@/modules/api-key/api-key-repository";
|
||||
import { DeploymentsService } from "@/modules/deployments/deployments.service";
|
||||
import { OAuthFlowService } from "@/modules/oauth-clients/services/oauth-flow.service";
|
||||
import { TokensRepository } from "@/modules/tokens/tokens.repository";
|
||||
import { UserWithProfile, UsersRepository } from "@/modules/users/users.repository";
|
||||
import { Injectable, InternalServerErrorException, UnauthorizedException } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import type { Request } from "express";
|
||||
|
||||
import { INVALID_ACCESS_TOKEN } from "@calcom/platform-constants";
|
||||
|
||||
@Injectable()
|
||||
export class ApiAuthStrategy extends PassportStrategy(BaseStrategy, "api-auth") {
|
||||
constructor(
|
||||
private readonly deploymentsService: DeploymentsService,
|
||||
private readonly config: ConfigService,
|
||||
private readonly oauthFlowService: OAuthFlowService,
|
||||
private readonly tokensRepository: TokensRepository,
|
||||
private readonly userRepository: UsersRepository,
|
||||
private readonly apiKeyRepository: ApiKeyRepository
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async authenticate(request: Request) {
|
||||
const authString = request.get("Authorization")?.replace("Bearer ", "");
|
||||
if (!authString) {
|
||||
return this.error(new UnauthorizedException("No Authorization header provided"));
|
||||
}
|
||||
|
||||
const requestOrigin = request.get("Origin");
|
||||
|
||||
try {
|
||||
const user = isApiKey(authString, this.config.get<string>("api.apiKeyPrefix") ?? "cal_")
|
||||
? await this.apiKeyStrategy(authString)
|
||||
: await this.accessTokenStrategy(authString, requestOrigin);
|
||||
|
||||
if (!user) {
|
||||
return this.error(new UnauthorizedException("No user associated with the provided token"));
|
||||
}
|
||||
|
||||
return this.success(user);
|
||||
} catch (err) {
|
||||
if (err instanceof Error) {
|
||||
return this.error(err);
|
||||
}
|
||||
return this.error(
|
||||
new InternalServerErrorException("An error occurred while authenticating the request")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async apiKeyStrategy(apiKey: string) {
|
||||
const isLicenseValid = await this.deploymentsService.checkLicense();
|
||||
if (!isLicenseValid) {
|
||||
throw new UnauthorizedException("Invalid or missing CALCOM_LICENSE_KEY environment variable");
|
||||
}
|
||||
const strippedApiKey = stripApiKey(apiKey, this.config.get<string>("api.keyPrefix"));
|
||||
const apiKeyHash = hashAPIKey(strippedApiKey);
|
||||
const keyData = await this.apiKeyRepository.getApiKeyFromHash(apiKeyHash);
|
||||
if (!keyData) {
|
||||
throw new UnauthorizedException("Your api key is not valid");
|
||||
}
|
||||
|
||||
const isKeyExpired =
|
||||
keyData.expiresAt && new Date().setHours(0, 0, 0, 0) > keyData.expiresAt.setHours(0, 0, 0, 0);
|
||||
if (isKeyExpired) {
|
||||
throw new UnauthorizedException("Your api key is expired");
|
||||
}
|
||||
|
||||
const apiKeyOwnerId = keyData.userId;
|
||||
if (!apiKeyOwnerId) {
|
||||
throw new UnauthorizedException("No user tied to this apiKey");
|
||||
}
|
||||
|
||||
const user: UserWithProfile | null = await this.userRepository.findByIdWithProfile(apiKeyOwnerId);
|
||||
return user;
|
||||
}
|
||||
|
||||
async accessTokenStrategy(accessToken: string, origin?: string) {
|
||||
const accessTokenValid = await this.oauthFlowService.validateAccessToken(accessToken);
|
||||
if (!accessTokenValid) {
|
||||
throw new UnauthorizedException(INVALID_ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
const client = await this.tokensRepository.getAccessTokenClient(accessToken);
|
||||
if (!client) {
|
||||
throw new UnauthorizedException("OAuth client not found given the access token");
|
||||
}
|
||||
|
||||
if (origin && !client.redirectUris.some((uri) => uri.startsWith(origin))) {
|
||||
throw new UnauthorizedException(
|
||||
`Invalid request origin - please open https://app.cal.com/settings/platform and add the origin '${origin}' to the 'Redirect uris' of your OAuth client.`
|
||||
);
|
||||
}
|
||||
|
||||
const ownerId = await this.tokensRepository.getAccessTokenOwnerId(accessToken);
|
||||
|
||||
if (!ownerId) {
|
||||
throw new UnauthorizedException(INVALID_ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
const user: UserWithProfile | null = await this.userRepository.findByIdWithProfile(ownerId);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import { BaseStrategy } from "@/lib/passport/strategies/types";
|
||||
import { ApiKeyService } from "@/modules/api-key/api-key.service";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { Injectable, NotFoundException, UnauthorizedException } from "@nestjs/common";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import type { Request } from "express";
|
||||
|
||||
@Injectable()
|
||||
export class ApiKeyAuthStrategy extends PassportStrategy(BaseStrategy, "api-key") {
|
||||
constructor(
|
||||
private readonly apiKeyService: ApiKeyService,
|
||||
private readonly userRepository: UsersRepository
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async authenticate(req: Request) {
|
||||
try {
|
||||
const apiKey = await this.apiKeyService.retrieveApiKey(req);
|
||||
|
||||
if (!apiKey) {
|
||||
throw new UnauthorizedException("Authorization token is missing.");
|
||||
}
|
||||
|
||||
if (apiKey.expiresAt && new Date() > apiKey.expiresAt) {
|
||||
throw new UnauthorizedException("The API key is expired.");
|
||||
}
|
||||
|
||||
const user = await this.userRepository.findById(apiKey.userId);
|
||||
if (!user) {
|
||||
throw new NotFoundException("User not found.");
|
||||
}
|
||||
|
||||
this.success(user);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return this.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextAuthPassportStrategy } from "@/lib/passport/strategies/types";
|
||||
import { UsersRepository } from "@/modules/users/users.repository";
|
||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { Injectable, InternalServerErrorException, UnauthorizedException } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import type { Request } from "express";
|
||||
@@ -33,6 +33,9 @@ export class NextAuthStrategy extends PassportStrategy(NextAuthPassportStrategy,
|
||||
return this.success(user);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) return this.error(error);
|
||||
return this.error(
|
||||
new InternalServerErrorException("An error occurred while authenticating the request")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
import { DeploymentsRepository } from "./deployments.repository";
|
||||
import { DeploymentsService } from "./deployments.service";
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
providers: [DeploymentsRepository, DeploymentsService, RedisService],
|
||||
exports: [DeploymentsRepository, DeploymentsService],
|
||||
})
|
||||
export class DeploymentsModule {}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
|
||||
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
|
||||
@Injectable()
|
||||
export class DeploymentsRepository {
|
||||
constructor(private readonly dbRead: PrismaReadService, private readonly dbWrite: PrismaWriteService) {}
|
||||
|
||||
async getDeployment() {
|
||||
return this.dbRead.prisma.deployment.findFirst({ where: { id: 1 } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { DeploymentsRepository } from "@/modules/deployments/deployments.repository";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
|
||||
const CACHING_TIME = 86400000; // 24 hours in milliseconds
|
||||
|
||||
const getLicenseCacheKey = (key: string) => `api-v2-license-key-url-${key}`;
|
||||
|
||||
type LicenseCheckResponse = {
|
||||
valid: boolean;
|
||||
};
|
||||
@Injectable()
|
||||
export class DeploymentsService {
|
||||
constructor(
|
||||
private readonly deploymentsRepository: DeploymentsRepository,
|
||||
private readonly configService: ConfigService,
|
||||
private readonly redisService: RedisService
|
||||
) {}
|
||||
|
||||
async checkLicense() {
|
||||
if (this.configService.get("e2e")) {
|
||||
return true;
|
||||
}
|
||||
let licenseKey = this.configService.get("api.licenseKey");
|
||||
|
||||
if (!licenseKey) {
|
||||
/** We try to check on DB only if env is undefined */
|
||||
const deployment = await this.deploymentsRepository.getDeployment();
|
||||
licenseKey = deployment?.licenseKey ?? undefined;
|
||||
}
|
||||
|
||||
if (!licenseKey) {
|
||||
return false;
|
||||
}
|
||||
const licenseKeyUrl = this.configService.get("api.licenseKeyUrl");
|
||||
const cachedData = await this.redisService.redis.get(getLicenseCacheKey(licenseKey));
|
||||
if (cachedData) {
|
||||
return (JSON.parse(cachedData) as LicenseCheckResponse)?.valid;
|
||||
}
|
||||
const response = await fetch(licenseKeyUrl, { mode: "cors" });
|
||||
const data = (await response.json()) as LicenseCheckResponse;
|
||||
const cacheKey = getLicenseCacheKey(licenseKey);
|
||||
this.redisService.redis.set(cacheKey, JSON.stringify(data), "EX", CACHING_TIME);
|
||||
return data.valid;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { TokenExpiredException } from "@/modules/auth/guards/access-token/token-expired.exception";
|
||||
import { TokenExpiredException } from "@/modules/auth/guards/api-auth/token-expired.exception";
|
||||
import { OAuthClientRepository } from "@/modules/oauth-clients/oauth-client.repository";
|
||||
import { RedisService } from "@/modules/redis/redis.service";
|
||||
import { TokensRepository } from "@/modules/tokens/tokens.repository";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
|
||||
import { AccessTokenGuard } from "@/modules/auth/guards/access-token/access-token.guard";
|
||||
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
|
||||
import { SlotsService } from "@/modules/slots/services/slots.service";
|
||||
import { Query, Body, Controller, Get, Delete, Post, Req, Res, UseGuards } from "@nestjs/common";
|
||||
import { ApiTags as DocsTags } from "@nestjs/swagger";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { TimeFormat, WeekDay } from "@/modules/users/inputs/create-managed-user.input";
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsNumber, IsOptional, IsString, IsTimeZone } from "class-validator";
|
||||
import { IsIn, IsNumber, IsOptional, IsString, IsTimeZone } from "class-validator";
|
||||
|
||||
export class UpdateManagedUserInput {
|
||||
@IsString()
|
||||
@@ -12,6 +12,7 @@ export class UpdateManagedUserInput {
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(["12", "24"])
|
||||
@ApiProperty({ example: 12, enum: [12, 24], description: "Must be 12 or 24" })
|
||||
timeFormat?: TimeFormat;
|
||||
|
||||
@@ -21,6 +22,7 @@ export class UpdateManagedUserInput {
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsIn(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
|
||||
@ApiProperty({
|
||||
example: "Monday",
|
||||
enum: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
|
||||
|
||||
Reference in new issue
Block a user