Skip to content

Commit

Permalink
Merge pull request #46 from acmutd/dev
Browse files Browse the repository at this point in the history
Patch 1.0.1
  • Loading branch information
harshasrikara authored Feb 22, 2021
2 parents 1fde070 + c38f090 commit 9d037cf
Show file tree
Hide file tree
Showing 22 changed files with 735 additions and 315 deletions.
52 changes: 52 additions & 0 deletions functions/src/admin/auth0.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import * as axios from "axios";
import * as functions from "firebase-functions";
import * as Sentry from "@sentry/node";
import logger from "../services/logging";

export const get_auth_token = async (): Promise<string> => {
const result = await axios.default.post(
`https://${functions.config().auth0.domain}/oauth/token`,
{
grant_type: "client_credentials",
client_id: functions.config().auth0_api.clientid,
client_secret: functions.config().auth0_api.client_secret,
audience: `https://${functions.config().auth0.domain}/api/v2/`,
},
{
headers: {
"content-type": "application/json",
},
}
);
return result.data.access_token;
};

export const add_callback = async (url: string, access_token: string): Promise<void> => {
try {
const result = await axios.default.get(
`https://${functions.config().auth0.domain}/api/v2/clients/${
functions.config().auth0.clientid
}?fields=callbacks&include_fields=true`,
{
headers: { "content-type": "application/json", authorization: `Bearer ${access_token}` },
}
);
const callbacks = result.data.callbacks;
callbacks.push(url);
await axios.default.patch(
`https://${functions.config().auth0.domain}/api/v2/clients/${functions.config().auth0.clientid}`,
{
callbacks: callbacks,
},
{
headers: { "content-type": "application/json", authorization: `Bearer ${access_token}` },
}
);
} catch (err) {
logger.log({
...err,
message: "Error occurred in updating callback urls on Auth0",
});
Sentry.captureException(err);
}
};
25 changes: 25 additions & 0 deletions functions/src/admin/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Admin

[admin.ts](./admin.ts) handles centrally initializing the Firebase Admin to access various different services across different files / functions.

### Admin.ts

When needing to use additional services from firebase instantiate them in [admin.ts](./admin.ts) and import them where needed. Also use this place to pass in custom arguments or different configuration parameters.

### Auth0.ts

This service handles performing OAuth exchanges to get access tokens. Also used by the event checkin service to add callback urls to Auth0.
### Notes

- The `service-account.json` file is not passed in as a paramter to `admin.initializeApp()` because the backend is deployed on Firebase Functions and those variables are automatically accessible as environment variables. If the backend is shifted elsewhere then those variables will need to be passed in.
- If you choose write any standalone scripts store them in this folder.
- When creating services that perform OAuth client-credential exchanges create new files for them here
- Ensure that an `async get_auth_token` is present any services that perform authentication. Reuse the same token per API transaction instead of instantiating a new one for each function call.

### Questions

Sometimes you may have additional questions. If the answer was not found in this readme please feel free to reach out to the [Director of Development](mailto:[email protected]) for _ACM_

We request that you be as detailed as possible in your questions, doubts or concerns to ensure that we can be of maximum assistance. Thank you!

