|
| 1 | +import type { NextApiRequest, NextApiResponse } from "next"; |
| 2 | + |
| 3 | +import { createDefaultInstallation } from "@calcom/app-store/_utils/installation"; |
| 4 | +import { getServerSession } from "@calcom/features/auth/lib/getServerSession"; |
| 5 | +import { HttpError } from "@calcom/lib/http-error"; |
| 6 | + |
| 7 | +import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug"; |
| 8 | +import appConfig from "../config.json"; |
| 9 | + |
| 10 | +export default async function handler(req: NextApiRequest, res: NextApiResponse) { |
| 11 | + if (req.method !== "GET") return res.status(405).json({ message: "Method not allowed" }); |
| 12 | + const appKeys = await getAppKeysFromSlug(appConfig.slug); |
| 13 | + |
| 14 | + let client_id = ""; |
| 15 | + if (typeof appKeys.client_id === "string") client_id = appKeys.client_id; |
| 16 | + if (!client_id) return res.status(400).json({ message: "ZohoCRM client id missing." }); |
| 17 | + |
| 18 | + // Check that user is authenticated |
| 19 | + req.session = await getServerSession({ req, res }); |
| 20 | + const { teamId } = req.query; |
| 21 | + const user = req.session?.user; |
| 22 | + if (!user) { |
| 23 | + throw new HttpError({ statusCode: 401, message: "You must be logged in to do this" }); |
| 24 | + } |
| 25 | + const userId = user.id; |
| 26 | + await createDefaultInstallation({ |
| 27 | + appType: `${appConfig.slug}_other_calendar`, |
| 28 | + user, |
| 29 | + slug: appConfig.slug, |
| 30 | + key: {}, |
| 31 | + teamId: Number(teamId), |
| 32 | + }); |
| 33 | + const tenantId = teamId ? teamId : userId; |
| 34 | + // @TODO check scopes before deployment |
| 35 | + const scopes = [ |
| 36 | + "ZohoCRM.modules.ALL", |
| 37 | + "ZohoCRM.settings.ALL", |
| 38 | + "ZohoCRM.users.ALL", |
| 39 | + "AaaServer.profile.READ", |
| 40 | + ]; |
| 41 | + |
| 42 | + const queryParams = { |
| 43 | + scope: scopes.join(","), |
| 44 | + client_id, |
| 45 | + response_type: "code", |
| 46 | + access_type: "offline", |
| 47 | + redirect_uri: "http://localhost:3010/oauth-callback/zohocrm", |
| 48 | + state: `{%22tenantId%22:%22${tenantId}%22,%22revertPublicToken%22:%22${process.env.REVERT_PUBLIC_TOKEN}%22}`, |
| 49 | + }; |
| 50 | + |
| 51 | + const urlSearchParams = new URLSearchParams(queryParams); |
| 52 | + const queryString = urlSearchParams.toString(); |
| 53 | + |
| 54 | + res.status(200).json({ |
| 55 | + url: `https://accounts.zoho.com/oauth/v2/auth?${queryString}`, |
| 56 | + newTab: true, |
| 57 | + }); |
| 58 | +} |
0 commit comments