Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate Auth Utils into ViewTrips Components #113

Merged
merged 20 commits into from
Aug 5, 2020
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
74fbc25
Add converting auth util functions
keiffer01 Jul 24, 2020
f5cc4e3
Remove unnecessary semicolons
keiffer01 Jul 24, 2020
a092b3d
JSDoc formatting
keiffer01 Jul 27, 2020
ac94795
Merge branch 'authutils-converting' of github.com:googleinterns/step5…
zghera Jul 28, 2020
5751398
Remove temp utils.
zghera Jul 28, 2020
261da47
Replace temp auth functions with legitimate ones in filter-input.js.
zghera Jul 28, 2020
261e9f5
Replace temp auth functions with legitimate ones in trips-container.js.
zghera Jul 28, 2020
73859cf
Add state to trip component to use temp auth functions with legitimat…
zghera Jul 28, 2020
2e917e0
Edit implementation to be asynchronous in order to correctly use getU…
zghera Jul 29, 2020
eb0ab86
Add async for formatting trip data (required calls to userUid -> user…
zghera Jul 29, 2020
ab4cabf
Add moveCurUserEmailToFront and other small refactors.
zghera Jul 29, 2020
ee7af5f
Add tests for moveCurUserEmailToFront.
zghera Jul 29, 2020
54dbb3c
Merge branch 'master' into integrate-auth-utils
zghera Jul 29, 2020
29ad2b7
Merge branch 'master' into integrate-auth-utils
zghera Jul 29, 2020
5e25888
Merge branch 'master' into integrate-auth-utils
zghera Jul 30, 2020
068797b
Fix spelling of 'mitigate' in JSDoc.
zghera Jul 30, 2020
a09f7b7
Remove accidentally added JSDoc files.
zghera Jul 30, 2020
b97f73d
Add comment to clarify use of cleanup function is useEffect.
zghera Aug 3, 2020
d43a39c
Merge branch 'master' into integrate-auth-utils
zghera Aug 3, 2020
a06165b
Merge branch 'master' into integrate-auth-utils
zghera Aug 5, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions frontend/src/components/Utils/filter-input.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as firebase from 'firebase/app';

import authUtils from '../AuthUtils';
import { getUserUidArrFromUserEmailArr } from './temp-auth-utils.js'
import { getTimestampFromDateString } from './time.js'

/**
Expand All @@ -15,31 +14,32 @@ export function getCleanedTextInput(rawInput, defaultValue) {
}

/**
* Return an array of collaborator uids given the emails provided in the
* add trip form.
* Return a promise containing an array of collaborator uids given the emails
* provided in the add trip form.
*
* TODO(#72 & #67): Remove 'remove empty fields' once there is better way to
* remove collaborators (#72) and there is email validation (#67).
*
* @param {!Array{string}} collaboratorEmailsArr Array of emails corresponding
* @param {!Array<string>} collaboratorEmailsArr Array of emails corresponding
* to the collaborators of the trip (not including the trip creator email).
* @return {!Array{string}} Array of all collaborator uids (including trip
* @return {Promise<!Array<string>>} Array of all collaborator uids (including trip
zghera marked this conversation as resolved.
Show resolved Hide resolved
* creator uid).
*/
export function getCollaboratorUidArray(collaboratorEmailArr) {
export async function getCollaboratorUidArray(collaboratorEmailArr) {
collaboratorEmailArr = [authUtils.getCurUserEmail()]
.concat(collaboratorEmailArr);
.concat(collaboratorEmailArr);

// Removes empty fields (temporary until fix #67 & #72).
const cleanedCollaboratorEmailArr = collaboratorEmailArr.filter(email => {
return email !== '';
})
return getUserUidArrFromUserEmailArr(cleanedCollaboratorEmailArr);
});

return await authUtils.getUserUidArrFromUserEmailArr(cleanedCollaboratorEmailArr);
}

