2021-04-11 17:12:18 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
|
|
import prisma from '../../../lib/prisma';
|
2021-03-22 13:48:48 +00:00
|
|
|
const {google} = require('googleapis');
|
|
|
|
|
|
|
|
const credentials = process.env.GOOGLE_API_CREDENTIALS;
|
|
|
|
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2021-04-11 17:12:18 +00:00
|
|
|
const { user } = req.query;
|
2021-03-22 13:48:48 +00:00
|
|
|
|
|
|
|
const currentUser = await prisma.user.findFirst({
|
|
|
|
where: {
|
|
|
|
username: user,
|
|
|
|
},
|
|
|
|
select: {
|
2021-04-16 02:09:22 +00:00
|
|
|
credentials: true,
|
|
|
|
timeZone: true,
|
2021-03-22 13:48:48 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2021-04-11 17:12:18 +00:00
|
|
|
authorise(bookEvent);
|
2021-03-22 13:48:48 +00:00
|
|
|
|
|
|
|
// Set up Google API credentials
|
|
|
|
function authorise(callback) {
|
|
|
|
const {client_secret, client_id, redirect_uris} = JSON.parse(credentials).web;
|
|
|
|
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
|
|
|
|
oAuth2Client.setCredentials(currentUser.credentials[0].key);
|
2021-04-11 17:12:18 +00:00
|
|
|
callback(oAuth2Client);
|
2021-03-22 13:48:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function bookEvent(auth) {
|
|
|
|
var event = {
|
|
|
|
'summary': 'Meeting with ' + req.body.name,
|
|
|
|
'description': req.body.notes,
|
|
|
|
'start': {
|
|
|
|
'dateTime': req.body.start,
|
2021-04-16 02:09:22 +00:00
|
|
|
'timeZone': currentUser.timeZone,
|
2021-03-22 13:48:48 +00:00
|
|
|
},
|
|
|
|
'end': {
|
|
|
|
'dateTime': req.body.end,
|
2021-04-16 02:09:22 +00:00
|
|
|
'timeZone': currentUser.timeZone,
|
2021-03-22 13:48:48 +00:00
|
|
|
},
|
|
|
|
'attendees': [
|
|
|
|
{'email': req.body.email},
|
|
|
|
],
|
|
|
|
'reminders': {
|
|
|
|
'useDefault': false,
|
|
|
|
'overrides': [
|
|
|
|
{'method': 'email', 'minutes': 60}
|
|
|
|
],
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
const calendar = google.calendar({version: 'v3', auth});
|
|
|
|
calendar.events.insert({
|
|
|
|
auth: auth,
|
|
|
|
calendarId: 'primary',
|
|
|
|
resource: event,
|
|
|
|
}, function(err, event) {
|
|
|
|
if (err) {
|
|
|
|
console.log('There was an error contacting the Calendar service: ' + err);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
res.status(200).json({message: 'Event created'});
|
|
|
|
});
|
|
|
|
}
|
2021-04-16 02:09:22 +00:00
|
|
|
}
|