feat: OAuth provider for Zapier (#11465)
Co-authored-by: Alex van Andel <[email protected]> Co-authored-by: sajanlamsal <[email protected]> Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: alannnc <[email protected]> Co-authored-by: Leo Giovanetti <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Hariom Balhara <[email protected]> Co-authored-by: Udit Takkar <[email protected]> Co-authored-by: Nitin Panghal <[email protected]> Co-authored-by: Omar López <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: zomars <[email protected]> Co-authored-by: Shivam Kalra <[email protected]> Co-authored-by: Richard Poelderl <[email protected]> Co-authored-by: Crowdin Bot <[email protected]> Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: Nafees Nazik <[email protected]> Co-authored-by: Chiranjeev Vishnoi <[email protected]> Co-authored-by: Denzil Samuel <[email protected]> Co-authored-by: Syed Ali Shahbaz <[email protected]> Co-authored-by: nitinpanghal <[email protected]> Co-authored-by: Ahmad <[email protected]> Co-authored-by: Annlee Fores <[email protected]> Co-authored-by: Keith Williams <[email protected]> Co-authored-by: Vijay <[email protected]>
This commit is contained in:
+15









Carina Wollendorfer
Alex van Andel
sajanlamsal
CarinaWolli
alannnc
Leo Giovanetti
Peer Richelsen
Hariom Balhara
Udit Takkar
Nitin Panghal
Omar López
Peer Richelsen
Shivam Kalra
Richard Poelderl
Crowdin Bot
Joe Au-Yeung
Nafees Nazik
Chiranjeev Vishnoi
Denzil Samuel
Syed Ali Shahbaz
nitinpanghal
Ahmad
Annlee Fores
Keith Williams
Vijay authored and
GitHub committed 2023-09-28 12:41:28 -07:00
1 parent
b4f44e9a60
commit
68bd877c5b
31 files changed
+1896
-196
No files matched your search
@@ -1,26 +1,16 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import findValidApiKey from "@calcom/features/ee/api-keys/lib/findValidApiKey";
|
||||
import { addSubscription } from "@calcom/features/webhooks/lib/scheduleTrigger";
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { validateAccountOrApiKey } from "../../lib/validateAccountOrApiKey";
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const apiKey = req.query.apiKey as string;
|
||||
|
||||
if (!apiKey) {
|
||||
return res.status(401).json({ message: "No API key provided" });
|
||||
}
|
||||
|
||||
const validKey = await findValidApiKey(apiKey, "zapier");
|
||||
|
||||
if (!validKey) {
|
||||
return res.status(401).json({ message: "API key not valid" });
|
||||
}
|
||||
|
||||
const { subscriberUrl, triggerEvent } = req.body;
|
||||
|
||||
const { account, appApiKey } = await validateAccountOrApiKey(req, ["READ_BOOKING", "READ_PROFILE"]);
|
||||
const createAppSubscription = await addSubscription({
|
||||
appApiKey: validKey,
|
||||
appApiKey,
|
||||
account,
|
||||
triggerEvent: triggerEvent,
|
||||
subscriberUrl: subscriberUrl,
|
||||
appId: "zapier",
|
||||
|
||||
@@ -1,30 +1,24 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import z from "zod";
|
||||
|
||||
import findValidApiKey from "@calcom/features/ee/api-keys/lib/findValidApiKey";
|
||||
import { deleteSubscription } from "@calcom/features/webhooks/lib/scheduleTrigger";
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { validateAccountOrApiKey } from "../../lib/validateAccountOrApiKey";
|
||||
|
||||
const querySchema = z.object({
|
||||
apiKey: z.string(),
|
||||
id: z.string(),
|
||||
});
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { apiKey, id } = querySchema.parse(req.query);
|
||||
const { id } = querySchema.parse(req.query);
|
||||
|
||||
if (!apiKey) {
|
||||
return res.status(401).json({ message: "No API key provided" });
|
||||
}
|
||||
|
||||
const validKey = await findValidApiKey(apiKey, "zapier");
|
||||
|
||||
if (!validKey) {
|
||||
return res.status(401).json({ message: "API key not valid" });
|
||||
}
|
||||
const { account, appApiKey } = await validateAccountOrApiKey(req, ["READ_BOOKING", "READ_PROFILE"]);
|
||||
|
||||
const deleteEventSubscription = await deleteSubscription({
|
||||
appApiKey: validKey,
|
||||
appApiKey,
|
||||
account,
|
||||
webhookId: id,
|
||||
appId: "zapier",
|
||||
});
|
||||
|
||||
@@ -1,29 +1,32 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import findValidApiKey from "@calcom/features/ee/api-keys/lib/findValidApiKey";
|
||||
import { listBookings } from "@calcom/features/webhooks/lib/scheduleTrigger";
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
|
||||
import { validateAccountOrApiKey } from "../../lib/validateAccountOrApiKey";
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const apiKey = req.query.apiKey as string;
|
||||
|
||||
if (!apiKey) {
|
||||
return res.status(401).json({ message: "No API key provided" });
|
||||
}
|
||||
|
||||
const validKey = await findValidApiKey(apiKey, "zapier");
|
||||
|
||||
if (!validKey) {
|
||||
return res.status(401).json({ message: "API key not valid" });
|
||||
}
|
||||
|
||||
const bookings = await listBookings(validKey);
|
||||
const { account: authorizedAccount, appApiKey: validKey } = await validateAccountOrApiKey(req, [
|
||||
"READ_BOOKING",
|
||||
]);
|
||||
const bookings = await listBookings(validKey, authorizedAccount);
|
||||
|
||||
if (!bookings) {
|
||||
return res.status(500).json({ message: "Unable to get bookings." });
|
||||
}
|
||||
if (bookings.length === 0) {
|
||||
const requested = validKey.teamId ? "teamId: " + validKey.teamId : "userId: " + validKey.userId;
|
||||
const userInfo = validKey
|
||||
? validKey.userId
|
||||
: authorizedAccount && !authorizedAccount.isTeam
|
||||
? authorizedAccount.name
|
||||
: null;
|
||||
const teamInfo = validKey
|
||||
? validKey.teamId
|
||||
: authorizedAccount && authorizedAccount.isTeam
|
||||
? authorizedAccount.name
|
||||
: null;
|
||||
|
||||
const requested = teamInfo ? "team: " + teamInfo : "user: " + userInfo;
|
||||
return res.status(404).json({
|
||||
message: `There are no bookings to retrieve, please create a booking first. Requested: \`${requested}\``,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import isAuthorized from "@calcom/features/auth/lib/oAuthAuthorization";
|
||||
import findValidApiKey from "@calcom/features/ee/api-keys/lib/findValidApiKey";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
|
||||
export async function validateAccountOrApiKey(req: NextApiRequest, requiredScopes: string[] = []) {
|
||||
const apiKey = req.query.apiKey as string;
|
||||
|
||||
if (!apiKey) {
|
||||
const authorizedAccount = await isAuthorized(req, requiredScopes);
|
||||
if (!authorizedAccount) throw new HttpError({ statusCode: 401, message: "Unauthorized" });
|
||||
return { account: authorizedAccount, appApiKey: undefined };
|
||||
}
|
||||
|
||||
const validKey = await findValidApiKey(apiKey, "zapier");
|
||||
if (!validKey) throw new HttpError({ statusCode: 401, message: "API key not valid" });
|
||||
return { account: null, appApiKey: validKey };
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expect } from "@playwright/test";
|
||||
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { test } from "@calcom/web/playwright/lib/fixtures";
|
||||
|
||||
import "../../src/types";
|
||||
|
||||
@@ -12,14 +12,14 @@ import { getCalApi } from "@calcom/embed-react";
|
||||
const api = getCalApi();
|
||||
|
||||
test("Check that the API is available", async () => {
|
||||
expect(api).toBeDefined()
|
||||
expect(api).toBeDefined();
|
||||
const awaitedApi = await api;
|
||||
awaitedApi('floatingButton', {
|
||||
calLink: 'free',
|
||||
awaitedApi("floatingButton", {
|
||||
calLink: "free",
|
||||
config: {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error We are intentionaly testing invalid value
|
||||
layout: 'wrongview'
|
||||
}
|
||||
})
|
||||
layout: "wrongview",
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import jwt from "jsonwebtoken";
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { OAuthTokenPayload } from "@calcom/web/pages/api/auth/oauth/token";
|
||||
|
||||
export default async function isAuthorized(req: NextApiRequest, requiredScopes: string[] = []) {
|
||||
const token = req.headers.authorization?.split(" ")[1] || "";
|
||||
let decodedToken: OAuthTokenPayload;
|
||||
try {
|
||||
decodedToken = jwt.verify(token, process.env.CALENDSO_ENCRYPTION_KEY || "") as OAuthTokenPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!decodedToken) return null;
|
||||
const hasAllRequiredScopes = requiredScopes.every((scope) => decodedToken.scope.includes(scope));
|
||||
|
||||
if (!hasAllRequiredScopes || decodedToken.token_type !== "Access Token") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (decodedToken.userId) {
|
||||
const user = await prisma.user.findFirst({
|
||||
where: {
|
||||
id: decodedToken.userId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) return null;
|
||||
|
||||
return { id: user.id, name: user.username, isTeam: false };
|
||||
}
|
||||
|
||||
if (decodedToken.teamId) {
|
||||
const team = await prisma.team.findFirst({
|
||||
where: {
|
||||
id: decodedToken.teamId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!team) return null;
|
||||
return { ...team, isTeam: true };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -117,6 +117,7 @@ const tabs: VerticalTabItemProps[] = [
|
||||
{ name: "apps", href: "/settings/admin/apps/calendar" },
|
||||
{ name: "users", href: "/settings/admin/users" },
|
||||
{ name: "organizations", href: "/settings/admin/organizations" },
|
||||
{ name: "oAuth", href: "/settings/admin/oAuth" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -16,18 +16,27 @@ export async function addSubscription({
|
||||
triggerEvent,
|
||||
subscriberUrl,
|
||||
appId,
|
||||
account,
|
||||
}: {
|
||||
appApiKey: ApiKey;
|
||||
appApiKey?: ApiKey;
|
||||
triggerEvent: WebhookTriggerEvents;
|
||||
subscriberUrl: string;
|
||||
appId: string;
|
||||
account?: {
|
||||
id: number;
|
||||
name: string | null;
|
||||
isTeam: boolean;
|
||||
} | null;
|
||||
}) {
|
||||
try {
|
||||
const userId = appApiKey ? appApiKey.userId : account && !account.isTeam ? account.id : null;
|
||||
const teamId = appApiKey ? appApiKey.teamId : account && account.isTeam ? account.id : null;
|
||||
|
||||
const createSubscription = await prisma.webhook.create({
|
||||
data: {
|
||||
id: v4(),
|
||||
userId: appApiKey.userId,
|
||||
teamId: appApiKey.teamId,
|
||||
userId,
|
||||
teamId,
|
||||
eventTriggers: [triggerEvent],
|
||||
subscriberUrl,
|
||||
active: true,
|
||||
@@ -38,8 +47,11 @@ export async function addSubscription({
|
||||
if (triggerEvent === WebhookTriggerEvents.MEETING_ENDED) {
|
||||
//schedule job for already existing bookings
|
||||
const where: Prisma.BookingWhereInput = {};
|
||||
if (appApiKey.teamId) where.eventType = { teamId: appApiKey.teamId };
|
||||
else where.userId = appApiKey.userId;
|
||||
if (teamId) {
|
||||
where.eventType = { teamId };
|
||||
} else {
|
||||
where.userId = userId;
|
||||
}
|
||||
const bookings = await prisma.booking.findMany({
|
||||
where: {
|
||||
...where,
|
||||
@@ -60,7 +72,10 @@ export async function addSubscription({
|
||||
|
||||
return createSubscription;
|
||||
} catch (error) {
|
||||
log.error(`Error creating subscription for user ${appApiKey.userId} and appId ${appApiKey.appId}.`);
|
||||
const userId = appApiKey ? appApiKey.userId : account && !account.isTeam ? account.id : null;
|
||||
const teamId = appApiKey ? appApiKey.teamId : account && account.isTeam ? account.id : null;
|
||||
|
||||
log.error(`Error creating subscription for ${teamId ? `team ${teamId}` : `user ${userId}`}.`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,10 +83,16 @@ export async function deleteSubscription({
|
||||
appApiKey,
|
||||
webhookId,
|
||||
appId,
|
||||
account,
|
||||
}: {
|
||||
appApiKey: ApiKey;
|
||||
appApiKey?: ApiKey;
|
||||
webhookId: string;
|
||||
appId: string;
|
||||
account?: {
|
||||
id: number;
|
||||
name: string | null;
|
||||
isTeam: boolean;
|
||||
} | null;
|
||||
}) {
|
||||
try {
|
||||
const webhook = await prisma.webhook.findFirst({
|
||||
@@ -82,8 +103,21 @@ export async function deleteSubscription({
|
||||
|
||||
if (webhook?.eventTriggers.includes(WebhookTriggerEvents.MEETING_ENDED)) {
|
||||
const where: Prisma.BookingWhereInput = {};
|
||||
if (appApiKey.teamId) where.eventType = { teamId: appApiKey.teamId };
|
||||
else where.userId = appApiKey.userId;
|
||||
|
||||
if (appApiKey) {
|
||||
if (appApiKey.teamId) {
|
||||
where.eventType = { teamId: appApiKey.teamId };
|
||||
} else {
|
||||
where.userId = appApiKey.userId;
|
||||
}
|
||||
} else if (account) {
|
||||
if (account.isTeam) {
|
||||
where.eventType = { teamId: account.id };
|
||||
} else {
|
||||
where.userId = account.id;
|
||||
}
|
||||
}
|
||||
|
||||
const bookingsWithScheduledJobs = await prisma.booking.findMany({
|
||||
where: {
|
||||
...where,
|
||||
@@ -117,22 +151,48 @@ export async function deleteSubscription({
|
||||
}
|
||||
return deleteWebhook;
|
||||
} catch (err) {
|
||||
const userId = appApiKey ? appApiKey.userId : account && !account.isTeam ? account.id : null;
|
||||
const teamId = appApiKey ? appApiKey.teamId : account && account.isTeam ? account.id : null;
|
||||
|
||||
log.error(
|
||||
`Error deleting subscription for user ${appApiKey.userId}, webhookId ${webhookId}, appId ${appId}`
|
||||
`Error deleting subscription for user ${
|
||||
teamId ? `team ${teamId}` : `userId ${userId}`
|
||||
}, webhookId ${webhookId}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function listBookings(appApiKey: ApiKey) {
|
||||
export async function listBookings(
|
||||
appApiKey?: ApiKey,
|
||||
account?: {
|
||||
id: number;
|
||||
name: string | null;
|
||||
isTeam: boolean;
|
||||
} | null
|
||||
) {
|
||||
try {
|
||||
const where: Prisma.BookingWhereInput = {};
|
||||
if (appApiKey.teamId) {
|
||||
where.eventType = {
|
||||
OR: [{ teamId: appApiKey.teamId }, { parent: { teamId: appApiKey.teamId } }],
|
||||
};
|
||||
} else {
|
||||
where.userId = appApiKey.userId;
|
||||
if (appApiKey) {
|
||||
if (appApiKey.teamId) {
|
||||
where.eventType = {
|
||||
OR: [{ teamId: appApiKey.teamId }, { parent: { teamId: appApiKey.teamId } }],
|
||||
};
|
||||
} else {
|
||||
where.userId = appApiKey.userId;
|
||||
}
|
||||
} else if (account) {
|
||||
if (!account.isTeam) {
|
||||
where.userId = account.id;
|
||||
where.eventType = {
|
||||
teamId: null,
|
||||
};
|
||||
} else {
|
||||
where.eventType = {
|
||||
teamId: account.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const bookings = await prisma.booking.findMany({
|
||||
take: 3,
|
||||
where: where,
|
||||
@@ -197,7 +257,10 @@ export async function listBookings(appApiKey: ApiKey) {
|
||||
|
||||
return updatedBookings;
|
||||
} catch (err) {
|
||||
log.error(`Error retrieving list of bookings for user ${appApiKey.userId} and appId ${appApiKey.appId}.`);
|
||||
const userId = appApiKey ? appApiKey.userId : account && !account.isTeam ? account.id : null;
|
||||
const teamId = appApiKey ? appApiKey.teamId : account && account.isTeam ? account.id : null;
|
||||
|
||||
log.error(`Error retrieving list of bookings for ${teamId ? `team ${teamId}` : `user ${userId}`}.`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AccessScope" AS ENUM ('READ_BOOKING', 'READ_PROFILE');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "OAuthClient" (
|
||||
"clientId" TEXT NOT NULL,
|
||||
"redirectUri" TEXT NOT NULL,
|
||||
"clientSecret" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"logo" TEXT,
|
||||
|
||||
CONSTRAINT "OAuthClient_pkey" PRIMARY KEY ("clientId")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AccessCode" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"clientId" TEXT,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"scopes" "AccessScope"[],
|
||||
"userId" INTEGER,
|
||||
"teamId" INTEGER,
|
||||
|
||||
CONSTRAINT "AccessCode_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "OAuthClient_clientId_key" ON "OAuthClient"("clientId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AccessCode" ADD CONSTRAINT "AccessCode_clientId_fkey" FOREIGN KEY ("clientId") REFERENCES "OAuthClient"("clientId") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AccessCode" ADD CONSTRAINT "AccessCode_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AccessCode" ADD CONSTRAINT "AccessCode_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -244,6 +244,7 @@ model User {
|
||||
hosts Host[]
|
||||
organizationId Int?
|
||||
organization Team? @relation("scope", fields: [organizationId], references: [id], onDelete: SetNull)
|
||||
accessCodes AccessCode[]
|
||||
// Linking account code for orgs v2
|
||||
//linkedByUserId Int?
|
||||
//linkedBy User? @relation("linked_account", fields: [linkedByUserId], references: [id], onDelete: Cascade)
|
||||
@@ -293,6 +294,7 @@ model Team {
|
||||
routingForms App_RoutingForms_Form[]
|
||||
apiKeys ApiKey[]
|
||||
credentials Credential[]
|
||||
accessCodes AccessCode[]
|
||||
|
||||
@@unique([slug, parentId])
|
||||
}
|
||||
@@ -908,6 +910,33 @@ model SelectedSlots {
|
||||
@@unique(fields: [userId, slotUtcStartDate, slotUtcEndDate, uid], name: "selectedSlotUnique")
|
||||
}
|
||||
|
||||
model OAuthClient {
|
||||
clientId String @id @unique
|
||||
redirectUri String
|
||||
clientSecret String
|
||||
name String
|
||||
logo String?
|
||||
accessCodes AccessCode[]
|
||||
}
|
||||
|
||||
model AccessCode {
|
||||
id Int @id @default(autoincrement())
|
||||
code String
|
||||
clientId String?
|
||||
client OAuthClient? @relation(fields: [clientId], references: [clientId], onDelete: Cascade)
|
||||
expiresAt DateTime
|
||||
scopes AccessScope[]
|
||||
userId Int?
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
teamId Int?
|
||||
team Team? @relation(fields: [teamId], references: [id], onDelete: Cascade)
|
||||
}
|
||||
|
||||
enum AccessScope {
|
||||
READ_BOOKING
|
||||
READ_PROFILE
|
||||
}
|
||||
|
||||
view BookingTimeStatus {
|
||||
id Int @unique
|
||||
uid String?
|
||||
|
||||
@@ -41,6 +41,7 @@ const ENDPOINTS = [
|
||||
"workflows",
|
||||
"appsRouter",
|
||||
"googleWorkspace",
|
||||
"oAuth",
|
||||
] as const;
|
||||
export type Endpoint = (typeof ENDPOINTS)[number];
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import { bookingsRouter } from "./bookings/_router";
|
||||
import { deploymentSetupRouter } from "./deploymentSetup/_router";
|
||||
import { eventTypesRouter } from "./eventTypes/_router";
|
||||
import { googleWorkspaceRouter } from "./googleWorkspace/_router";
|
||||
import { oAuthRouter } from "./oAuth/_router";
|
||||
import { viewerOrganizationsRouter } from "./organizations/_router";
|
||||
import { paymentsRouter } from "./payments/_router";
|
||||
import { slotsRouter } from "./slots/_router";
|
||||
@@ -50,6 +51,7 @@ export const viewerRouter = mergeRouters(
|
||||
features: featureFlagRouter,
|
||||
appsRouter,
|
||||
users: userAdminRouter,
|
||||
oAuth: oAuthRouter,
|
||||
googleWorkspace: googleWorkspaceRouter,
|
||||
admin: adminRouter,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import authedProcedure, { authedAdminProcedure } from "@calcom/trpc/server/procedures/authedProcedure";
|
||||
|
||||
import { router } from "../../../trpc";
|
||||
import { ZAddClientInputSchema } from "./addClient.schema";
|
||||
import { ZGenerateAuthCodeInputSchema } from "./generateAuthCode.schema";
|
||||
import { ZGetClientInputSchema } from "./getClient.schema";
|
||||
|
||||
type OAuthRouterHandlerCache = {
|
||||
getClient?: typeof import("./getClient.handler").getClientHandler;
|
||||
addClient?: typeof import("./addClient.handler").addClientHandler;
|
||||
generateAuthCode?: typeof import("./generateAuthCode.handler").generateAuthCodeHandler;
|
||||
};
|
||||
|
||||
const UNSTABLE_HANDLER_CACHE: OAuthRouterHandlerCache = {};
|
||||
|
||||
export const oAuthRouter = router({
|
||||
getClient: authedProcedure.input(ZGetClientInputSchema).query(async ({ ctx, input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.getClient) {
|
||||
UNSTABLE_HANDLER_CACHE.getClient = await import("./getClient.handler").then(
|
||||
(mod) => mod.getClientHandler
|
||||
);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.getClient) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.getClient({
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
addClient: authedAdminProcedure.input(ZAddClientInputSchema).mutation(async ({ input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.addClient) {
|
||||
UNSTABLE_HANDLER_CACHE.addClient = await import("./addClient.handler").then(
|
||||
(mod) => mod.addClientHandler
|
||||
);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.addClient) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.addClient({
|
||||
input,
|
||||
});
|
||||
}),
|
||||
|
||||
generateAuthCode: authedProcedure.input(ZGenerateAuthCodeInputSchema).mutation(async ({ ctx, input }) => {
|
||||
if (!UNSTABLE_HANDLER_CACHE.generateAuthCode) {
|
||||
UNSTABLE_HANDLER_CACHE.generateAuthCode = await import("./generateAuthCode.handler").then(
|
||||
(mod) => mod.generateAuthCodeHandler
|
||||
);
|
||||
}
|
||||
|
||||
// Unreachable code but required for type safety
|
||||
if (!UNSTABLE_HANDLER_CACHE.generateAuthCode) {
|
||||
throw new Error("Failed to load handler");
|
||||
}
|
||||
|
||||
return UNSTABLE_HANDLER_CACHE.generateAuthCode({
|
||||
ctx,
|
||||
input,
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { randomBytes, createHash } from "crypto";
|
||||
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
import type { TAddClientInputSchema } from "./addClient.schema";
|
||||
|
||||
type AddClientOptions = {
|
||||
input: TAddClientInputSchema;
|
||||
};
|
||||
|
||||
export const addClientHandler = async ({ input }: AddClientOptions) => {
|
||||
const { name, redirectUri, logo } = input;
|
||||
|
||||
const [hashedSecret, secret] = generateSecret();
|
||||
const clientId = randomBytes(32).toString("hex");
|
||||
|
||||
const client = await prisma.oAuthClient.create({
|
||||
data: {
|
||||
name,
|
||||
redirectUri,
|
||||
clientId,
|
||||
clientSecret: hashedSecret,
|
||||
logo,
|
||||
},
|
||||
});
|
||||
|
||||
const clientWithSecret = {
|
||||
...client,
|
||||
clientSecret: secret,
|
||||
};
|
||||
|
||||
return clientWithSecret;
|
||||
};
|
||||
|
||||
const hashSecretKey = (apiKey: string): string => createHash("sha256").update(apiKey).digest("hex");
|
||||
|
||||
// Generate a random secret
|
||||
export const generateSecret = (secret = randomBytes(32).toString("hex")) => [hashSecretKey(secret), secret];
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZAddClientInputSchema = z.object({
|
||||
name: z.string(),
|
||||
redirectUri: z.string(),
|
||||
logo: z.string(),
|
||||
});
|
||||
|
||||
export type TAddClientInputSchema = z.infer<typeof ZAddClientInputSchema>;
|
||||
@@ -0,0 +1,78 @@
|
||||
import { randomBytes } from "crypto";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { AccessScope } from "@calcom/prisma/enums";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TGenerateAuthCodeInputSchema } from "./generateAuthCode.schema";
|
||||
|
||||
type AddClientOptions = {
|
||||
ctx: {
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
};
|
||||
input: TGenerateAuthCodeInputSchema;
|
||||
};
|
||||
|
||||
export const generateAuthCodeHandler = async ({ ctx, input }: AddClientOptions) => {
|
||||
const { clientId, scopes, teamSlug } = input;
|
||||
const client = await prisma.oAuthClient.findFirst({
|
||||
where: {
|
||||
clientId,
|
||||
},
|
||||
select: {
|
||||
clientId: true,
|
||||
redirectUri: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!client) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "Client ID not valid" });
|
||||
}
|
||||
const authorizationCode = generateAuthorizationCode();
|
||||
|
||||
const team = teamSlug
|
||||
? await prisma.team.findFirst({
|
||||
where: {
|
||||
slug: teamSlug,
|
||||
members: {
|
||||
some: {
|
||||
userId: ctx.user.id,
|
||||
role: {
|
||||
in: ["OWNER", "ADMIN"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
: undefined;
|
||||
|
||||
if (teamSlug && !team) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
await prisma.accessCode.create({
|
||||
data: {
|
||||
code: authorizationCode,
|
||||
clientId,
|
||||
userId: !teamSlug ? ctx.user.id : undefined,
|
||||
teamId: team ? team.id : undefined,
|
||||
expiresAt: dayjs().add(10, "minutes").toDate(),
|
||||
scopes: scopes as [AccessScope],
|
||||
},
|
||||
});
|
||||
return { client, authorizationCode };
|
||||
};
|
||||
|
||||
function generateAuthorizationCode() {
|
||||
const randomBytesValue = randomBytes(40);
|
||||
const authorizationCode = randomBytesValue
|
||||
.toString("base64")
|
||||
.replace(/=/g, "")
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_");
|
||||
return authorizationCode;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZGenerateAuthCodeInputSchema = z.object({
|
||||
clientId: z.string(),
|
||||
scopes: z.array(z.string()),
|
||||
teamSlug: z.string().optional(),
|
||||
});
|
||||
|
||||
export type TGenerateAuthCodeInputSchema = z.infer<typeof ZGenerateAuthCodeInputSchema>;
|
||||
@@ -0,0 +1,24 @@
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
import type { TGetClientInputSchema } from "./getClient.schema";
|
||||
|
||||
type GetClientOptions = {
|
||||
input: TGetClientInputSchema;
|
||||
};
|
||||
|
||||
export const getClientHandler = async ({ input }: GetClientOptions) => {
|
||||
const { clientId } = input;
|
||||
|
||||
const client = await prisma.oAuthClient.findFirst({
|
||||
where: {
|
||||
clientId,
|
||||
},
|
||||
select: {
|
||||
clientId: true,
|
||||
redirectUri: true,
|
||||
name: true,
|
||||
logo: true,
|
||||
},
|
||||
});
|
||||
return client;
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZGetClientInputSchema = z.object({
|
||||
clientId: z.string(),
|
||||
});
|
||||
|
||||
export type TGetClientInputSchema = z.infer<typeof ZGetClientInputSchema>;
|
||||
Reference in new issue
Block a user