/**
* Returns a formatted and cleaned trip object that will be used as the data
* for the created Trip document.
* Returns a promise containing the formatted and cleaned trip object that will
* be used as the data for the created Trip document.
*
* We know that rawTripObj will contain all of the necessary fields because each
* key-value pair is explicitly included. This means, only the value
Expand All @@ -50,12 +50,13 @@ export function getCollaboratorUidArray(collaboratorEmailArr) {
*
* @param {!Object} rawTripObj A JS Object containing the raw form data from the
* add trip form.
* @return {!Object} Formatted/cleaned version of `rawTripObj` holding the data
* @return {Promise<!Object>} Formatted/cleaned version of `rawTripObj` holding the data
* for the new Trip document that is to be created.
*/
export function formatTripData(rawTripObj) {
export async function formatTripData(rawTripObj) {
const defaultName = "Untitled Trip";
const defaultDestination = "No Destination"
const collaboratorUidArr = await getCollaboratorUidArray(rawTripObj.collaboratorEmails);

const formattedTripObj = {
trip_creation_time: firebase.firestore.Timestamp.now(),
Expand All @@ -65,7 +66,7 @@ export function formatTripData(rawTripObj) {
defaultDestination),
start_date: getTimestampFromDateString(rawTripObj.startDate),
end_date: getTimestampFromDateString(rawTripObj.endDate),
collaborators: getCollaboratorUidArray(rawTripObj.collaboratorEmails),
collaborators: collaboratorUidArr,
};

return formattedTripObj;
Expand Down
20 changes: 9 additions & 11 deletions frontend/src/components/Utils/filter-input.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { getUserUidArrFromUserEmailArr } from './temp-auth-utils';
import { getCleanedTextInput, getCollaboratorUidArray } from './filter-input.js';

describe('getCleanedTextInput tests', () => {
Expand Down Expand Up @@ -26,47 +25,46 @@ describe('getCleanedTextInput tests', () => {
const mockCurUserEmail = 'cur.user@email.com';
jest.mock('../AuthUtils', () => ({
getCurUserEmail: () => mockCurUserEmail,
}));
// TODO(Issue #55): Replace mock with real auth file once integrated.
jest.mock('./temp-auth-utils.js', () => ({
getUserUidArrFromUserEmailArr: (userEmailArr) => {
return userEmailArr.map(userEmail => '_' + userEmail + '_');
return new Promise(resolve => {
resolve(userEmailArr.map(userEmail => '_' + userEmail + '_'));
});
},
}));
describe('getCollaboratorUidArray tests', () => {
test('No collaborators entered', () => {
test('No collaborators entered', async () => {
const expectedUidArr = [`_${mockCurUserEmail}_`];
// This is the list that is created when there are no collaborators added
// (automatically one empty string from the constructor created ref).
const testEmailArr = [''];

const testUidArr = getCollaboratorUidArray(testEmailArr);
const testUidArr = await getCollaboratorUidArray(testEmailArr);

expect(testUidArr).toEqual(expectedUidArr);
});

test('Some added collaborators', () => {
test('Some added collaborators', async () => {
const person1Email = 'p1@gmail.com';
const person2Email = 'p2@outlook.com';
const expectedUidArr = [`_${mockCurUserEmail}_`,
`_${person1Email}_`,
`_${person2Email}_`];
const testEmailArr = [person1Email, person2Email];

const testUidArr = getCollaboratorUidArray(testEmailArr);
const testUidArr = await getCollaboratorUidArray(testEmailArr);

expect(testUidArr).toEqual(expectedUidArr);
});

test('Some added collaborators and some blank entries', () => {
test('Some added collaborators and some blank entries', async () => {
const person1Email = 'p1@gmail.com';
const person2Email = 'p2@outlook.com';
const expectedUidArr = [`_${mockCurUserEmail}_`,
`_${person1Email}_`,
`_${person2Email}_`];
const testEmailArr = ['', person1Email, '', person2Email, ''];

const testUidArr = getCollaboratorUidArray(testEmailArr);
const testUidArr = await getCollaboratorUidArray(testEmailArr);

expect(testUidArr).toEqual(expectedUidArr);
});
Expand Down
64 changes: 0 additions & 64 deletions frontend/src/components/Utils/temp-auth-utils.js

This file was deleted.

8 changes: 4 additions & 4 deletions frontend/src/components/ViewTrips/save-trip-modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ class SaveTripModal extends React.Component {
/**
* Formats/cleans the form data and saves the Trip document in firestore.
*/
saveTrip() {
const tripData = formatTripData(
saveTrip = async () => {
const tripData = await formatTripData(
{
name: this.nameRef.current.value,
description: this.descriptionRef.current.value,
Expand All @@ -137,8 +137,8 @@ class SaveTripModal extends React.Component {
* - Refreshing the trips container.
* - Closing the modal.
*/
handleSubmitForm = () => {
this.saveTrip();
handleSubmitForm = async () => {
await this.saveTrip();
this.props.refreshTripsContainer();
this.props.handleClose();
}
Expand Down
50 changes: 37 additions & 13 deletions frontend/src/components/ViewTrips/trip.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React from 'react';
import React, {useState, useEffect} from 'react';

import Button from 'react-bootstrap/Button';

import authUtils from '../AuthUtils';
import { timestampToISOString } from '../Utils/time.js';
import { getUserEmailArrFromUserUidArr } from '../Utils/temp-auth-utils.js';
import DeleteTripButton from './delete-trip-button.js';
import ViewActivitiesButton from './view-activities-button.js';

Expand All @@ -30,19 +30,23 @@ export function getDateRange(tripData) {
}

/**
* Return collaborator emails corresponding to the collaborator uid's
* `collaboratorUidArr` in a comma separated string.
* Returns an array with the same contents as `collaboratorEmailArr` except that
* the current user email is moved to be the first element of the array (the
* other elements maintain their original order).
*
* @param {!Array<string>} collaboratorUidArr Array of collaborator uids
* stored in trip document.
* @returns {string} Collaborator emails in comma separated string.
* Ex: "person1@email.com, person2@email.com".
* @param {!string[]} collaboratorEmailArr Array of user emails sorted in
* alphabetical order.
* @return {!string[]} Array of user emails where first element is the current
* user email and the following elements maintain their previous order.
*/
export function getCollaboratorEmails(collaboratorUidArr) {
const collaboratorEmailArr = getUserEmailArrFromUserUidArr(collaboratorUidArr);
return collaboratorEmailArr.join(', ');
export function moveCurUserEmailToFront(collaboratorEmailArr) {
collaboratorEmailArr = collaboratorEmailArr.filter(email => {
return email !== authUtils.getCurUserEmail();
zghera marked this conversation as resolved.
Show resolved Hide resolved
});
return [authUtils.getCurUserEmail()].concat(collaboratorEmailArr);
}


/**
* Component corresponding to the container containing an individual trip.
*
Expand All @@ -63,8 +67,28 @@ const Trip = (props) => {
const name = props.tripData.name;
const description = props.tripData.description;
const destination = props.tripData.destination;
const collaboratorEmailsStr =
getCollaboratorEmails(props.tripData.collaborators);
const collaboratorUidArr = props.tripData.collaborators;
const [collaboratorEmailsStr, setCollaboratorEmailsStr] = useState('');

useEffect(() => {
// Only set state collaboratorEmailsStr if component is mounted. This is
// a precautionary to mitigate warnings that occur when setting state on
// a component that has already unmounted. See more here
// https://www.robinwieruch.de/react-warning-cant-call-setstate-on-an-unmounted-component.
let componentStillMounted = true;

async function fetchCollaboratorEmails() {
let collaboratorEmailArr =
await authUtils.getUserEmailArrFromUserUidArr(collaboratorUidArr);
collaboratorEmailArr = moveCurUserEmailToFront(collaboratorEmailArr);
if (componentStillMounted) {
setCollaboratorEmailsStr(collaboratorEmailArr.join(', '));
}
}

fetchCollaboratorEmails();
return () => { componentStillMounted = false; };
zghera marked this conversation as resolved.
Show resolved Hide resolved
}, [collaboratorUidArr]);

const formattedTripData = {
name: name,
Expand Down
37 changes: 36 additions & 1 deletion frontend/src/components/ViewTrips/trip.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as firebase from 'firebase/app';
import 'firebase/firebase-firestore';

import { getDateRange } from './trip.js'
import { getDateRange, moveCurUserEmailToFront } from './trip.js'

test('getDateRange test', () => {
// Dates used for both test and expected date strings.
Expand All @@ -25,3 +25,38 @@ test('getDateRange test', () => {
`${endMonth}/${endDay}/${endYear}`;
expect(testDateRange).toEqual(expectedDateRange);
})

const mockCurUserEmail = 'cur.user@email.com';
const USER_A_EMAIL = 'apple@email.com';
const USER_Z_EMAIL = 'zamboni@email.com';
jest.mock('../AuthUtils', () => ({
getCurUserEmail: () => mockCurUserEmail,
}));
describe('moveCurUserEmailToFront tests', () => {
test('No users (error is caught in getUserEmailArrFromUserUidArr)', async () => {
const expectedEmailArr = [mockCurUserEmail];
const testEmailInputArr = [];

const testEmailOutputArr = moveCurUserEmailToFront(testEmailInputArr);

expect(testEmailOutputArr).toEqual(expectedEmailArr);
});

test('Only the current user', async () => {
const expectedEmailArr = [mockCurUserEmail];
const testEmailInputArr = [mockCurUserEmail];

const testEmailOutputArr = moveCurUserEmailToFront(testEmailInputArr);

expect(testEmailOutputArr).toEqual(expectedEmailArr);
});

test('Current user between two others (alphabetical order)', async () => {
const expectedEmailArr = [mockCurUserEmail, USER_A_EMAIL, USER_Z_EMAIL];
const testEmailInputArr = [USER_A_EMAIL, mockCurUserEmail, USER_Z_EMAIL];

const testEmailOutputArr = moveCurUserEmailToFront(testEmailInputArr);

expect(testEmailOutputArr).toEqual(expectedEmailArr);
});
});
4 changes: 2 additions & 2 deletions frontend/src/components/ViewTrips/trips-container.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import React from 'react';

import app from '../Firebase/';

import authUtils from '../AuthUtils';
import * as DB from '../../constants/database.js';
import { getCurUserUid } from '../Utils/temp-auth-utils.js'
import Trip from './trip.js';

const db = app.firestore();
Expand All @@ -17,7 +17,7 @@ const db = app.firestore();
* containing the query results with zero or more Trip documents.
*/
function queryUserTrips(db) {
const curUserUid = getCurUserUid();
const curUserUid = authUtils.getCurUserUid();
return db.collection(DB.COLLECTION_TRIPS)
.where(DB.TRIPS_COLLABORATORS, 'array-contains', curUserUid)
.orderBy(DB.TRIPS_CREATION_TIME, 'desc')
Expand Down