Skip to content

Commit

Permalink
updating invite crud
Browse files Browse the repository at this point in the history
  • Loading branch information
Preshy-Jones committed Dec 3, 2022
1 parent bee93d0 commit 14ec228
Show file tree
Hide file tree
Showing 8 changed files with 210 additions and 66 deletions.
14 changes: 14 additions & 0 deletions env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
PORT=8000
MONGODB_URI=mongodb+srv://PreshyJones:confidence@myfirstcluster-2ekpt.mongodb.net/dinner?retryWrites=true&w=majority
JWT_EXPIRES_IN="90d"
JWT_SECRET= "ejgesgfyjehfvsyukaffrg"
REFRESH_TOKEN_SECRET="ejgesgfyjehfvsyukaffrg"
NODE_ENV=development
SENDGRID_API_KEY=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
GOOGLE_CLIENT_ID="942349562307-ldd3b7317ih6nskr99gn81r73jitm927.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET="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"
SERVER_ROOT_URI='http://localhost:8000/api/v1/auth/google/token'
UI_ROOT_URI='http://localhost:3000'
COOKIE_NAME='auth_token'
INVITATION_TOKEN_SECRET="boomshakalaka"
CREDENTIALS='{"type": "service_account","project_id": "confident-facet-364012","private_key_id": "1f817510d3efade14b09de482b156c00bccf6e21","private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCr2/kpAYU2YUuR\nexWuEI+z83T+DbNfeRJxo4MS/7ko17Xav16REGYd3SoHqnWy6lUQ02Enml4wp4eC\nmnaHicsLoqwYE6NCVbBMwFvXsv6JK3vwiuL94N1FGGalRG47WW4kp7XqM4KxjhN6\ntfGnMs+bA5j2LOJDBCcErmA7iiPNerqQVeaPPRR6JLqlBPxzhh0r4qr6sdmuk86E\nDY9UrrOGQ+Ux3qtr/zhrtUdGpkZS5l4TmjWPjD4vsJQz+uHgMMl31b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I95SV0R3LQsuBZ4tz1yRsJZ6vj3E5hh0dZSxRLjnVesXFEMXkHxUbvE/2wk7yHe\nzf7d9OkOXvaFB/zrFAYSIrW3pQygdUVbX182yVECgYAlhtBwb2T/cXezCQqONB/a\nyX6a5X3PwG1JEoBXXlrXb2FsX64vDdcQIuHQGhCSQ8wYr4HloIxwbqtdOt2nn3x7\nVBADOS+33hjwq5hIH7238UqGTl12nSYHxS2Q2m3GLlEX9ys5Zf8dvOLS4t933OJz\nC0rjmj/8zR8368XA2X8QpQ==\n-----END PRIVATE KEY-----\n","client_email": "i123456@confident-facet-364012.iam.gserviceaccount.com","client_id": "102254133935705883736","auth_uri": "https://accounts.google.com/o/oauth2/auth","token_uri": "https://oauth2.googleapis.com/token","auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs","client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/i123456%40confident-facet-364012.iam.gserviceaccount.com"}'
97 changes: 97 additions & 0 deletions src/controllers/calendar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
const expressAsyncHandler = require('express-async-handler');
const services = require('../services');

const { google } = require('googleapis');
require('dotenv').config();

// Provide the required configuration
const CREDENTIALS =
// JSON.parse(
process.env.CREDENTIALS;
// );

// Google calendar API settings
const SCOPES = 'https://www.googleapis.com/auth/calendar';
const calendar = google.calendar({ version: 'v3' });

const auth = new google.auth.JWT(
CREDENTIALS.client_email,
null,
CREDENTIALS.private_key,
SCOPES
);

// Insert Event Into Controller
const insertCalendar = expressAsyncHandler(async (req, res, next) => {
try {
let response = await calendar.events.insert({
auth: auth,
calendarId: req.body.calendarId,
resource: req.body.event,
});

if (response['status'] == 200 && response['statusText'] === 'OK') {
const message = 'Successfully added event into calendar';
return services.newEventToken({}, 'success', message, res);
} else {
return services.createSendToken({}, 'error', response['statusText'], res);
}
} catch (error) {
console.log(`Error at insertEvent --> ${error}`);
return services.createSendToken({}, 'error', error, res);
}
});

