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

add webhooks for calendly events #111

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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,8 @@
/*
Warnings:

- Added the required column `externalUserId` to the `UserOauth` table without a default value. This is not possible if the table is not empty.

*/
-- AlterTable
ALTER TABLE "UserOauth" ADD COLUMN "externalUserId" TEXT;
19 changes: 10 additions & 9 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,16 @@ enum OauthProvider {
}

model UserOauth {
id String @id @default(uuid())
userAuthId String
UserAuth UserAuth @relation(fields: [userAuthId], references: [id])
provider OauthProvider
accessToken String
expiresAt DateTime
refreshToken String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @id @default(uuid())
userAuthId String
UserAuth UserAuth @relation(fields: [userAuthId], references: [id])
provider OauthProvider
accessToken String
expiresAt DateTime
refreshToken String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
externalUserId String

@@unique([userAuthId, provider])
}
Expand Down
59 changes: 59 additions & 0 deletions src/lib/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export class GCloud {
accessToken: json["access_token"] as string,
refreshToken: refreshToken || (json["refresh_token"] as string),
expiresAt: new Date(Date.now() + expiresInSeconds * 1000),
externalUserId: "test",
};
}

Expand Down Expand Up @@ -146,11 +147,13 @@ export class Calendly {
throw new Error("Calendly API error");
}
const expiresInSeconds = Number(json["expires_in"]);
const externalUserId = json["owner"].split("/").pop();
return {
provider: OauthProvider.CALENDLY,
accessToken: json["access_token"] as string,
refreshToken: json["refresh_token"] as string,
expiresAt: new Date(Date.now() + expiresInSeconds * 1000),
externalUserId: externalUserId,
};
}

Expand Down Expand Up @@ -268,6 +271,18 @@ async function findUserOauth(
});
}

async function findUserOauthByExternalId(
oauthExternalUserId: string,
provider: OauthProvider,
): Promise<UserOauth | null> {
return prisma.userOauth.findUnique({
where: {
externalUserId: oauthExternalUserId,
provider: provider,
},
});
}

export async function getAccessToken(
userAuthId: string,
provider: OauthProvider,
Expand Down Expand Up @@ -326,3 +341,47 @@ export async function disconnectOauth({
});
return res;
}

export async function oauthProcessCallback({
uri,
callback_url,
created_at,
updated_at,
retry_started_at,
state,
events,
scope,
organization,
user,
group,
creator,
}: {
uri: string,
callback_url: string,
created_at: string,
updated_at: string,
retry_started_at: string,
state: string,
events: string,
scope: string,
organization: string,
user: string,
group: string,
creator: string,
}): Promise<boolean> {
const oauthInfo = await findUserOauth(userAuthId, provider);
if (!oauthInfo) {
return false;
}
const intf = providerIntf(provider);
const res = await intf.revoke(oauthInfo);
await prisma.userOauth.delete({
where: {
userAuthId_provider: {
userAuthId,
provider,
},
},
});
return res;
}
35 changes: 35 additions & 0 deletions src/pages/api/oauth/callback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { NextApiRequest, NextApiResponse } from "next";
import { Value } from "@sinclair/typebox/value";
import { CalendlyWebhookSubscriptionRequestSchema, DisconnectOauthProviderRequestSchema } from "@/types/oauth.schema";
import { BadRequestError } from "@/types/errors";
import { disconnectOauth } from "@/lib/oauth";
import { provider } from "std-env";

async function OauthProviderCallbackHandler(
req: NextApiRequest,
res: NextApiResponse<{ success: boolean } | BadRequestError>,
): Promise<void> {
const { body } = req;
if (!Value.Check(CalendlyWebhookSubscriptionRequestSchema, body)) {
return res.status(400).json({ message: "Invalid inputs" });
}
const { uri, callback_url, created_at, updated_at, retry_started_at, state, events, scope, organization, user, group, creator} = body;

const status = await disconnectOauth({
userAuthId,
provider,
});

return res.status(200).json({ success: status });
}

export default async function handle(
req: NextApiRequest,
res: NextApiResponse<{ success: boolean } | BadRequestError>,
): Promise<void> {
if (req.method === "POST") {
await disconnectOauthProviderHandler(req, res);
} else {
return res.status(405).json({ message: "Method Not allowed" });
}
}
19 changes: 19 additions & 0 deletions src/types/oauth.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,22 @@ export const DisconnectOauthProviderRequestSchema = Type.Object({
// Password of user
provider: Type.Enum(OauthProvider),
});

export type CalendlyWebhookSubscriptionRequestSchema = Static<
typeof CalendlyWebhookSubscriptionRequestSchema
>;

export const CalendlyWebhookSubscriptionRequestSchema = Type.Object({
uri: Type.String(),
callback_url: Type.String(),
created_at: Type.String(),
updated_at: Type.String(),
retry_started_at: Type.String(),
state: Type.String(),
events: Type.Array(Type.String()),
scope: Type.String(),
organization: Type.String(),
user: Type.String(),
group: Type.String(),
creator: Type.String(),
});
Loading