![ACM Development](https://www.acmutd.co/brand/Development/Banners/light_dark_background.png)
18 changes: 16 additions & 2 deletions functions/src/application/portal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export const create_blank_profile = async (request: Request, response: Response)

export const record_event = async (request: Request, response: Response): Promise<void> => {
const pathname = (request.query.checkpath as string).substring((request.query.checkpath as string).lastIndexOf("/"));
const is_checkin = (request.query.checkpath as string).includes("checkin");
const data = request.body;
try {
const result = await firestore
Expand All @@ -64,20 +65,33 @@ export const record_event = async (request: Request, response: Response): Promis
return;
}

const field_name = is_checkin ? "past_events" : "past_rsvps";

firestore
.collection(profile_collection)
.doc(data.sub)
.set(
{
email: data.email,
sub: data.sub,
past_events: admin.firestore.FieldValue.arrayUnion({
[field_name]: admin.firestore.FieldValue.arrayUnion({
name: result.data()?.name,
submitted_at: new Date().toISOString(),
submitted_at: result.data()?.date,
}),
},
{ merge: true }
);
const field = is_checkin ? "attendance" : "rsvp";

firestore
.collection(event_collection)
.doc(pathname as string)
.update({
[field]: admin.firestore.FieldValue.arrayUnion({
sub: data.sub,
email: data.email,
}),
});
logger.log({
...data,
...result.data(),
Expand Down
50 changes: 50 additions & 0 deletions functions/src/application/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Portal

This code drives the majority of the backend responsible for powering the ACM Portal.

### Portal Functions

```
// fill at later point in time
```
### Typeform Functions

The typeform functions section is very mature and is responsible for all interactions with the third party service.

##### Open Webhook

The `typeform_webhook` function present in [typeform.ts](./typeform.ts) is responsible for receiving all incoming webhook requests from typeform. When creating a new typeform make sure to add in the following url as a webhook: `https://us-central1-acm-core.cloudfunctions.net/challenge/typeform`.

This function will extract all the information within the typeform response body and save only the relevant fields in the following format. An array of `qa` type objects represents the final state of the object that is persisted in Cloud Firestore. This format makes it easy to quickly retrieve typeform responses and perform additional manipulation with Firestore Triggers.

```
export interface qa {
question: string;
answer: string;
type: string;
}
```

Hidden fields are also extracted from Typeform submissions and saved in the same format. In this situation the `question` will be the hidden field key and the `answer` will be the hidden field value.

##### Confirmation Emails

One essential part to ensuring that members who submit forms to ACM are happy and aware that their submission was received is to send them confirmation emails. While typeform natively supports sending confirmation emails it does not support the ability to customize and design them to match the ACM Brand Guidelines. In [typeform.ts](./typeform.ts) we have the `send_confirmation` firestore trigger. This function gets run anytime a new typeform document gets saved in Cloud Firestore.

This functions queries the `typeform_meta` firestore collection with the `typeform_id` to see whether there exists a confirmation email that should be sent. If the exists information regarding the Sendgrid template / sender information then this firestore trigger will call the Sendgrid API to send out that specific email. Adding a new configuration can be done through the officer utility [Sendgrid x Typeform](https://survey.acmutd.co/email).

##### Custom Actions

Sometimes we want to perform a custom action based on the submission of a typeform. These are typically the internal utilities made for the ACM officer to refine workflows. All custom action functions are saved in [Custom Actions](../custom). These are also Firestore Triggers and get executed anytime a new document is created. The following functions have custom triggers:

- [Vanity Form](https://survey.acmutd.co/vanity)
- [Sendgrid Form](https://survey.acmutd.co/email)
- [Event Form](https://survey.acmutd.co/event)

### Questions

Sometimes you may have additional questions. If the answer was not found in this readme please feel free to reach out to the [Director of Development](mailto:[email protected]) for _ACM_

We request that you be as detailed as possible in your questions, doubts or concerns to ensure that we can be of maximum assistance. Thank you!

![ACM Development](https://www.acmutd.co/brand/Development/Banners/light_dark_background.png)
47 changes: 45 additions & 2 deletions functions/src/application/typeform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@ import { firestore } from "../admin/admin";
import logger from "../services/logging";
import { upsert_contact, send_dynamic_template, user_contact, sendgrid_email } from "../mail/sendgrid";
import admin from "firebase-admin";
import { build_vanity_link } from "../custom/vanity";
import { connect_sendgrid } from "../custom/sendgrid_map";
import { create_event } from "../custom/event";
// import crypto from "crypto";

const profile_collection = "profile";
const typeform_meta_collection = "typeform_meta";

type definition = {
id: string;
title: string;
Expand Down Expand Up @@ -93,7 +99,7 @@ export const send_confirmation = functions.firestore
.onCreate(async (snap, context) => {
const document = snap.data();
try {
const meta_doc = await firestore.collection("typeform_meta").doc(document.typeform_id).get();
const meta_doc = await firestore.collection(typeform_meta_collection).doc(document.typeform_id).get();
if (!meta_doc.exists) {
logger.log(`No email template found for typeform ${document.typeform_id}`);
return;
Expand Down Expand Up @@ -146,15 +152,52 @@ export const send_confirmation = functions.firestore
`sending email to user ${sub} with email ${email} in response to completion of form ${document.typeform_id}`
);
await firestore
.collection("profile")
.collection(profile_collection)
.doc(sub)
.update({
past_applications: admin.firestore.FieldValue.arrayUnion({
name: document.typeform_id,
submitted_at: document.submission_time,
}),
});
await firestore
.collection(typeform_meta_collection)
.doc(document.typeform_id)
.update({
submitted: admin.firestore.FieldValue.arrayUnion({
sub: sub,
email: email,
}),
});
} catch (error) {
Sentry.captureException(error);
}
});

export const custom_form_actions = functions.firestore
.document("typeform/{document_name}")
.onCreate(async (snap, context) => {
const document = snap.data();
try {
switch (document.typeform_id) {
case "Link Generator":
build_vanity_link(document);
break;
case "Connect Sendgrid":
connect_sendgrid(document);
break;
case "Event Generator":
create_event(document);
break;
default:
logger.log(`No custom action found for typeform ${document.typeform_id}... exiting`);
return;
}
} catch (error) {
logger.log({
...error,
message: "Error occured in custom typeform function",
});
Sentry.captureException(error);
}
});
Expand Down
52 changes: 52 additions & 0 deletions functions/src/custom/deprecated_vanity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import * as functions from "firebase-functions";
import * as Sentry from "@sentry/node";
import request from "request";
import sendgrid from "@sendgrid/mail";

/**
* @deprecated limited functionality
*/
export const create_vanity_link = functions.firestore
.document("vanity_link/{document_name}")
.onCreate((snap, context) => {
const document_value = snap.data();
try {
const linkRequest = {
destination: document_value.vanity_redirect,
domain: { fullName: document_value.vanity_domain + ".acmutd.co" },
slashtag: document_value.vanity_slash,
};

const requestHeaders = {
"Content-Type": "application/json",
apikey: functions.config().rebrandly.apikey,
};

request(
{
uri: "https://api.rebrandly.com/v1/links",
method: "POST",
body: JSON.stringify(linkRequest),
headers: requestHeaders,
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(err: any, res: any, body: string) => {
//const link = JSON.parse(body);
sendgrid.setApiKey(functions.config().sendgrid.apikey);
const msg: sendgrid.MailDataRequired = {
from: "[email protected]",
to: document_value.email,
dynamicTemplateData: {
preheader: "Successful Generation of Vanity Link",
subject: "Vanity Link",
vanity_link: document_value.vanity_domain + ".acmutd.co/" + document_value.vanity_slash,
},
templateId: "d-cd15e958009a43b3b3a8d7352ee12c79",
};
sendgrid.send(msg);
}
);
} catch (error) {
Sentry.captureException(error);
}
});
78 changes: 78 additions & 0 deletions functions/src/custom/event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { firestore } from "../admin/admin";
import logger from "../services/logging";
import { send_dynamic_template, sendgrid_email } from "../mail/sendgrid";
import { get_auth_token, add_callback } from "../admin/auth0";

export interface EventDoc {
name: string;
path_name: string;
date: string;
}

const event_collection = "event";

export const create_event = async (document: FirebaseFirestore.DocumentData): Promise<void> => {
const typeform_results = document.data;
let first_name = "";
let last_name = "";
let email = "";
let name = "";
let path_name = "";
let date = "";

const first_name_question = "first_name";
const last_name_question = "last_name";
const email_question = "email";
const name_question = "Name of Event";
const path_name_question = "path";
const date_question = "date";

typeform_results.forEach((element: any) => {
if (element.question.includes(first_name_question)) first_name = element.answer;
if (element.question.includes(last_name_question)) last_name = element.answer;
if (element.question.includes(email_question)) email = element.answer;
if (element.question.includes(name_question)) name = element.answer;
if (element.question.includes(path_name_question)) path_name = element.answer;
if (element.question.includes(date_question)) date = new Date(element.answer).toDateString();
});

const email_options: sendgrid_email = {
from: "[email protected]",
from_name: "ACM Development",
template_id: "d-f2d3b8a1b4dd4c14895905b7abb4581b",
to: email,
dynamicSubstitutions: {
first_name: first_name,
last_name: last_name,
name: name,
checkin_link: `https://app.acmutd.co/checkin/${path_name}`,
date: date,
preheader: "Successful Event Check-in Creation Connection",
subject: "Event Creation Confirmation",
},
};

const data: EventDoc = {
name: name,
path_name: path_name,
date: date,
};

create_map(data);
add_callback(`https://app.acmutd.co/checkin/${path_name}`, await get_auth_token());
send_dynamic_template(email_options);
};

const create_map = (document: EventDoc): void => {
firestore
.collection(event_collection)
.doc(document.path_name)
.create({
...document,
path_name: `/checkin/${document.path_name}`,
});
logger.log({
...document,
message: "Successfully created an event check-in",
});
};
Loading

0 comments on commit 9d037cf

Please sign in to comment.