first commit
This commit is contained in:
15
calcom/example-apps/credential-sync/.env.example
Normal file
15
calcom/example-apps/credential-sync/.env.example
Normal file
@@ -0,0 +1,15 @@
|
||||
CALCOM_TEST_USER_ID=1
|
||||
|
||||
GOOGLE_REFRESH_TOKEN=
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
|
||||
ZOOM_REFRESH_TOKEN=
|
||||
ZOOM_CLIENT_ID=
|
||||
ZOOM_CLIENT_SECRET=
|
||||
CALCOM_ADMIN_API_KEY=
|
||||
|
||||
# Refer to Cal.com env variables as these are set in their env
|
||||
CALCOM_CREDENTIAL_SYNC_SECRET="";
|
||||
CALCOM_CREDENTIAL_SYNC_HEADER_NAME="calcom-credential-sync-secret";
|
||||
CALCOM_APP_CREDENTIAL_ENCRYPTION_KEY="";
|
||||
9
calcom/example-apps/credential-sync/README.md
Normal file
9
calcom/example-apps/credential-sync/README.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# README
|
||||
|
||||
This is an example app that acts as the source of truth for Cal.com Apps credentials. This app is capable of generating the access_token itself and then sync those to Cal.com app.
|
||||
|
||||
## How to start
|
||||
`yarn dev` starts the server on port 5100. After this open http://localhost:5100 and from there you would be able to manage the tokens for various Apps.
|
||||
|
||||
## Endpoints
|
||||
http://localhost:5100/api/getToken should be set as the value of env variable CALCOM_CREDENTIAL_SYNC_ENDPOINT in Cal.com
|
||||
13
calcom/example-apps/credential-sync/constants.ts
Normal file
13
calcom/example-apps/credential-sync/constants.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
// How to get it? -> Establish a connection with Google(e.g. through cal.com app) and then copy the refresh_token from there.
|
||||
export const GOOGLE_REFRESH_TOKEN = process.env.GOOGLE_REFRESH_TOKEN;
|
||||
export const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
|
||||
export const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
|
||||
|
||||
export const ZOOM_REFRESH_TOKEN = process.env.ZOOM_REFRESH_TOKEN;
|
||||
export const ZOOM_CLIENT_ID = process.env.ZOOM_CLIENT_ID;
|
||||
export const ZOOM_CLIENT_SECRET = process.env.ZOOM_CLIENT_SECRET;
|
||||
export const CALCOM_ADMIN_API_KEY = process.env.CALCOM_ADMIN_API_KEY;
|
||||
|
||||
export const CALCOM_CREDENTIAL_SYNC_SECRET = process.env.CALCOM_CREDENTIAL_SYNC_SECRET;
|
||||
export const CALCOM_CREDENTIAL_SYNC_HEADER_NAME = process.env.CALCOM_CREDENTIAL_SYNC_HEADER_NAME;
|
||||
export const CALCOM_APP_CREDENTIAL_ENCRYPTION_KEY = process.env.CALCOM_APP_CREDENTIAL_ENCRYPTION_KEY;
|
||||
89
calcom/example-apps/credential-sync/lib/integrations.ts
Normal file
89
calcom/example-apps/credential-sync/lib/integrations.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import {
|
||||
GOOGLE_CLIENT_ID,
|
||||
GOOGLE_CLIENT_SECRET,
|
||||
GOOGLE_REFRESH_TOKEN,
|
||||
ZOOM_CLIENT_ID,
|
||||
ZOOM_CLIENT_SECRET,
|
||||
ZOOM_REFRESH_TOKEN,
|
||||
} from "../constants";
|
||||
|
||||
export async function generateGoogleCalendarAccessToken() {
|
||||
const keys = {
|
||||
client_id: GOOGLE_CLIENT_ID,
|
||||
client_secret: GOOGLE_CLIENT_SECRET,
|
||||
redirect_uris: [
|
||||
"http://localhost:3000/api/integrations/googlecalendar/callback",
|
||||
"http://localhost:3000/api/auth/callback/google",
|
||||
],
|
||||
};
|
||||
const clientId = keys.client_id;
|
||||
const clientSecret = keys.client_secret;
|
||||
const refresh_token = GOOGLE_REFRESH_TOKEN;
|
||||
|
||||
const url = "https://oauth2.googleapis.com/token";
|
||||
const data = {
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
refresh_token: refresh_token,
|
||||
grant_type: "refresh_token",
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: new URLSearchParams(data),
|
||||
});
|
||||
|
||||
const json = await response.json();
|
||||
if (json.access_token) {
|
||||
console.log("Access Token:", json.access_token);
|
||||
return json.access_token;
|
||||
} else {
|
||||
console.error("Failed to retrieve access token:", json);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching access token:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateZoomAccessToken() {
|
||||
const client_id = ZOOM_CLIENT_ID; // Replace with your client ID
|
||||
const client_secret = ZOOM_CLIENT_SECRET; // Replace with your client secret
|
||||
const refresh_token = ZOOM_REFRESH_TOKEN; // Replace with your refresh token
|
||||
|
||||
const url = "https://zoom.us/oauth/token";
|
||||
const auth = Buffer.from(`${client_id}:${client_secret}`).toString("base64");
|
||||
|
||||
const params = new URLSearchParams();
|
||||
params.append("grant_type", "refresh_token");
|
||||
params.append("refresh_token", refresh_token);
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Basic ${auth}`,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: params,
|
||||
});
|
||||
|
||||
const json = await response.json();
|
||||
if (json.access_token) {
|
||||
console.log("New Access Token:", json.access_token);
|
||||
console.log("New Refresh Token:", json.refresh_token); // Save this refresh token securely
|
||||
return json.access_token; // You might also want to return the new refresh token if applicable
|
||||
} else {
|
||||
console.error("Failed to refresh access token:", json);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error refreshing access token:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
5
calcom/example-apps/credential-sync/next-env.d.ts
vendored
Normal file
5
calcom/example-apps/credential-sync/next-env.d.ts
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/basic-features/typescript for more information.
|
||||
9
calcom/example-apps/credential-sync/next.config.js
Normal file
9
calcom/example-apps/credential-sync/next.config.js
Normal file
@@ -0,0 +1,9 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
require("dotenv").config({ path: "../../.env" });
|
||||
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
transpilePackages: ["@calcom/lib"],
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
31
calcom/example-apps/credential-sync/package.json
Normal file
31
calcom/example-apps/credential-sync/package.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@calcom/example-app-credential-sync",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "PORT=5100 next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@calcom/atoms": "*",
|
||||
"@prisma/client": "5.4.2",
|
||||
"next": "14.0.4",
|
||||
"prisma": "^5.7.1",
|
||||
"react": "^18",
|
||||
"react-dom": "^18"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.3.1",
|
||||
"@types/react": "^18",
|
||||
"@types/react-dom": "^18",
|
||||
"autoprefixer": "^10.0.1",
|
||||
"dotenv": "^16.3.1",
|
||||
"eslint": "^8",
|
||||
"eslint-config-next": "14.0.4",
|
||||
"postcss": "^8",
|
||||
"tailwindcss": "^3.3.0",
|
||||
"typescript": "^4.9.4"
|
||||
}
|
||||
}
|
||||
41
calcom/example-apps/credential-sync/pages/api/getToken.ts
Normal file
41
calcom/example-apps/credential-sync/pages/api/getToken.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
import { CALCOM_CREDENTIAL_SYNC_HEADER_NAME, CALCOM_CREDENTIAL_SYNC_SECRET } from "../../constants";
|
||||
import { generateGoogleCalendarAccessToken, generateZoomAccessToken } from "../../lib/integrations";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const secret = req.headers[CALCOM_CREDENTIAL_SYNC_HEADER_NAME];
|
||||
console.log("getToken hit");
|
||||
try {
|
||||
if (!secret) {
|
||||
return res.status(403).json({ message: "secret header not set" });
|
||||
}
|
||||
if (secret !== CALCOM_CREDENTIAL_SYNC_SECRET) {
|
||||
return res.status(403).json({ message: "Invalid secret" });
|
||||
}
|
||||
|
||||
const calcomUserId = req.body.calcomUserId;
|
||||
const appSlug = req.body.appSlug;
|
||||
console.log("getToken Params", {
|
||||
calcomUserId,
|
||||
appSlug,
|
||||
});
|
||||
let accessToken;
|
||||
if (appSlug === "google-calendar") {
|
||||
accessToken = await generateGoogleCalendarAccessToken();
|
||||
} else if (appSlug === "zoom") {
|
||||
accessToken = await generateZoomAccessToken();
|
||||
} else {
|
||||
throw new Error("Unhandled values");
|
||||
}
|
||||
if (!accessToken) {
|
||||
throw new Error("Unable to generate token");
|
||||
}
|
||||
res.status(200).json({
|
||||
_1: true,
|
||||
access_token: accessToken,
|
||||
});
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: e.message });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { symmetricEncrypt } from "@calcom/lib/crypto";
|
||||
|
||||
import {
|
||||
CALCOM_APP_CREDENTIAL_ENCRYPTION_KEY,
|
||||
CALCOM_CREDENTIAL_SYNC_SECRET,
|
||||
CALCOM_CREDENTIAL_SYNC_HEADER_NAME,
|
||||
CALCOM_ADMIN_API_KEY,
|
||||
} from "../../constants";
|
||||
import { generateGoogleCalendarAccessToken, generateZoomAccessToken } from "../../lib/integrations";
|
||||
|
||||
export default async function handler(req: NextApiRequest, res) {
|
||||
const isInvalid = req.query["invalid"] === "1";
|
||||
const userId = parseInt(req.query["userId"] as string);
|
||||
const appSlug = req.query["appSlug"];
|
||||
|
||||
try {
|
||||
let accessToken;
|
||||
if (appSlug === "google-calendar") {
|
||||
accessToken = await generateGoogleCalendarAccessToken();
|
||||
} else if (appSlug === "zoom") {
|
||||
accessToken = await generateZoomAccessToken();
|
||||
} else {
|
||||
throw new Error(`Unhandled appSlug: ${appSlug}`);
|
||||
}
|
||||
|
||||
if (!accessToken) {
|
||||
return res.status(500).json({ error: "Could not get access token" });
|
||||
}
|
||||
|
||||
const result = await fetch(
|
||||
`http://localhost:3002/api/v1/credential-sync?apiKey=${CALCOM_ADMIN_API_KEY}&userId=${userId}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
[CALCOM_CREDENTIAL_SYNC_HEADER_NAME]: CALCOM_CREDENTIAL_SYNC_SECRET,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
appSlug,
|
||||
encryptedKey: symmetricEncrypt(
|
||||
JSON.stringify({
|
||||
access_token: isInvalid ? "1233231231231" : accessToken,
|
||||
}),
|
||||
CALCOM_APP_CREDENTIAL_ENCRYPTION_KEY
|
||||
),
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
const clonedResult = result.clone();
|
||||
try {
|
||||
if (result.ok) {
|
||||
const json = await result.json();
|
||||
return res.status(200).json(json);
|
||||
} else {
|
||||
return res.status(400).json({ error: await clonedResult.text() });
|
||||
}
|
||||
} catch (e) {
|
||||
return res.status(400).json({ error: await clonedResult.text() });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return res.status(400).json({ message: "Internal Server Error", error: error.message });
|
||||
}
|
||||
}
|
||||
57
calcom/example-apps/credential-sync/pages/index.tsx
Normal file
57
calcom/example-apps/credential-sync/pages/index.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function Index() {
|
||||
const [data, setData] = useState("");
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const pathname = usePathname();
|
||||
const appSlug = searchParams.get("appSlug");
|
||||
const userId = searchParams.get("userId");
|
||||
|
||||
useEffect(() => {
|
||||
let isRedirectNeeded = false;
|
||||
const newSearchParams = new URLSearchParams(new URL(document.URL).searchParams);
|
||||
if (!userId) {
|
||||
newSearchParams.set("userId", "1");
|
||||
isRedirectNeeded = true;
|
||||
}
|
||||
|
||||
if (!appSlug) {
|
||||
newSearchParams.set("appSlug", "google-calendar");
|
||||
isRedirectNeeded = true;
|
||||
}
|
||||
|
||||
if (isRedirectNeeded) {
|
||||
router.push(`${pathname}?${newSearchParams.toString()}`);
|
||||
}
|
||||
}, [router, pathname, userId, appSlug]);
|
||||
|
||||
async function updateToken({ invalid } = { invalid: false }) {
|
||||
const res = await fetch(
|
||||
`/api/setTokenInCalCom?invalid=${invalid ? 1 : 0}&userId=${userId}&appSlug=${appSlug}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const data = await res.json();
|
||||
setData(JSON.stringify(data));
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>Welcome to Credential Sync Playground</h1>
|
||||
<p>
|
||||
You are managing credentials for cal.com <strong>userId={userId}</strong> for{" "}
|
||||
<strong>appSlug={appSlug}</strong>. Update query params to manage a different user or app{" "}
|
||||
</p>
|
||||
<button onClick={() => updateToken({ invalid: true })}>Give an invalid token to Cal.com</button>
|
||||
<button onClick={() => updateToken()}>Give a valid token to Cal.com</button>
|
||||
<div>{data}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
19
calcom/example-apps/credential-sync/tsconfig.json
Normal file
19
calcom/example-apps/credential-sync/tsconfig.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": false,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noEmit": true,
|
||||
"incremental": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve"
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user