2021-04-11 17:12:18 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from 'next';
|
2021-03-26 15:51:19 +00:00
|
|
|
import { getSession } from 'next-auth/client';
|
|
|
|
import prisma from '../../../../lib/prisma';
|
|
|
|
const {google} = require('googleapis');
|
|
|
|
|
|
|
|
const credentials = process.env.GOOGLE_API_CREDENTIALS;
|
2021-06-03 00:05:54 +00:00
|
|
|
const scopes = ['https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/calendar.events'];
|
2021-03-26 15:51:19 +00:00
|
|
|
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
|
|
if (req.method === 'GET') {
|
|
|
|
// 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; }
|
|
|
|
|
2021-05-11 09:21:05 +00:00
|
|
|
// Get user
|
2021-03-26 15:51:19 +00:00
|
|
|
const user = await prisma.user.findFirst({
|
|
|
|
where: {
|
|
|
|
email: session.user.email,
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
id: true
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// Get token from Google Calendar API
|
|
|
|
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 authUrl = oAuth2Client.generateAuthUrl({
|
|
|
|
access_type: 'offline',
|
|
|
|
scope: scopes,
|
2021-04-21 22:10:48 +00:00
|
|
|
// A refresh token is only returned the first time the user
|
|
|
|
// consents to providing access. For illustration purposes,
|
|
|
|
// setting the prompt to 'consent' will force this consent
|
|
|
|
// every time, forcing a refresh_token to be returned.
|
|
|
|
prompt: 'consent',
|
2021-03-26 15:51:19 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
res.status(200).json({url: authUrl});
|
|
|
|
}
|
2021-04-21 22:10:48 +00:00
|
|
|
}
|