Skip to content

Commit

Permalink
Replaced axios with fetch
Browse files Browse the repository at this point in the history
Removed axios from package.json. And replaced axios call with fetch call.
  • Loading branch information
jerryren527 committed Nov 1, 2023
1 parent bcf15dc commit 061243b
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 67 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
"@babel/runtime": "^7.10.2",
"@sentry/node": "^5.17.0",
"async-exit-hook": "^2.0.1",
"axios": "^1.5.1",
"babel-plugin-module-resolver": "^5.0.0",
"bcryptjs": "^2.4.3",
"body-parser": "^1.18.3",
Expand Down
131 changes: 65 additions & 66 deletions src/controllers/userProfileController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const moment = require('moment-timezone');

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const axios = require('axios')
import fetch from 'node-fetch';

const moment_ = require('moment');
const jwt = require('jsonwebtoken');
Expand Down Expand Up @@ -60,27 +60,25 @@ const userProfileController = function (UserProfile) {

UserProfile.find(
{},
"_id firstName lastName role weeklycommittedHours email permissions isActive reactivationDate createdDate endDate"
'_id firstName lastName role weeklycommittedHours email permissions isActive reactivationDate createdDate endDate',
)
.sort({
lastName: 1,
})
.then((results) => {
if (!results) {
if (cache.getCache("allusers")) {
const getData = JSON.parse(cache.getCache("allusers"));
if (cache.getCache('allusers')) {
const getData = JSON.parse(cache.getCache('allusers'));
res.status(200).send(getData);
return;
}else{
res.status(500).send({ error: "User result was invalid" });
return;
}
res.status(500).send({ error: 'User result was invalid' });
return;
}
cache.setCache("allusers", JSON.stringify(results));
cache.setCache('allusers', JSON.stringify(results));
res.status(200).send(results);
})
.catch((error) => res.status(404).send(error));

.catch(error => res.status(404).send(error));
};

const getProjectMembers = async function (req, res) {
Expand All @@ -94,19 +92,18 @@ const userProfileController = function (UserProfile) {
$in: [req.params.projectId],
},
},
"_id firstName email",
'_id firstName email',
(err, profiles) => {
if (err) {
res.status(404).send("Error finding user profiles");
res.status(404).send('Error finding user profiles');
return;
}
res.json(profiles);
}
},
);
};