// Get Event in Calendar
const getCalendar = expressAsyncHandler(async (req, res, next) => {
try {
let response = await calendar.events.list({
auth: auth,
calendarId: req.body.calendarId,
timeMin: req.body.dateTimeStart,
timeMax: req.body.dateTimeEnd,
timeZone: 'Asia/Kolkata',
});

console.log(response);

let items = response['data']['items'];
const message = 'Successfully fetched events in calendar';
return services.newEventToken(items, 'success', message, res);
} catch (error) {
console.log(`Error at getEvents --> ${error}`);
return services.createSendToken({}, 'error', error, res);
}
});

// Delete Event in Calendar
const deleteCalendar = expressAsyncHandler(async (req, res, next) => {
try {
let response = await calendar.events.delete({
auth: auth,
calendarId: req.body.calendarId,
eventId: req.body.eventId,
});

if (response.data === '') {
const message = 'Successfully deleted event in calendar';
return services.newEventToken({}, 'success', message, res);
} else {
return services.createSendToken(
{},
'error',
'Something ent wrong hilt deleting',
res
);
}
} catch (error) {
console.log(`Error at deleteEvent --> ${error}`);
return services.createSendToken({}, 'error', error, res);
}
});

module.exports = {
getCalendar,
deleteCalendar,
insertCalendar,
};
134 changes: 79 additions & 55 deletions src/controllers/invite.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,84 +15,93 @@ module.exports.createInvite = asyncHandler(async (req, res, next) => {
// next(new AppError('Event not found', 404));
// }
// }

const foundEvent = await Event.findOne({ _id: event_id });
if (foundEvent.user_id.toString() !== req.user._id.toString()) {
next(new AppError('You are not the host of this event', 401));
}

let memo = [];
for (let i = 0; i < email_list.length; i++) {
if (memo.includes(email_list[i].toLowerCase()) === false) {
const eventToken = await generateJWTToken(
event_id,
{ event_id },
process.env.INVITATION_TOKEN_SECRET,
'1d'
'90d'
);

const invitationLink =
'https://catchup.hng.tech/participants/' + eventToken;
const email = email_list[i];
await sendInvitationLink(invitationLink, email);
memo.push(email_list[i].toLowerCase());
}
}

const invitationPayload = {
email_list: memo,
event_id,
userId: req.user.id,
active: true,
};
//find invitation where email and event_id match
const foundInvitation = await Invitation.findOne({
email: email_list[i].toLowerCase(),
event_id,
});

const newInvitation = await new Invitation(invitationPayload).save();
if (!foundInvitation) {
const email = email_list[i];
// await sendInvitationLink(invitationLink, email);
memo.push(email_list[i].toLowerCase());
const invitationPayload = {
email: email_list[i],
event_id,
};

return res.send({
const newInvitation = await new Invitation(invitationPayload).save();
}
}
}

return res.json({
status: 'success',
message: 'Invitations have been sent successfully',
data: {
newInvitation: newInvitation,
},
message: 'Invitations have been processed',
});
});

module.exports.updateInvite = asyncHandler(async (req, res, next) => {
const { email_list, event_id } = req.body;
const { id } = req.params;
// module.exports.updateInvite = asyncHandler(async (req, res, next) => {
// const { email_list, event_id } = req.body;
// const { id } = req.params;

const newInvitation = await Invitation.findById(id);
if (!newInvitation) {
next(new AppError('Invitation not found', 404));
}
// const newInvitation = await Invitation.findById(id);
// if (!newInvitation) {
// next(new AppError('Invitation not found', 404));
// }

let memo = [];
for (let i = 0; i < email_list.length; i++) {
if (
memo.includes(email_list[i].toLowerCase()) === false &&
newInvitation.email_list.includes(email_list[i].toLowerCase()) === false
) {
const eventToken = await generateJWTToken(
event_id,
process.env.INVITATION_TOKEN_SECRET,
'1d'
);
// let memo = [];
// for (let i = 0; i < email_list.length; i++) {
// if (
// memo.includes(email_list[i].toLowerCase()) === false &&
// newInvitation.email_list.includes(email_list[i].toLowerCase()) === false
// ) {
// const eventToken = await generateJWTToken(
// event_id,
// process.env.INVITATION_TOKEN_SECRET,
// '1d'
// );

const invitationLink =
'https://catchup.hng.tech/participants/' + eventToken;
const email = email_list[i];
memo.push(email_list[i].toLowerCase());
await sendInvitationLink(invitationLink, email);
}
}
// const invitationLink =
// 'https://catchup.hng.tech/participants/' + eventToken;
// const email = email_list[i];
// memo.push(email_list[i].toLowerCase());
// await sendInvitationLink(invitationLink, email);
// }
// }

newInvitation.email_list = [...newInvitation.email_list, ...memo];
newInvitation.save();
return res.send({
status: 'success',
message: 'Invitations have been updated and send successfully',
data: {
newInvitation: newInvitation,
},
});
});
// newInvitation.email_list = [...newInvitation.email_list, ...memo];
// newInvitation.save();
// return res.send({
// status: 'success',
// message: 'Invitations have been updated and send successfully',
// data: {
// newInvitation: newInvitation,
// },
// });
// });

