Skip to content

Commit

Permalink
Move encryption to an external service (#89)
Browse files Browse the repository at this point in the history
* Initial commit

* Create PR template

* Add .md extension to PR template

* DEPENDENCY: added react-router-dom

* DEPENDECY: added prop-types

* BUG: removed Typescript notation from Home.js

* ADDITION: added Navbar and Member file structure

* UPGRADE: adapted Home.js to functional component

* FEAT: added routes between pages

* DEPENDENCY: @hack4impact-uiuc/bridge

* formatted code with Prettier

* FORMAT: Removed unused imports

* FORMAT: Ran prettier styling

* Add community .github to this repo

* Create member DB model

* Run formatter

* Change spread to Object.values

* Connected to mongo atlas and successfully retried Home resource

* Add vercel config

* Remove config

* Add vercel.json back in

* Update secret names

* Set up MongoDB Atlas (#15)

* Connected to mongo atlas and successfully retried Home resource

* Ran yarn format

* add MONGO_URL to CI test

* fixed formatting and tests

* modify gitignore to ignore all env files in api/config

* resolve merge conflict in app.js

* re-add template config files

* add config files to .gitignore

* Frontend Auth (#13)

* FEAT: basic structure of navbar

* FEAT: added login feature to view any page

* REMOVE: incorrent dependency location

* FEAT: add login connected to UNTESTED endpoint

* PAGE: added 404 Not Found Page

* LINT: added prop-types and styling

* REMOVE: deleted 404 page

* DEPENDENCY: added ag-grid

* STYLING: Updated Profile dropdown CSS

* STYLING: changed Login Page styling

* FEAT: added proper headers for ag-grid

* LINT: fixes some lint issues

* DOCUMENATION: added comments to components

* LINT: fixed documentation styling

* LINT: fixed prop-types

* PR FEEDBACK: resolves @alicesf2 comments

* PR FEEDBACK: resolves @mattwalo32 comments

* Fix vercel deployments (#18)

* Change variables to start with REACT_APP

* Use VERCEL_URL variable

* ignore all .env files

* Change mongo var name

* Fix variable name typo

* Run formatter

* Deleted failing test

* Add flag to pass with no tests

* Remove vercel dependency

* Remove REACT_APP prefix

* Remove .env files

* Remove global dependency

* Readd env files

* gitignore env files

* Add test back

* Delete dev.env

* Remove "pass with no tests" flag

* Backend auth (#14)

* Enable connection to Mongo

* Install passport and express-session

* Change most member attributes to not required

* Add auth routes

* Add passport setup with cookie sessions

* Add options for express-session

* Add options for express-session

* Move passport-setup to root

* Add middleware for auth

* Change auth routes to use result instead of data

* Add protected route as an example

* Remove home test and replace with dummy test

* Remove dummy test

* Remove console.log

* Remove extra || null

* Add back home.test.js and new env vars to api.yaml

* Add example dev.env

* Add redirectURI endpoint to allow for changing Vercel subdomains

* Add redirect URLs as parameters for /login

* Format auth.js

* Remove FRONTEND_URI from example env file

* Enable failure flash

* Add back .env files

* Add vercel env vars

* Remove OAUTH_CALLBACK_URI from production env

* Frontend-Backend Auth connection (#22)

* Redirct to backend login api

* Use CORS in dev with proper auth settings

* FEAT: removes auth state and connects sess. to api

* LINT: fixed styling and prop-type errors

* Ran prettier

Co-authored-by: Jeffrey Tang <[email protected]>

* Members endpoints with GET, POST, and PUT (#21)

* Create basic endpoint skeleton

* get endpoint 500 error

* Fix routing

* Get member endpoint to work

* Return more fields from endpoint

* Return object id from endpoint

* Add filterSensitiveInfo util

* Give all non-required Member fields a default of null

* Move passport-setup to utils

* Remove console.log

* Add members endpoints

* Fix filterSensitiveInfo util

* Use passport-setup.js in utils

* Use auth endpoint

* Move /api/auth/user to /api/members/current

* Add omit fields to GET /:memberId

* Change current user endpoint in frontend

* Add more auth utils

* Use isDirector from module in members routes

* Change level default in model back to TBD

* Add level priority explanation

* Add detailed permission checking in members endpoint

* Fix difference function

* Fix typos in user-utils

* Add _id as neverEditable field

* Fix allFields not being checked correctly

* Filter viewable fields when returning from PUT

Co-authored-by: mlw6 <[email protected]>
Co-authored-by: ishaansharma <[email protected]>

* Remove extraneous router (#25)

* Member profile page (#23)

* Create basic endpoint skeleton

* get endpoint 500 error

* Fix routing

* Get member endpoint to work

* Return more fields from endpoint

* Return object id from endpoint

* Add filterSensitiveInfo util

* Give all non-required Member fields a default of null

* Move passport-setup to utils

* Remove console.log

* Add members endpoints

* Fix filterSensitiveInfo util

* Use passport-setup.js in utils

* Use auth endpoint

* Move /api/auth/user to /api/members/current

* Add omit fields to GET /:memberId

* Change current user endpoint in frontend

* Add more auth utils

* Use isDirector from module in members routes

* Change level default in model back to TBD

* Add level priority explanation

* Add detailed permission checking in members endpoint

* Fix difference function

* Fix typos in user-utils

* Add _id as neverEditable field

* Fix allFields not being checked correctly

* Filter viewable fields when returning from PUT

* Pull enum options from backend

* Add status options to endpoint

* Disable dropdowns

* Add labels to fields

* Create wrapper for getting member by ID

* Add boolean selector

* Add number fields

* Add fields for basic string attributes

* Retrieve schema type from DB

* Move preprocessing to backend

* Fix enum type detection

* Remove duplicated code

* Fix attribute change error

* Run formatter

* Remove warnings

* Format client

* Populate edit fields from DB

* Add types to props

* Run formatter

* Remove alert

* Run formatter

* Get permissions from backend

* Disable input boxes if missing permissions

* Add enum dropdowns

* Format client

* Remove user ID override

* Change to ES6 defaults

* Remove unused package

* Change var to let

* Concisen member options endpoint

* Delete env file

* Unexport schema

* Use concise property iteration

* Make /options endpoint concise

* Remove unneeded exports

* Capitalize constant

* Shorten attribute change callback

* Run formatter

* Turn off default-props in linter

* Fix var name typo

* Change member page routing

* Run formatter

* Use useParams hook

* Change object syntax

* Run formatter

* Link "View Profile" to current logged-in user

* Fix lint, ignore _id

* Run format

* Don't show mongo ID

* Rename Member.js to Profile.js

* Run formatter

* Store fields in value instead of placeholder

Co-authored-by: ishaansharma <[email protected]>
Co-authored-by: Jeffrey Tang <[email protected]>

* Add lint-staged pre-commit hook (#27)

* Add lint-staged pre-commit hook

* Format "unstaged" files

* Sync prettier versions

* Homepage Member Grid (#19)

* added another row to member grid

* added some filters to columns

* added filters to applicable columns

* added custom sorting for date-related fields

* format

* added filter to all fields

* enabled floating filters in member grid, minor styling changes

* yarn format

* extract coldefs and mock member data to utils files, decrease line height in overflow text

* yarn lint

* yarn and yarn format

* Consolidate .env files (#28)

* Consolidate envs and clean up app.js

* Fix yarn test not using .env

* Add null to enum options so default works (#24)

* Add null to enum options so default works

* Use TBD as enum defaults rather than null

* Transfer old data (#29)

* Create basic endpoint skeleton

* get endpoint 500 error

* Fix routing

* Get member endpoint to work

* Return more fields from endpoint

* Return object id from endpoint

* Add filterSensitiveInfo util

* Give all non-required Member fields a default of null

* Move passport-setup to utils

* Remove console.log

* Add members endpoints

* Fix filterSensitiveInfo util

* Use passport-setup.js in utils

* Use auth endpoint

* Move /api/auth/user to /api/members/current

* Add omit fields to GET /:memberId

* Change current user endpoint in frontend

* Add more auth utils

* Use isDirector from module in members routes

* Change level default in model back to TBD

* Add level priority explanation

* Add detailed permission checking in members endpoint

* Fix difference function

* Fix typos in user-utils

* Add _id as neverEditable field

* Fix allFields not being checked correctly

* Filter viewable fields when returning from PUT

* Pull enum options from backend

* Add status options to endpoint

* Disable dropdowns

* Add labels to fields

* Create wrapper for getting member by ID

* Add boolean selector

* Add number fields

* Add fields for basic string attributes

* Retrieve schema type from DB

* Move preprocessing to backend

* Fix enum type detection

* Remove duplicated code

* Fix attribute change error

* Run formatter

* Remove warnings

* Format client

* Populate edit fields from DB

* Add types to props

* Run formatter

* Remove alert

* Run formatter

* Get permissions from backend

* Disable input boxes if missing permissions

* Add enum dropdowns

* Format client

* Remove user ID override

* Change to ES6 defaults

* Remove unused package

* Change var to let

* Concisen member options endpoint

* Delete env file

* Unexport schema

* Use concise property iteration

* Make /options endpoint concise

* Remove unneeded exports

* Capitalize constant

* Shorten attribute change callback

* Run formatter

* Turn off default-props in linter

* Fix var name typo

* Change member page routing

* Run formatter

* Use useParams hook

* Change object syntax

* Run formatter

* Start creating tool to transfer data

* Consolidate envs and clean up app.js

* Fix yarn test not using .env

* Add lint-staged pre-commit hook (#27)

* Add lint-staged pre-commit hook

* Format "unstaged" files

* Sync prettier versions

* Format all files using new Prettier config

* Finish writing tool

* Format remaining fields

* Check for member uniqueness

* Fix enum formatting

* Run formatter

* Run formatter

* Run format with new hook

* Remove duplicate of Profile.js

Co-authored-by: ishaansharma <[email protected]>
Co-authored-by: Jeffrey Tang <[email protected]>
Co-authored-by: Yousef Ahmed <[email protected]>

* added comments to Table.js for backend connection

* Fix/update README (#26)

* Remove README from .github to fix overriding

* Update README for this project

* Fix image sizes

* Fix image sizes

* added Ainfo for Alice Fang

* Add Matthew's Profile Picture

* Update README.md

* added Ishaan's info

Co-authored-by: Alice Fang <[email protected]>
Co-authored-by: Matthew Walowski <[email protected]>
Co-authored-by: Amit Sawhney <[email protected]>
Co-authored-by: ishaansharma <[email protected]>

* Upgrade node-notifier to 8.0.1 (#36)

* Attribute editing fix (#37)

* Create basic endpoint skeleton

* get endpoint 500 error

* Fix routing

* Get member endpoint to work

* Return more fields from endpoint

* Return object id from endpoint

* Add filterSensitiveInfo util

* Give all non-required Member fields a default of null

* Move passport-setup to utils

* Remove console.log

* Add members endpoints

* Fix filterSensitiveInfo util

* Use passport-setup.js in utils

* Use auth endpoint

* Move /api/auth/user to /api/members/current

* Add omit fields to GET /:memberId

* Change current user endpoint in frontend

* Add more auth utils

* Use isDirector from module in members routes

* Change level default in model back to TBD

* Add level priority explanation

* Add detailed permission checking in members endpoint

* Fix difference function

* Fix typos in user-utils

* Add _id as neverEditable field

* Fix allFields not being checked correctly

* Filter viewable fields when returning from PUT

* Pull enum options from backend

* Add status options to endpoint

* Disable dropdowns

* Add labels to fields

* Create wrapper for getting member by ID

* Add boolean selector

* Add number fields

* Add fields for basic string attributes

* Retrieve schema type from DB

* Move preprocessing to backend

* Fix enum type detection

* Remove duplicated code

* Fix attribute change error

* Run formatter

* Remove warnings

* Format client

* Populate edit fields from DB

* Add types to props

* Run formatter

* Remove alert

* Run formatter

* Get permissions from backend

* Disable input boxes if missing permissions

* Add enum dropdowns

* Format client

* Remove user ID override

* Change to ES6 defaults

* Remove unused package

* Change var to let

* Concisen member options endpoint

* Delete env file

* Unexport schema

* Use concise property iteration

* Make /options endpoint concise

* Remove unneeded exports

* Capitalize constant

* Shorten attribute change callback

* Run formatter

* Turn off default-props in linter

* Fix var name typo

* Change member page routing

* Run formatter

* Use useParams hook

* Change object syntax

* Run formatter

* Start creating tool to transfer data

* Consolidate envs and clean up app.js

* Fix yarn test not using .env

* Add lint-staged pre-commit hook (#27)

* Add lint-staged pre-commit hook

* Format "unstaged" files

* Sync prettier versions

* Format all files using new Prettier config

* Finish writing tool

* Format remaining fields

* Check for member uniqueness

* Fix enum formatting

* Run formatter

* Run formatter

* Run format with new hook

* Change new sign-in process to attempt to link user via email

* Show login error on frontend

* Remove unused Member page (renamed)

* Fix navbar welcome text spacing

* Fix lint

* Switch to cookie-session

* Change date attribute prop type to number

* Allow numbers for string attribute value

* Change enum attribute prop types

* Add keys to fields

* Only pass string to enum callback

* Fix default enum attribute option

* Rename StringAttribute to TextAttribute

Co-authored-by: ishaansharma <[email protected]>
Co-authored-by: Jeffrey Tang <[email protected]>
Co-authored-by: Yousef Ahmed <[email protected]>

* STRUCTURE: added basic api endpoint structures

* Added base structure attempt at notes endpoint

* Abstracted notes middleware and updated PUT

* New user auth flow (#31)

* Create basic endpoint skeleton

* get endpoint 500 error

* Fix routing

* Get member endpoint to work

* Return more fields from endpoint

* Return object id from endpoint

* Add filterSensitiveInfo util

* Give all non-required Member fields a default of null

* Move passport-setup to utils

* Remove console.log

* Add members endpoints

* Fix filterSensitiveInfo util

* Use passport-setup.js in utils

* Use auth endpoint

* Move /api/auth/user to /api/members/current

* Add omit fields to GET /:memberId

* Change current user endpoint in frontend

* Add more auth utils

* Use isDirector from module in members routes

* Change level default in model back to TBD

* Add level priority explanation

* Add detailed permission checking in members endpoint

* Fix difference function

* Fix typos in user-utils

* Add _id as neverEditable field

* Fix allFields not being checked correctly

* Filter viewable fields when returning from PUT

* Pull enum options from backend

* Add status options to endpoint

* Disable dropdowns

* Add labels to fields

* Create wrapper for getting member by ID

* Add boolean selector

* Add number fields

* Add fields for basic string attributes

* Retrieve schema type from DB

* Move preprocessing to backend

* Fix enum type detection

* Remove duplicated code

* Fix attribute change error

* Run formatter

* Remove warnings

* Format client

* Populate edit fields from DB

* Add types to props

* Run formatter

* Remove alert

* Run formatter

* Get permissions from backend

* Disable input boxes if missing permissions

* Add enum dropdowns

* Format client

* Remove user ID override

* Change to ES6 defaults

* Remove unused package

* Change var to let

* Concisen member options endpoint

* Delete env file

* Unexport schema

* Use concise property iteration

* Make /options endpoint concise

* Remove unneeded exports

* Capitalize constant

* Shorten attribute change callback

* Run formatter

* Turn off default-props in linter

* Fix var name typo

* Change member page routing

* Run formatter

* Use useParams hook

* Change object syntax

* Run formatter

* Start creating tool to transfer data

* Consolidate envs and clean up app.js

* Fix yarn test not using .env

* Add lint-staged pre-commit hook (#27)

* Add lint-staged pre-commit hook

* Format "unstaged" files

* Sync prettier versions

* Format all files using new Prettier config

* Finish writing tool

* Format remaining fields

* Check for member uniqueness

* Fix enum formatting

* Run formatter

* Run formatter

* Run format with new hook

* Change new sign-in process to attempt to link user via email

* Show login error on frontend

* Remove unused Member page (renamed)

* Fix navbar welcome text spacing

* Fix lint

* Switch to cookie-session

* Make login failure text constant

* Make login failure query param constant

Co-authored-by: mlw6 <[email protected]>
Co-authored-by: ishaansharma <[email protected]>
Co-authored-by: Yousef Ahmed <[email protected]>

* added api call to get all members

* Profile layout (#45)

* Add style prop to attributes

* Make fields take two columns

* Style date attribute

* Allow boolean attribute to take booleans

* Cast memberID to string before comparing for perms

* Rename ProfileFragment to ProfileDropdown

* Rename ProfileDropdown folder

* Update editable fields (#43)

* added notes schema

* changed memberid to string type

* changed default values for arrays

* Allow Members to Update Profile (#46)

* Add style prop to attributes

* Make fields take two columns

* Style date attribute

* Allow boolean attribute to take booleans

* Cast memberID to string before comparing for perms

* Rename ProfileFragment to ProfileDropdown

* Rename ProfileDropdown folder

* Send PUT request on member update

* Style button

* Add success messsage and conditionally disable submit button

* Run formatter

* Set upstream user after updating profile

* Exported notes api

* Member grid backend connection (#49)

* added comments to Table.js for backend connection

* added api call to get all members

* -fixed member state variable

Co-authored-by: Alice Fang <[email protected]>

* Style Migration (#50)

* added support for semantic ui react

* removed support for bridge

* migrated login page to semantic ui

* replaced all bridge components with semantic, minor styling edits

* yarn format

* add husky

* yarn add husky to root

* removed css comments and fixed package.json

* add formatting

* Add formatting for conflicts

* add string validation

* removed console.log

* Refactor small pieces of notes

* format code

* Remove unused note.js file

* changed phone regex and modularized validation function

* Add GET note labels endpoint

* Bump elliptic from 6.5.3 to 6.5.4 in /client (#57)

Bumps [elliptic](https://github.com/indutny/elliptic) from 6.5.3 to 6.5.4.
- [Release notes](https://github.com/indutny/elliptic/releases)
- [Commits](indutny/elliptic@v6.5.3...v6.5.4)

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* tested an fixed all endpoints

* formatting

* Missing Fields (#58)

* add comment

* add momentjs and sorting/cohorts dates

* centralized fieldvals

* finished adding all missing fields

* add styling fixes

* remove unecessary deletes

* format

* add stylistic changes

* add permit optional chaining from flow

* add modules, remove react-jsonschema-form-semanticui

* add notes routing

* add note editor, temp notes list

* add new api wrappers

* add remove react-jsonschema-form-semanticui package

* add fields for access

* add sidebar for saving and metadata

* Change get endpoint to return member object

* format

* Refactor code

* format

* Add version control for put requests

* Bump ssri from 6.0.1 to 6.0.2 in /client (#67)

Bumps [ssri](https://github.com/npm/ssri) from 6.0.1 to 6.0.2.
- [Release notes](https://github.com/npm/ssri/releases)
- [Changelog](https://github.com/npm/ssri/blob/v6.0.2/CHANGELOG.md)
- [Commits](npm/ssri@v6.0.1...v6.0.2)

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Fix map formatting

* remove default parameter

* Update put request

* Ad get endpoint fix

* format

* Add edit version control for put

* format

* add upsert

* format

* add validate member info

* add fix key casing

* add new profile and navbar

* add update navbar flex

* add table styles, formatting

* add layout for pages

* add working notes and note pages

* add remove console.log in notes

* Add edit version control for notes PUT endpoint (#69)

* Add edit version control for put

* format

* add upsert

* add cleanup, documentation

* Updated get so that editableBy users also can view by default

* format

* Add Members UI (#70)

* add button for new user

* add user created on frontend

* add user created on frontend

* formatting

* linting

* fixed add members

* linting

* comments

* comments

* linting

* add required fields

* removed css

* linting

* fixed year validation

* generalized digit regex

* add success message, default editor

* add view-only mode, grab user to check for view-mode

* add forward to Id page on note creation

* Bump lodash from 4.17.20 to 4.17.21 in /api (#79)

Bumps [lodash](https://github.com/lodash/lodash) from 4.17.20 to 4.17.21.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](lodash/lodash@4.17.20...4.17.21)

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Bump lodash from 4.17.20 to 4.17.21 (#78)

Bumps [lodash](https://github.com/lodash/lodash) from 4.17.20 to 4.17.21.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](lodash/lodash@4.17.20...4.17.21)

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Size notes columns to fit page width

* Edit user default privileges for notes (#80)

* Add memberID as editor when creating note by default

* Remove the current member from the dropdowns when creating a note

* Remove outdated comment

* Update README.md

* Add delete note functionality

* Update public site attributes

* Bump hosted-git-info from 2.8.8 to 2.8.9 in /api (#82)

Bumps [hosted-git-info](https://github.com/npm/hosted-git-info) from 2.8.8 to 2.8.9.
- [Release notes](https://github.com/npm/hosted-git-info/releases)
- [Changelog](https://github.com/npm/hosted-git-info/blob/v2.8.9/CHANGELOG.md)
- [Commits](npm/hosted-git-info@v2.8.8...v2.8.9)

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Bump hosted-git-info from 2.8.8 to 2.8.9 (#81)

Bumps [hosted-git-info](https://github.com/npm/hosted-git-info) from 2.8.8 to 2.8.9.
- [Release notes](https://github.com/npm/hosted-git-info/releases)
- [Changelog](https://github.com/npm/hosted-git-info/blob/v2.8.9/CHANGELOG.md)
- [Commits](npm/hosted-git-info@v2.8.8...v2.8.9)

Signed-off-by: dependabot[bot] <[email protected]>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Add ability to encrypt notes (#83)

* Add encryption and decryption algorithms

* Incorporate encryption with notes feature

* Remove logs and set default encrypt state to true

* Update README with ME

* Preserve production URL

* Add Tech Director, meeting, and other enum types

* Update email regex and add 403 error for notes

* Change encryption method to use an external service

* Add axios dependency

* Disable csrf

* Fix formatting

* Delete leftover files

* Update encryption service domain

* Move api rate limit to catch all routes

* Fix linting

* Cleanup files

* Implement requested changes

* Format files

Co-authored-by: Jeffrey Tang <[email protected]>
Co-authored-by: Matthew Walowski <[email protected]>
Co-authored-by: Amit Sawhney <[email protected]>
Co-authored-by: Amit Sawhney <[email protected]>
Co-authored-by: Alice Fang <[email protected]>
Co-authored-by: Alice Fang <[email protected]>
Co-authored-by: ishaansharma <[email protected]>
Co-authored-by: IshaanRSharma <[email protected]>
Co-authored-by: Daniel <[email protected]>
Co-authored-by: Daniel Moon <[email protected]>
Co-authored-by: Leundai <[email protected]>
Co-authored-by: Daniel Moon <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Siraj <[email protected]>
  • Loading branch information
15 people authored May 25, 2021
1 parent 55fbbe8 commit f3cb8a5
Show file tree
Hide file tree
Showing 11 changed files with 165 additions and 102 deletions.
1 change: 1 addition & 0 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"test": "jest --setupFiles dotenv/config"
},
"dependencies": {
"axios": "^0.21.1",
"cookie-parser": "^1.4.5",
"cookie-session": "^1.4.0",
"cors": "^2.8.5",
Expand Down
2 changes: 2 additions & 0 deletions api/src/api/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ router.get('/login', (req, res, next) => {
const auth = passport.authenticate('google', {
scope: ['profile', 'email'],
state: Buffer.from(JSON.stringify(state)).toString('base64'),
prompt: 'consent',
accessType: 'offline',
});
auth(req, res, next);
});
Expand Down
148 changes: 105 additions & 43 deletions api/src/api/notes.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const {
validateEditability,
validateReqParams,
} = require('../middleware/notes');
const { encryptNote, decryptNote } = require('../utils/notes');
const { encryptNote, decryptNote } = require('../utils/apiWrapper');

/**
* returns member names and ids from valid received ids
Expand All @@ -21,20 +21,21 @@ const { encryptNote, decryptNote } = require('../utils/notes');
* @returns {Array<Object>}
*/
const memberFromId = async (ids) => {
const memberPromises = ids
// filters out invalid ids
.filter((id) => !!id)
// creates promises for each valid id
.map((memberId) => Member.findById(memberId));

// get member data
const members = await Promise.all(memberPromises);
const members = await Member.find(
{ _id: { $in: ids } },
{ firstName: 1, lastName: 1 },
);

const formattedMembers = {};
// return derived full name and id from meber
return members.map((member) => ({
memberId: member._id,
name: `${member.firstName} ${member.lastName}`,
}));
members.forEach(
(member) =>
(formattedMembers[member._id] = {
memberId: member._id,
name: `${member.firstName} ${member.lastName}`,
}),
);
return formattedMembers;
};

router.get(
Expand All @@ -61,28 +62,47 @@ router.get(
],
}).lean();

const memberIds = [
...note.metaData.access.viewableBy,
...note.metaData.access.editableBy,
...note.metaData.referencedMembers,
];
const uniqueMemberIds = [...new Set(memberIds)];
const formattedMembers = await memberFromId(uniqueMemberIds);

// Replace all members ids with object that has id and name
note['metaData']['access']['viewableBy'] = await memberFromId(
note['metaData']['access']['viewableBy'],
note.metaData.access.viewableBy = note.metaData.access.viewableBy.map(
(member) => formattedMembers[member],
);
note['metaData']['access']['editableBy'] = await memberFromId(
note['metaData']['access']['editableBy'],
note.metaData.access.editableBy = note.metaData.access.editableBy.map(
(member) => formattedMembers[member],
);
note['metaData']['referencedMembers'] = await memberFromId(
note['metaData']['referencedMembers'],
note.metaData.referencedMembers = note.metaData.referencedMembers.map(
(member) => formattedMembers[member],
);

if (note.encrypt) {
const encryptionKey = req.user.oauthID + req.user.UIN;

try {
note.content = await decryptNote(note.content, encryptionKey);
} catch (err) {
return res.status(403).json({
success: false,
message: 'Unauthorized',
});
}
const partialEncryptionKey = req.user.oauthID + req.user.UIN;
const authedCredentials = req.session.authedCredentials;
const result = await decryptNote({
authedCredentials,
note,
partialEncryptionKey,
});

if (result.error && !result.error.response)
return res
.status(500)
.json({ success: false, message: 'encryption service is down' });
if (result.error)
return res
.status(403)
.json({ success: false, message: 'unauthorized' });

note.content = result.data.note;

if (result.data.newToken)
req.session.authedCredentials.accessToken = result.data.newToken;
}

res.status(200).json({
Expand All @@ -96,7 +116,6 @@ router.get(
'/',
requireRegistered,
errorWrap(async (req, res) => {
const output_notes = [];
const filter = {
'metaData.title': 1,
'metaData.labels': 1,
Expand All @@ -119,24 +138,30 @@ router.get(
filter,
).lean();

for (let note of notes) {
const memberIds = notes.flatMap((note) => [
...note.metaData.access.viewableBy,
...note.metaData.access.editableBy,
...note.metaData.referencedMembers,
]);
const uniqueMemberIds = [...new Set(memberIds)];
const formattedMembers = await memberFromId(uniqueMemberIds);

notes.forEach((note) => {
// Replace all members ids with object that has id and name
note['metaData']['access']['viewableBy'] = await memberFromId(
note['metaData']['access']['viewableBy'],
note.metaData.access.viewableBy = note.metaData.access.viewableBy.map(
(member) => formattedMembers[member],
);
note['metaData']['access']['editableBy'] = await memberFromId(
note['metaData']['access']['editableBy'],
note.metaData.access.editableBy = note.metaData.access.editableBy.map(
(member) => formattedMembers[member],
);
note['metaData']['referencedMembers'] = await memberFromId(
note['metaData']['referencedMembers'],
note.metaData.referencedMembers = note.metaData.referencedMembers.map(
(member) => formattedMembers[member],
);

output_notes.push(note);
}
});

res.status(200).json({
success: true,
result: output_notes,
result: notes,
});
}),
);
Expand All @@ -161,7 +186,26 @@ router.post(
req.body.metaData.access.editableBy.push(memberID.toString());

if (req.body.encrypt) {
req.body.content = await encryptNote(req.body);
const authedCredentials = req.session.authedCredentials;
const note = req.body;
const result = await encryptNote({
authedCredentials,
note,
});

if (!result.error.response)
return res
.status(500)
.json({ success: false, message: 'encryption service is down' });
if (result.error)
return res
.status(403)
.json({ success: false, message: 'unauthorized' });

data.content = result.data.note;

if (result.data.newToken)
req.session.authedCredentials.accessToken = result.data.newToken;
}

const note = await Note.create(req.body);
Expand Down Expand Up @@ -195,7 +239,25 @@ router.put(

data.metaData.versionHistory = currentVersionHistory;
if (req.body.encrypt) {
data.content = await encryptNote(req.body);
const authedCredentials = req.session.authedCredentials;
const note = req.body;
const result = await encryptNote({
authedCredentials,
note,
});

if (!result.error.response)
return res
.status(500)
.json({ success: false, message: 'encryption service is down' });
if (result.error)
return res
.status(403)
.json({ success: false, message: 'unauthorized' });

data.content = result.data.note;
if (result.data.newToken)
req.session.authedCredentials.accessToken = result.data.newToken;
}

const updatedNote = await Note.findByIdAndUpdate(
Expand Down
9 changes: 3 additions & 6 deletions api/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,17 @@ const cookieSession = require('cookie-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const passport = require('passport');
const csrf = require('csurf');
const apiRoutes = require('./api');
const { errorHandler } = require('./middleware');
const environment = process.env.NODE_ENV || 'dev';
const app = express();

const limiter = new RateLimit({
windowMs: 1 * 60 * 1000,
max: 15,
windowMs: 5 * 60 * 1000, // Set window to 5 minutes
max: 60, // Maximum number of requests per minute
});

app.use('/auth/', limiter);
app.use(limiter);

// HTTPS, CORS, bodyParser
app.use(helmet());
Expand All @@ -36,15 +35,13 @@ app.use(bodyParser.urlencoded({ limit: '2.1mb', extended: false }));
const sessionConfig = {
secret: process.env.SESSION_SECRET,
};

if (environment == 'production') {
app.set('trust proxy', 1);
sessionConfig.secure = true;
}

app.use(cookieSession(sessionConfig));
app.use(cookieParser());
app.use(csrf({ cookie: true }));

// Mongo setup
require('./utils/mongo-setup');
Expand Down
24 changes: 24 additions & 0 deletions api/src/utils/apiWrapper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const axios = require('axios');

const SERVICE_URL = process.env.SERVICE_URL;

const encryptNote = (body) => {
const requestString = `${SERVICE_URL}/encrypt`;
return axios.post(requestString, body).catch((error) => ({
type: 'ENCRYPT_FAIL',
error,
}));
};

const decryptNote = (body) => {
const requestString = `${SERVICE_URL}/decrypt`;
return axios.post(requestString, body).catch((error) => ({
type: 'DECRYPT_FAIL',
error,
}));
};

module.exports = {
encryptNote,
decryptNote,
};
10 changes: 0 additions & 10 deletions api/src/utils/members.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,22 +74,12 @@ const validateField = (field, value, validatingFields) => {
return true;
};

// Generates encryption passwords as a combination of the unique oauthID and UIN
const generateEncryptionPasswords = async (memberIds, db) => {
const members = await Member.find({ _id: { $in: memberIds } });
const encryptionPasswords = members.map(
(member) => member.oauthID + member.UIN,
);
return encryptionPasswords;
};

module.exports = {
allFields,
getEditableFields,
getViewableFields,
filterViewableFields,
validateField,
validationFields,
generateEncryptionPasswords,
errorMessages,
};
40 changes: 0 additions & 40 deletions api/src/utils/notes.js

This file was deleted.

11 changes: 10 additions & 1 deletion api/src/utils/passport-setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,20 @@ passport.use(
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.OAUTH_CALLBACK_URI,
passReqToCallback: true,
},
async (accessToken, refreshToken, profile, cb) => {
async (req, accessToken, refreshToken, profile, cb) => {
// find the user in the database based on their oauth id
const user = await Member.findOne({ oauthID: profile.id });

// Set the user's tokens
req.session.authedCredentials = {
accessToken,
refreshToken,
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
};

if (user) {
// user exists
cb(null, user);
Expand Down
Loading

1 comment on commit f3cb8a5

@vercel
Copy link

@vercel vercel bot commented on f3cb8a5 May 25, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.