Skip to content

Commit

Permalink
removed config error throwing
Browse files Browse the repository at this point in the history
  • Loading branch information
xandermcleod committed Feb 10, 2024
1 parent f264604 commit 84b8f40
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 125 deletions.
83 changes: 39 additions & 44 deletions packages/backend/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,59 @@
import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
import express from 'express';
import dotenv from 'dotenv';
import mongoose from 'mongoose';

import eventRoute from "./event/event-route";
import userRoute from "./user/user-route";
import registerRoute from "./register/register-route";
import paymentRoute from "./payment/payment-route";
import webhookRoute from "./webhook/webhook-route";
import cors from "cors";
import { verifyToken } from "./middleware/verifyToken";
import { verifyAdmin } from "./middleware/verifyAdmin";
import firebase_admin from "firebase-admin";
import eventRoute from './event/event-route';
import userRoute from './user/user-route';
import registerRoute from './register/register-route';
import paymentRoute from './payment/payment-route';
import webhookRoute from './webhook/webhook-route';
import cors from 'cors';
import { verifyToken } from './middleware/verifyToken';
import { verifyAdmin } from './middleware/verifyAdmin';
import firebase_admin from 'firebase-admin';

const conf = dotenv.config();
if (conf.error) {
throw conf.error;
}

const app = express();
const port = process.env.PORT || 5000;
const dbURL = `${process.env.DB_URL}`;
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
measurementId: process.env.FIREBASE_MEASUREMENT_ID,
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
measurementId: process.env.FIREBASE_MEASUREMENT_ID,
};
firebase_admin.initializeApp(firebaseConfig);
app.use(cors());
app.use((req, res, next) => {
if (req.originalUrl.startsWith("/stripe_webhooks")) {
// we need raw instead of json so that we can use webhook signing
next();
} else {
express.json()(req, res, next);
}
if (req.originalUrl.startsWith('/stripe_webhooks')) {
// we need raw instead of json so that we can use webhook signing
next();
} else {
express.json()(req, res, next);
}
});

app.use(verifyToken);
app.use(verifyAdmin);

app.use("/events", eventRoute);
app.use("/users", userRoute);
app.use("/register", registerRoute);
app.use("/payment", paymentRoute);
app.use("/stripe_webhooks", webhookRoute);
app.use('/events', eventRoute);
app.use('/users', userRoute);
app.use('/register', registerRoute);
app.use('/payment', paymentRoute);
app.use('/stripe_webhooks', webhookRoute);