module.exports.deleteInvite = asyncHandler(async (req, res, next) => {
const { email, event_id } = req.body;
const { id } = req.params;
// await Invitation.deleteMany({});
const newInvitation = await Invitation.findByIdAndUpdate(id, {
$pull: { email_list: email },
});
Expand Down Expand Up @@ -123,3 +132,18 @@ module.exports.getEventDetails = asyncHandler(async (req, res, next) => {
const payload = await jwt.verify(jwt, process.env.INVITATION_TOKEN_SECRET);
return res.status(200).json({ payload });
});


module.exports.getEventInvites = asyncHandler(async (req, res, next) => {
const { id } = req.params;
const invites = await Invitation.find({ event_id: id }).sort({
createdAt: 'desc',
});
return res.send({
status: 'success',
message: 'Invites retrieved successfully',
data: {
invites,
},
});
});
9 changes: 9 additions & 0 deletions src/controllers/participant.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const { createSendData } = require('../services');
const {
generateFinalEventsDates,
} = require('../services/generateFinalEventDate');
const Invitation = require('../models/invitation');

// adding a participant
const addParticipant = asyncHandler(async (req, res, next) => {
Expand Down Expand Up @@ -57,6 +58,14 @@ const addParticipant = asyncHandler(async (req, res, next) => {
preferred_date_time,
};
const participant = await new Participant(newParticipantData).save();
const foundInvitation = await Invitation.findOne({
email: email,
event_id,
});
if (foundInvitation) {
foundInvitation.status = 'accepted';
await foundInvitation.save();
}
return createSendData(participant, 'success', message, res);
});

Expand Down
13 changes: 5 additions & 8 deletions src/models/invitation.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,20 @@ const mongoose = require('mongoose');

const invitationSchema = new mongoose.Schema(
{
userId: {
email: {
type: String,
required: true,
},
email_list: {
type: Array,
required: true,
lowercase: true,
},
event_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Event',
required: true,
},
active: {
type: Boolean,
},
status: {
type: String,
required: true,
default: 'pending',
},
},
{
Expand Down
5 changes: 4 additions & 1 deletion src/routes/v1/invitation.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const {
deleteInvite,
getAllInvites,
getEventDetails,
getEventInvites,
} = require('../../controllers/invite');
const services = require('../../services');

Expand All @@ -13,7 +14,9 @@ router.use(services.protect);

router.get('/', getAllInvites);
router.post('/', createInvite);
router.patch('/:id', updateInvite);
// router.patch('/:id', updateInvite);
router.delete('/:id', deleteInvite);
router.get("/event/:jwt", getEventDetails);
router.get('/event/:id', getEventInvites);

module.exports = router;
2 changes: 1 addition & 1 deletion src/services/Mail/sendAccountRecoveryToken.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const sendAccountRecoveryToken = async (token, email) => {

const options = {
from: {
email: `lordorionrules@gmail.com`,
email: `lordorion066@gmail.com`,
name: 'Catch Up',
},
to: email,
Expand Down
2 changes: 1 addition & 1 deletion src/services/Mail/sendInvitationLink.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const sendInvitationLink = async (token, email) => {

const options = {
from: {
email: `lordorionrules@gmail.com`,
email: `lordorion066@gmail.com`,
name: 'Catch Up',
},
to: email,
Expand Down

0 comments on commit 14ec228

Please sign in to comment.