const postUserProfile = async function (req, res) {

if (!await hasPermission(req.body.requestor, 'postUserProfile')) {
res.status(403).send('You are not authorized to create new users');
return;
Expand All @@ -120,32 +117,38 @@ const userProfileController = function (UserProfile) {
const userByEmail = await UserProfile.findOne({
email: {
$regex: escapeRegex(req.body.email),
$options: "i",
$options: 'i',
},
});


if (userByEmail) {
res.status(400).send({
error:
"That email address is already in use. Please choose another email address.",
type: "email",
'That email address is already in use. Please choose another email address.',
type: 'email',
});
return;
}

// In dev environment, if newly created user is Owner or Administrator, make fetch request to Beta login route with actualEmail and actual Password
if (process.env.dbName === 'hgnData_dev') {
if (req.body.role === 'Owner' || req.body.role === 'Administrator') {
const email = req.body.actualEmail
const password = req.body.actualPassword
const url = "https://hgn-rest-beta.azurewebsites.net/api/"
const email = req.body.actualEmail;
const password = req.body.actualPassword;
const url = 'https://hgn-rest-beta.azurewebsites.net/api/';
try {
// Log in to Beta login route using provided credentials
let response = await axios.post(url + "login", {
email: email,
password: password
})
const response = await fetch(`${url }login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
});
if (!response.ok) {
throw new Error('Invalid credentials');
}
} catch (error) {
res.status(400).send({
error: 'The actual email or password you provided is incorrect. Please enter the actual email and password associated with your account in the Main HGN app.',
Expand All @@ -170,8 +173,8 @@ const userProfileController = function (UserProfile) {
if (userByPhoneNumber) {
res.status(400).send({
error:
"That phone number is already in use. Please choose another number.",
type: "phoneNumber",
'That phone number is already in use. Please choose another number.',
type: 'phoneNumber',
});
return;
}
Expand All @@ -185,8 +188,8 @@ const userProfileController = function (UserProfile) {
if (userDuplicateName && !req.body.allowsDuplicateName) {
res.status(400).send({
error:
"That name is already in use. Please confirm if you want to use this name.",
type: "name",
'That name is already in use. Please confirm if you want to use this name.',
type: 'name',
});
return;
}
Expand All @@ -213,15 +216,15 @@ const userProfileController = function (UserProfile) {
up.projects = Array.from(new Set(req.body.projects));
up.createdDate = req.body.createdDate;
up.email = req.body.email;
up.weeklySummaries = req.body.weeklySummaries || [{ summary: "" }];
up.weeklySummaries = req.body.weeklySummaries || [{ summary: '' }];
up.weeklySummariesCount = req.body.weeklySummariesCount || 0;
up.weeklySummaryOption = req.body.weeklySummaryOption;
up.mediaUrl = req.body.mediaUrl || "";
up.collaborationPreference = req.body.collaborationPreference || "";
up.timeZone = req.body.timeZone || "America/Los_Angeles";
up.mediaUrl = req.body.mediaUrl || '';
up.collaborationPreference = req.body.collaborationPreference || '';
up.timeZone = req.body.timeZone || 'America/Los_Angeles';
up.location = req.body.location;
up.permissions = req.body.permissions;
up.bioPosted = req.body.bioPosted || "default";
up.bioPosted = req.body.bioPosted || 'default';
up.isFirstTimelog = true;
up.actualEmail = req.body.actualEmail;

Expand All @@ -244,11 +247,11 @@ const userProfileController = function (UserProfile) {
lastName: up.lastName,
email: up.email,
};
const allUserCache = JSON.parse(cache.getCache("allusers"));
const allUserCache = JSON.parse(cache.getCache('allusers'));
allUserCache.push(userCache);
cache.setCache("allusers", JSON.stringify(allUserCache));
cache.setCache('allusers', JSON.stringify(allUserCache));
})
.catch((error) => res.status(501).send(error));
.catch(error => res.status(501).send(error));
};

const putUserProfile = async function (req, res) {
Expand All @@ -259,12 +262,12 @@ const userProfileController = function (UserProfile) {
|| req.body.requestor.requestorId === userid
)
);
const canEditTeamCode = req.body.requestor.role === "Owner" ||
req.body.requestor.permissions?.frontPermissions.includes("editTeamCode");

const canEditTeamCode = req.body.requestor.role === 'Owner'
|| req.body.requestor.permissions?.frontPermissions.includes('editTeamCode');

if (!isRequestorAuthorized) {
res.status(403).send("You are not authorized to update this user");
res.status(403).send('You are not authorized to update this user');
return;
}

Expand All @@ -276,7 +279,7 @@ const userProfileController = function (UserProfile) {
cache.removeCache(`user-${userid}`);
UserProfile.findById(userid, async (err, record) => {
if (err || !record) {
res.status(404).send("No valid records found");
res.status(404).send('No valid records found');
return;
}
// validate userprofile pic
Expand All @@ -295,8 +298,7 @@ const userProfileController = function (UserProfile) {
: [];
record.jobTitle = req.body.jobTitle;
record.emailPubliclyAccessible = req.body.emailPubliclyAccessible;
record.phoneNumberPubliclyAccessible =
req.body.phoneNumberPubliclyAccessible;
record.phoneNumberPubliclyAccessible = req.body.phoneNumberPubliclyAccessible;

record.profilePic = req.body.profilePic;
record.firstName = req.body.firstName;
Expand All @@ -318,24 +320,24 @@ const userProfileController = function (UserProfile) {
record.isVisible = req.body.isVisible || false;
record.isRehireable = req.body.isRehireable || false;
record.totalIntangibleHrs = req.body.totalIntangibleHrs;
record.bioPosted = req.body.bioPosted || "default";
record.bioPosted = req.body.bioPosted || 'default';
record.isFirstTimelog = req.body.isFirstTimelog;

if(!canEditTeamCode && record.teamCode !== req.body.teamCode){
res.status(403).send("You are not authorized to edit team code.");
if (!canEditTeamCode && record.teamCode !== req.body.teamCode) {
res.status(403).send('You are not authorized to edit team code.');
return;
}

record.teamCode = req.body.teamCode;

// find userData in cache
const isUserInCache = cache.hasCache("allusers");
const isUserInCache = cache.hasCache('allusers');
let allUserData;
let userData;
let userIdx;
if (isUserInCache) {
allUserData = JSON.parse(cache.getCache("allusers"));
userIdx = allUserData.findIndex((users) => users._id === userid);
allUserData = JSON.parse(cache.getCache('allusers'));
userIdx = allUserData.findIndex(users => users._id === userid);
userData = allUserData[userIdx];
}
if (await hasPermission(req.body.requestor, 'putUserProfileImportantInfo')) {
Expand All @@ -350,11 +352,11 @@ const userProfileController = function (UserProfile) {
// If their last update was made today, remove that
const lasti = record.weeklycommittedHoursHistory.length - 1;
const lastChangeDate = moment(
record.weeklycommittedHoursHistory[lasti].dateChanged
record.weeklycommittedHoursHistory[lasti].dateChanged,
);
const now = moment();

if (lastChangeDate.isSame(now, "day")) {
if (lastChangeDate.isSame(now, 'day')) {
record.weeklycommittedHoursHistory.pop();
}

Expand All @@ -367,8 +369,7 @@ const userProfileController = function (UserProfile) {
record.weeklycommittedHoursHistory.push(newEntry);
}

record.missedHours =
req.body.role === "Core Team" ? req.body?.missedHours ?? 0 : 0;
record.missedHours = req.body.role === 'Core Team' ? req.body?.missedHours ?? 0 : 0;
record.adminLinks = req.body.adminLinks;
record.teams = Array.from(new Set(req.body.teams));
record.projects = Array.from(new Set(req.body.projects));
Expand Down Expand Up @@ -400,8 +401,7 @@ const userProfileController = function (UserProfile) {
record.weeklycommittedHoursHistory.push(newEntry);
}
// then also change the first committed history (index 0)
record.weeklycommittedHoursHistory[0].dateChanged =
record.createdDate;
record.weeklycommittedHoursHistory[0].dateChanged = record.createdDate;
}

record.bioPosted = req.body.bioPosted || 'default';
Expand All @@ -416,7 +416,7 @@ const userProfileController = function (UserProfile) {
userData.endDate = record.endDate.toISOString();
}
} else {
record.set("endDate", undefined, { strict: false });
record.set('endDate', undefined, { strict: false });
}
if (isUserInCache) {
userData.role = record.role;
Expand All @@ -438,7 +438,7 @@ const userProfileController = function (UserProfile) {
results.infringements,
results.firstName,
results.lastName,
results.email
results.email,
);
res.status(200).json({
_id: record._id,
Expand All @@ -447,10 +447,10 @@ const userProfileController = function (UserProfile) {
// update alluser cache if we have cache
if (isUserInCache) {
allUserData.splice(userIdx, 1, userData);
cache.setCache("allusers", JSON.stringify(allUserData));
cache.setCache('allusers', JSON.stringify(allUserData));
}
})
.catch((error) => res.status(400).send(error));
.catch(error => res.status(400).send(error));
});
};

Expand Down Expand Up @@ -595,15 +595,14 @@ const userProfileController = function (UserProfile) {
const { userId } = req.params;
const { key, value } = req.body;

if (key === "teamCode") {
const canEditTeamCode = req.body.requestor.role === "Owner" ||
req.body.requestor.permissions?.frontPermissions.includes("editTeamCode");
if (key === 'teamCode') {
const canEditTeamCode = req.body.requestor.role === 'Owner'
|| req.body.requestor.permissions?.frontPermissions.includes('editTeamCode');

if(!canEditTeamCode){
res.status(403).send("You are not authorized to edit team code.");
if (!canEditTeamCode) {
res.status(403).send('You are not authorized to edit team code.');
return;
}

}

// remove user from cache, it should be loaded next time
Expand Down Expand Up @@ -873,7 +872,7 @@ const userProfileController = function (UserProfile) {
const currentRefreshToken = jwt.sign(jwtPayload, JWT_SECRET);
res.status(200).send({ refreshToken: currentRefreshToken });
};

return {
postUserProfile,
getUserProfiles,
Expand Down

0 comments on commit 061243b

Please sign in to comment.