2021-09-22 19:52:38 +00:00
|
|
|
import { google } from "googleapis";
|
2021-08-18 11:52:25 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2021-08-18 11:52:25 +00:00
|
|
|
import { getSession } from "@lib/auth";
|
2021-12-10 21:14:54 +00:00
|
|
|
import { BASE_URL } from "@lib/config/constants";
|
2021-10-12 09:35:44 +00:00
|
|
|
import prisma from "@lib/prisma";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2021-11-03 10:47:52 +00:00
|
|
|
import { decodeOAuthState } from "../utils";
|
|
|
|
|
2021-10-12 09:35:44 +00:00
|
|
|
const credentials = process.env.GOOGLE_API_CREDENTIALS;
|
2021-03-26 15:51:19 +00:00
|
|
|
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2021-08-19 12:27:01 +00:00
|
|
|
const { code } = req.query;
|
|
|
|
|
|
|
|
// Check that user is authenticated
|
|
|
|
const session = await getSession({ req: req });
|
|
|
|
|
2021-10-12 09:35:44 +00:00
|
|
|
if (!session?.user?.id) {
|
2021-08-19 12:27:01 +00:00
|
|
|
res.status(401).json({ message: "You must be logged in to do this" });
|
|
|
|
return;
|
|
|
|
}
|
2022-01-06 22:06:31 +00:00
|
|
|
if (code && typeof code !== "string") {
|
2021-08-19 12:27:01 +00:00
|
|
|
res.status(400).json({ message: "`code` must be a string" });
|
|
|
|
return;
|
|
|
|
}
|
2021-10-12 09:35:44 +00:00
|
|
|
if (!credentials) {
|
|
|
|
res.status(400).json({ message: "There are no Google Credentials installed." });
|
|
|
|
return;
|
|
|
|
}
|
2021-08-19 12:27:01 +00:00
|
|
|
|
2021-10-13 11:35:25 +00:00
|
|
|
const { client_secret, client_id } = JSON.parse(credentials).web;
|
2021-12-10 21:14:54 +00:00
|
|
|
const redirect_uri = BASE_URL + "/api/integrations/googlecalendar/callback";
|
2022-01-06 22:06:31 +00:00
|
|
|
|
2021-10-12 09:35:44 +00:00
|
|
|
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uri);
|
2021-11-03 10:47:52 +00:00
|
|
|
|
2022-01-06 22:06:31 +00:00
|
|
|
let key = "";
|
|
|
|
|
|
|
|
if (code) {
|
|
|
|
const token = await oAuth2Client.getToken(code);
|
|
|
|
|
|
|
|
key = token.res?.data;
|
|
|
|
}
|
|
|
|
|
2021-08-19 12:27:01 +00:00
|
|
|
await prisma.credential.create({
|
|
|
|
data: {
|
|
|
|
type: "google_calendar",
|
2021-08-19 14:37:18 +00:00
|
|
|
key,
|
2021-08-19 12:27:01 +00:00
|
|
|
userId: session.user.id,
|
|
|
|
},
|
|
|
|
});
|
2021-11-03 10:47:52 +00:00
|
|
|
const state = decodeOAuthState(req);
|
|
|
|
res.redirect(state?.returnTo ?? "/integrations");
|
2021-08-19 12:27:01 +00:00
|
|
|
}
|