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-09-22 19:52:38 +00:00
|
|
|
|
2021-08-18 11:52:25 +00:00
|
|
|
import prisma from "../../../../lib/prisma";
|
2021-03-26 15:51:19 +00:00
|
|
|
|
2021-08-19 12:27:01 +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 });
|
|
|
|
|
|
|
|
if (!session) {
|
|
|
|
res.status(401).json({ message: "You must be logged in to do this" });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (typeof code !== "string") {
|
|
|
|
res.status(400).json({ message: "`code` must be a string" });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const { client_secret, client_id, redirect_uris } = JSON.parse(credentials).web;
|
|
|
|
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
|
|
|
|
const token = await oAuth2Client.getToken(code);
|
2021-08-19 14:37:18 +00:00
|
|
|
const 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,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
res.redirect("/integrations");
|
|
|
|
}
|