mongoose
.connect(dbURL)
.then(() => {
app.listen(port, () => {
console.log(
`Connected to database. Server is running on port: ${port}`
);
});
})
.catch((error) => {
console.log(error);
.connect(dbURL)
.then(() => {
app.listen(port, () => {
console.log(`Connected to database. Server is running on port: ${port}`);
});
})
.catch((error) => {
console.log(error);
});
110 changes: 54 additions & 56 deletions packages/backend/src/email/emailService.ts
Original file line number Diff line number Diff line change
@@ -1,72 +1,70 @@
import sgMail from "@sendgrid/mail";
import dotenv from "dotenv";
import fs from "fs";
import path from "path";
import sgMail from '@sendgrid/mail';
import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';

const conf = dotenv.config();
if (conf.error) {
throw conf.error;
}

const apiKey = process.env.SENDGRID_API_KEY;
const fromEmail = process.env.SENDGRID_FROM_EMAIL;
if (apiKey == null) {
throw new Error("SENDGRID_API_KEY is not defined in your environment.");
throw new Error('SENDGRID_API_KEY is not defined in your environment.');
}
sgMail.setApiKey(apiKey);
export default class EmailService {
public static async _sendEmail(
to: string,
subject: string,
name: string,
title: string,
message: string
) {
if (fromEmail == null) {
throw new Error(
"SENDGRID_FROM_EMAIL is not defined in your environment."
);
}
// FIXME: This is a hacky way to use templates
// setup a template_id in sendgrid and use that instead if possible
const templatePath = path.join(
__dirname,
"./email-templates",
`send-confirmation.html`
);
const html = fs
.readFileSync(templatePath, "utf8")
.replace(/{{name}}/g, name)
.replace(/{{title}}/g, title)
.replace(/{{message}}/g, message);
public static async _sendEmail(
to: string,
subject: string,
name: string,
title: string,
message: string
) {
if (fromEmail == null) {
throw new Error(
'SENDGRID_FROM_EMAIL is not defined in your environment.'
);
}
// FIXME: This is a hacky way to use templates
// setup a template_id in sendgrid and use that instead if possible
const templatePath = path.join(
__dirname,
'./email-templates',
`send-confirmation.html`
);
const html = fs
.readFileSync(templatePath, 'utf8')
.replace(/{{name}}/g, name)
.replace(/{{title}}/g, title)
.replace(/{{message}}/g, message);

console.log("finished loading file");
console.log('finished loading file');

const msg = {
to,
from: fromEmail,
subject,
html,
};
const msg = {
to,
from: fromEmail,
subject,
html,
};

await sgMail.send(msg);
console.log("Email sent");
return;
}
await sgMail.send(msg);
console.log('Email sent');
return;
}

public static async sendEventEmail(
toEmail: string,
name: string,
eventName: string,
eventDate: string,
eventLocation: string,
paymentMethod: string
) {
const subject = `ASPA UOA ${eventName} Registration`;
const title = "ASPA UOA";
const message = `You have registered for ${eventName} on ${eventDate} at ${eventLocation} successfully!
public static async sendEventEmail(
toEmail: string,
name: string,
eventName: string,
eventDate: string,
eventLocation: string,
paymentMethod: string
) {
const subject = `ASPA UOA ${eventName} Registration`;
const title = 'ASPA UOA';
const message = `You have registered for ${eventName} on ${eventDate} at ${eventLocation} successfully!
Your payment for this event was made with ${paymentMethod}.
We look forward to seeing you there!
`;
await this._sendEmail(toEmail, subject, name, title, message);
}
await this._sendEmail(toEmail, subject, name, title, message);
}
}
31 changes: 14 additions & 17 deletions packages/backend/src/payment/payment-controller.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,27 @@
import { Request, Response } from "express";
import { Event } from "../event/event-model";
import { User } from "../user/user-model";
import Stripe from "stripe";
import { Request, Response } from 'express';
import { Event } from '../event/event-model';
import { User } from '../user/user-model';
import Stripe from 'stripe';

import dotenv from "dotenv";
import dotenv from 'dotenv';

const conf = dotenv.config();
if (conf.error) {
throw conf.error;
}

const secret = process.env.STRIPE_SECRET_KEY;
if (!secret)
throw new Error("Stripe secret key not found. Please update .env file.");
const stripe = new Stripe(secret, { apiVersion: "2022-11-15" });
throw new Error('Stripe secret key not found. Please update .env file.');
const stripe = new Stripe(secret, { apiVersion: '2022-11-15' });

/**
* Backend controller for Stripe Checkout.
*/
export const checkout = async (req: Request, res: Response) => {
if (!req.params.eventId) {
res.status(400).json("Missing req.params.eventId");
res.status(400).json('Missing req.params.eventId');
return;
}
if (!req.params.userId) {
res.status(400).json("Missing req.params.userId");
res.status(400).json('Missing req.params.userId');
return;
}

Expand Down Expand Up @@ -55,7 +52,7 @@ export const checkout = async (req: Request, res: Response) => {

// Create a Stripe Checkout Session
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
payment_method_types: ['card'],
line_items: [
{
// there is an adjustable quantity option btw
Expand All @@ -64,9 +61,9 @@ export const checkout = async (req: Request, res: Response) => {
},
],
success_url:
"http://localhost:3000/success-payment?session_id={CHECKOUT_SESSION_ID}",
cancel_url: "http://localhost:3000/failed-payment",
mode: "payment",
'http://localhost:3000/success-payment?session_id={CHECKOUT_SESSION_ID}',
cancel_url: 'http://localhost:3000/failed-payment',
mode: 'payment',
metadata: {
userId: user.id,
eventId: event.id,
Expand All @@ -81,7 +78,7 @@ export const checkout = async (req: Request, res: Response) => {
// redirect customer to url from checkout session
const payment_page = session.url;
if (!payment_page) {
const err = new Error("No payment page presented");
const err = new Error('No payment page presented');
res.status(400).json(err);
return;
}
Expand Down
13 changes: 5 additions & 8 deletions packages/backend/tools/getToken.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
// Script to get the token from firebase
// import dotenv from "dotenv";
const dotenv = require("dotenv");
const dotenv = require('dotenv');
const conf = dotenv.config();
if (conf.error) {
throw conf.error;
}

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append('Content-Type', 'application/json');

const email = process.env.SCRIPT_EMAIL;
const password = process.env.SCRIPT_PASSWORD;
Expand All @@ -20,10 +17,10 @@ var raw = JSON.stringify({
});

var requestOptions = {
method: "POST",
method: 'POST',
headers: myHeaders,
body: raw,
redirect: "follow",
redirect: 'follow',
};

fetch(
Expand All @@ -32,4 +29,4 @@ fetch(
)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
.catch((error) => console.log('error', error));

0 comments on commit 84b8f40

Please sign in to comment.