|
| 1 | +import jsforce from "jsforce"; |
| 2 | +import type { NextApiRequest, NextApiResponse } from "next"; |
| 3 | + |
| 4 | +import { WEBAPP_URL } from "@calcom/lib/constants"; |
| 5 | +import { getSafeRedirectUrl } from "@calcom/lib/getSafeRedirectUrl"; |
| 6 | +import prisma from "@calcom/prisma"; |
| 7 | + |
| 8 | +import { decodeOAuthState } from "../../_utils/decodeOAuthState"; |
| 9 | +import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug"; |
| 10 | +import getInstalledAppPath from "../../_utils/getInstalledAppPath"; |
| 11 | + |
| 12 | +let consumer_key = ""; |
| 13 | +let consumer_secret = ""; |
| 14 | +const instance_url = ""; |
| 15 | + |
| 16 | +export default async function handler(req: NextApiRequest, res: NextApiResponse) { |
| 17 | + const { code } = req.query; |
| 18 | + |
| 19 | + if (code === undefined && typeof code !== "string") { |
| 20 | + res.status(400).json({ message: "`code` must be a string" }); |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + if (!req.session?.user?.id) { |
| 25 | + return res.status(401).json({ message: "You must be logged in to do this" }); |
| 26 | + } |
| 27 | + |
| 28 | + const appKeys = await getAppKeysFromSlug("salesforce"); |
| 29 | + if (typeof appKeys.consumer_key === "string") consumer_key = appKeys.consumer_key; |
| 30 | + if (typeof appKeys.consumer_secret === "string") consumer_secret = appKeys.consumer_secret; |
| 31 | + if (!consumer_key) return res.status(400).json({ message: "Salesforce consumer key missing." }); |
| 32 | + if (!consumer_secret) return res.status(400).json({ message: "Salesforce consumer secret missing." }); |
| 33 | + |
| 34 | + const conn = new jsforce.Connection({ |
| 35 | + clientId: consumer_key, |
| 36 | + clientSecret: consumer_secret, |
| 37 | + redirectUri: WEBAPP_URL + "/api/integrations/salesforce/callback", |
| 38 | + }); |
| 39 | + |
| 40 | + const salesforceTokenInfo = await conn.oauth2.requestToken(code as string); |
| 41 | + |
| 42 | + await prisma.credential.create({ |
| 43 | + data: { |
| 44 | + type: "salesforce_other_calendar", |
| 45 | + key: salesforceTokenInfo as any, |
| 46 | + userId: req.session.user.id, |
| 47 | + appId: "salesforce", |
| 48 | + }, |
| 49 | + }); |
| 50 | + |
| 51 | + const state = decodeOAuthState(req); |
| 52 | + res.redirect( |
| 53 | + getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: "other", slug: "salesforce" }) |
| 54 | + ); |
| 55 | +} |
0 commit comments