diff --git a/src/controllers/badgeController.js b/src/controllers/badgeController.js index 366c9323e..fc2a5c81b 100644 --- a/src/controllers/badgeController.js +++ b/src/controllers/badgeController.js @@ -49,7 +49,7 @@ const badgeController = function (Badge) { record.badgeCollection = req.body.badgeCollection; if (cache.hasCache(`user-${userToBeAssigned}`)) cache.removeCache(`user-${userToBeAssigned}`); - + record.save() .then(results => res.status(201).send(results._id)) .catch(errors => res.status(500).send(errors)); diff --git a/src/controllers/dashBoardController.js b/src/controllers/dashBoardController.js index b1b62f9ae..db2cfadc1 100644 --- a/src/controllers/dashBoardController.js +++ b/src/controllers/dashBoardController.js @@ -1,8 +1,8 @@ -const path = require("path"); -const fs = require("fs/promises"); -const mongoose = require("mongoose"); -const dashboardhelper = require("../helpers/dashboardhelper")(); -const emailSender = require("../utilities/emailSender"); +const path = require('path'); +const fs = require('fs/promises'); +const mongoose = require('mongoose'); +const dashboardhelper = require('../helpers/dashboardhelper')(); +const emailSender = require('../utilities/emailSender'); const dashboardcontroller = function () { const dashboarddata = function (req, res) { @@ -20,13 +20,13 @@ const dashboardcontroller = function () { const laborthismonth = dashboardhelper.laborthismonth( userId, req.params.fromDate, - req.params.toDate + req.params.toDate, ); laborthismonth.then((results) => { if (!results || results.length === 0) { const emptyresult = [ { - projectName: "", + projectName: '', timeSpent_hrs: 0, }, ]; @@ -42,7 +42,7 @@ const dashboardcontroller = function () { const laborthisweek = dashboardhelper.laborthisweek( userId, req.params.fromDate, - req.params.toDate + req.params.toDate, ); laborthisweek.then((results) => { res.send(results).status(200); @@ -63,7 +63,7 @@ const dashboardcontroller = function () { }); } }) - .catch((error) => res.status(400).send(error)); + .catch(error => res.status(400).send(error)); }; const orgData = function (req, res) { @@ -73,7 +73,7 @@ const dashboardcontroller = function () { .then((results) => { res.status(200).send(results[0]); }) - .catch((error) => res.status(400).send(error)); + .catch(error => res.status(400).send(error)); }; const getBugReportEmailBody = function ( @@ -85,7 +85,7 @@ const dashboardcontroller = function () { expected, actual, visual, - severity + severity, ) { const text = `New Bug Report From ${firstName} ${lastName}:
[Feature Name] Bug Title:
@@ -130,32 +130,32 @@ const dashboardcontroller = function () { expected, actual, visual, - severity + severity, ); try { emailSender( - "onecommunityglobal@gmail.com", + 'onecommunityglobal@gmail.com', `Bug Rport from ${firstName} ${lastName}`, emailBody, - email + email, ); - res.status(200).send("Success"); + res.status(200).send('Success'); } catch { - res.status(500).send("Failed"); + res.status(500).send('Failed'); } }; const suggestionData = { suggestion: [ - "Identify and remedy poor client and/or user service experiences", - "Identify bright spots and enhance positive service experiences", - "Make fundamental changes to our programs and/or operations", - "Inform the development of new programs/projects", - "Identify where we are less inclusive or equitable across demographic groups", - "Strengthen relationships with the people we serve", + 'Identify and remedy poor client and/or user service experiences', + 'Identify bright spots and enhance positive service experiences', + 'Make fundamental changes to our programs and/or operations', + 'Inform the development of new programs/projects', + 'Identify where we are less inclusive or equitable across demographic groups', + 'Strengthen relationships with the people we serve', "Understand people's needs and how we can help them achieve their goals", - "Other", + 'Other', ], field: [], }; @@ -164,8 +164,8 @@ const dashboardcontroller = function () { let fieldaaray = []; if (suggestionData.field.length) { fieldaaray = suggestionData.field.map( - (item) => `${item}
-${args[3][item]}
` + item => `${item}
+${args[3][item]}
`, ); } const text = `New Suggestion From ${args[3].firstName} ${ @@ -178,7 +178,7 @@ const dashboardcontroller = function () {${args[0]}
⚹ Suggestion:${args[1]}
- ${fieldaaray.length > 0 ? fieldaaray : ""} + ${fieldaaray.length > 0 ? fieldaaray : ''} ⚹ Name of Suggester:${args[3].firstName} ${args[3].lastName}
⚹ Email of Suggester: @@ -193,27 +193,29 @@ const dashboardcontroller = function () { // send suggestion email const sendMakeSuggestion = async (req, res) => { - const { suggestioncate, suggestion, confirm, email, ...rest } = req.body; + const { + suggestioncate, suggestion, confirm, email, ...rest +} = req.body; const emailBody = await getsuggestionEmailBody( suggestioncate, suggestion, confirm, rest, - email + email, ); try { emailSender( - "onecommunityglobal@gmail.com", - "A new suggestion", + 'onecommunityglobal@gmail.com', + 'A new suggestion', emailBody, null, null, email, null ); - res.status(200).send("Success"); + res.status(200).send('Success'); } catch { - res.status(500).send("Failed"); + res.status(500).send('Failed'); } }; @@ -222,40 +224,40 @@ const dashboardcontroller = function () { if (suggestionData) { res.status(200).send(suggestionData); } else { - res.status(404).send("Suggestion data not found."); + res.status(404).send('Suggestion data not found.'); } } catch (error) { - console.error("Error getting suggestion data:", error); - res.status(500).send("Internal Server Error"); + console.error('Error getting suggestion data:', error); + res.status(500).send('Internal Server Error'); } }; const editSuggestionOption = async (req, res) => { try { if (req.body.suggestion) { - if (req.body.action === "add") { + if (req.body.action === 'add') { suggestionData.suggestion.unshift(req.body.newField); } - if (req.body.action === "delete") { + if (req.body.action === 'delete') { suggestionData.suggestion = suggestionData.suggestion.filter( - (item, index) => index + 1 !== +req.body.newField + (item, index) => index + 1 !== +req.body.newField, ); } } else { - if (req.body.action === "add") { + if (req.body.action === 'add') { suggestionData.field.unshift(req.body.newField); } - if (req.body.action === "delete") { + if (req.body.action === 'delete') { suggestionData.field = suggestionData.field.filter( - (item) => item !== req.body.newField + item => item !== req.body.newField, ); } } - res.status(200).send("success"); + res.status(200).send('success'); } catch (error) { - console.error("Error editing suggestion option:", error); - res.status(500).send("Internal Server Error"); + console.error('Error editing suggestion option:', error); + res.status(500).send('Internal Server Error'); } }; diff --git a/src/controllers/isEmailExistsController.js b/src/controllers/isEmailExistsController.js index 2c41efc33..f6009a3c5 100644 --- a/src/controllers/isEmailExistsController.js +++ b/src/controllers/isEmailExistsController.js @@ -1,25 +1,23 @@ const UserProfile = require('../models/userProfile'); const isEmailExistsController = function () { - const isEmailExists = async function (req, res) { - - try { - const userProfile = await UserProfile.findOne({ email: req.params.email }).lean().exec() + try { + const userProfile = await UserProfile.findOne({ email: req.params.email }).lean().exec(); if (userProfile) { - res.status(200).send(`Email, ${userProfile.email}, found.`) + res.status(200).send(`Email, ${userProfile.email}, found.`); } else { - res.status(403).send(`Email, ${req.params.email}, not found.`) + res.status(403).send(`Email, ${req.params.email}, not found.`); } } catch (err) { - console.log(err) + console.log(err); } - } + }; return { - isEmailExists - } -} + isEmailExists, + }; +}; -module.exports = isEmailExistsController +module.exports = isEmailExistsController; diff --git a/src/controllers/profileInitialSetupController.js b/src/controllers/profileInitialSetupController.js index 2e64b5e98..315ed01bb 100644 --- a/src/controllers/profileInitialSetupController.js +++ b/src/controllers/profileInitialSetupController.js @@ -1,9 +1,9 @@ -const mongoose = require("mongoose"); -const { v4: uuidv4 } = require("uuid"); -const moment = require("moment-timezone"); -const jwt = require("jsonwebtoken"); -const emailSender = require("../utilities/emailSender"); -const config = require("../config"); +const mongoose = require('mongoose'); +const { v4: uuidv4 } = require('uuid'); +const moment = require('moment-timezone'); +const jwt = require('jsonwebtoken'); +const emailSender = require('../utilities/emailSender'); +const config = require('../config'); const cache = require('../utilities/nodeCache')(); // returns the email body that includes the setup link for the recipient. @@ -96,7 +96,7 @@ const sendEmailWithAcknowledgment = (email, subject, message) => { const profileInitialSetupController = function ( ProfileInitialSetupToken, userProfile, - Project + Project, ) { const { JWT_SECRET } = config; @@ -108,16 +108,16 @@ const profileInitialSetupController = function ( - Generates a link using the token and emails it to the recipient. */ const getSetupToken = async (req, res) => { - let { email, baseUrl,weeklyCommittedHours } = req.body; + let { email, baseUrl, weeklyCommittedHours } = req.body; email = email.toLowerCase(); const token = uuidv4(); - const expiration = moment().tz("America/Los_Angeles").add(1, "week"); + const expiration = moment().tz('America/Los_Angeles').add(1, 'week'); try { const existingEmail = await userProfile.findOne({ - email: email, + email, }); if (existingEmail) { - res.status(400).send("email already in use"); + res.status(400).send('email already in use'); } else { await ProfileInitialSetupToken.findOneAndDelete({ email }); @@ -151,7 +151,7 @@ const profileInitialSetupController = function ( */ const validateSetupToken = async (req, res) => { const { token } = req.body; - const currentMoment = moment.tz("America/Los_Angeles"); + const currentMoment = moment.tz('America/Los_Angeles'); try { const foundToken = await ProfileInitialSetupToken.findOne({ token }); @@ -161,10 +161,10 @@ const profileInitialSetupController = function ( if (expirationMoment.isAfter(currentMoment)) { res.status(200).send(foundToken); } else { - res.status(400).send("Invalid token"); + res.status(400).send('Invalid token'); } } else { - res.status(404).send("Token not found"); + res.status(404).send('Token not found'); } } catch (error) { res.status(500).send(`Error finding token: ${error}`); @@ -182,31 +182,30 @@ const profileInitialSetupController = function ( */ const setUpNewUser = async (req, res) => { const { token } = req.body; - const currentMoment = moment.tz("America/Los_Angeles"); + const currentMoment = moment.tz('America/Los_Angeles'); try { const foundToken = await ProfileInitialSetupToken.findOne({ token }); const existingEmail = await userProfile.findOne({ email: foundToken.email, }); if (existingEmail) { - res.status(400).send("email already in use"); - } else { - if (foundToken) { + res.status(400).send('email already in use'); + } else if (foundToken) { const expirationMoment = moment(foundToken.expiration); if (expirationMoment.isAfter(currentMoment)) { const defaultProject = await Project.findOne({ - projectName: "Orientation and Initial Setup", + projectName: 'Orientation and Initial Setup', }); const newUser = new userProfile(); newUser.password = req.body.password; - newUser.role = "Volunteer"; + newUser.role = 'Volunteer'; newUser.firstName = req.body.firstName; newUser.lastName = req.body.lastName; newUser.jobTitle = req.body.jobTitle; newUser.phoneNumber = req.body.phoneNumber; - newUser.bio = ""; + newUser.bio = ''; newUser.weeklycommittedHours = foundToken.weeklyCommittedHours; newUser.weeklycommittedHoursHistory = [ { @@ -220,32 +219,31 @@ const profileInitialSetupController = function ( newUser.projects = Array.from(new Set([defaultProject])); newUser.createdDate = Date.now(); newUser.email = req.body.email; - newUser.weeklySummaries = [{ summary: "" }]; + newUser.weeklySummaries = [{ summary: '' }]; newUser.weeklySummariesCount = 0; - newUser.weeklySummaryOption = "Required"; - newUser.mediaUrl = ""; + newUser.weeklySummaryOption = 'Required'; + newUser.mediaUrl = ''; newUser.collaborationPreference = req.body.collaborationPreference; - newUser.timeZone = req.body.timeZone || "America/Los_Angeles"; + newUser.timeZone = req.body.timeZone || 'America/Los_Angeles'; newUser.location = req.body.location; newUser.permissions = { frontPermissions: [], - backPermissions: [] - } - newUser.bioPosted = "default"; + backPermissions: [], + }; + newUser.bioPosted = 'default'; newUser.privacySettings.email = req.body.privacySettings.email; - newUser.privacySettings.phoneNumber = - req.body.privacySettings.phoneNumber; - newUser.teamCode = ""; + newUser.privacySettings.phoneNumber = req.body.privacySettings.phoneNumber; + newUser.teamCode = ''; newUser.isFirstTimelog = true; const savedUser = await newUser.save(); emailSender( - process.env.MANAGER_EMAIL || "jae@onecommunityglobal.org", // "jae@onecommunityglobal.org" + process.env.MANAGER_EMAIL || 'jae@onecommunityglobal.org', // "jae@onecommunityglobal.org" `NEW USER REGISTERED: ${savedUser.firstName} ${savedUser.lastName}`, informManagerMessage(savedUser), null, - null + null, ); await ProfileInitialSetupToken.findByIdAndDelete(foundToken._id); @@ -255,14 +253,14 @@ const profileInitialSetupController = function ( permissions: savedUser.permissions, expiryTimestamp: moment().add( config.TOKEN.Lifetime, - config.TOKEN.Units + config.TOKEN.Units, ), }; const token = jwt.sign(jwtPayload, JWT_SECRET); res.send({ token }).status(200); - + const NewUserCache = { permissions: savedUser.permissions, isActive: true, @@ -275,18 +273,15 @@ const profileInitialSetupController = function ( email: savedUser.email, }; - const allUserCache = JSON.parse(cache.getCache("allusers")); + const allUserCache = JSON.parse(cache.getCache('allusers')); allUserCache.push(NewUserCache); - cache.setCache("allusers", JSON.stringify(allUserCache)); - - + cache.setCache('allusers', JSON.stringify(allUserCache)); } else { - res.status(400).send("Token is expired"); + res.status(400).send('Token is expired'); } } else { - res.status(400).send("Invalid token"); + res.status(400).send('Invalid token'); } - } } catch (error) { res.status(500).send(`Error: ${error}`); } @@ -298,17 +293,15 @@ const profileInitialSetupController = function ( - sends the API Key as response */ const getTimeZoneAPIKeyByToken = async (req, res) => { - const token = req.body.token; + const { token } = req.body; const premiumKey = process.env.TIMEZONE_PREMIUM_KEY; const foundToken = await ProfileInitialSetupToken.findOne({ token }); if (foundToken) { res.status(200).send({ userAPIKey: premiumKey }); - return; } else { - res.status(403).send("Unauthorized Request"); - return; + res.status(403).send('Unauthorized Request'); } }; diff --git a/src/controllers/projectController.js b/src/controllers/projectController.js index a88378985..9e39ffa77 100644 --- a/src/controllers/projectController.js +++ b/src/controllers/projectController.js @@ -122,7 +122,7 @@ const projectController = function (Project) { }; const assignProjectToUsers = async function (req, res) { - // verify requestor is administrator, projectId is passed in request params and is valid mongoose objectid, and request body contains an array of users + // verify requestor is administrator or has necessary permissions, projectId is passed in request params and is valid mongoose objectid, and request body contains an array of users if (!await hasPermission(req.body.requestor, 'assignProjectToUsers')) { res.status(403).send({ error: 'You are not authorized to perform this operation' }); diff --git a/src/controllers/teamController.js b/src/controllers/teamController.js index b204875a5..f9f82a2b4 100644 --- a/src/controllers/teamController.js +++ b/src/controllers/teamController.js @@ -18,14 +18,18 @@ const teamcontroller = function (Team) { .catch(error => res.send(error).status(404)); }; const postTeam = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'postTeam')) { + // verify if the requestor has the necessary permissions + + if (!await hasPermission(req.body.requestor, 'postTeam') + // && !await hasIndividualPermission(req.body.requestor.requestorId, 'seeTeamsManagement') + && !await hasPermission(req.body.requestor, 'seeTeamsManagementTab')) { res.status(403).send({ error: 'You are not authorized to create teams.' }); return; } const team = new Team(); team.teamName = req.body.teamName; - team.isACtive = req.body.isActive; + team.isActive = req.body.isActive; team.createdDatetime = Date.now(); team.modifiedDatetime = Date.now(); @@ -58,7 +62,11 @@ const teamcontroller = function (Team) { }); }; const putTeam = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'putTeam')) { + // verify if the requestor has the necessary permissions + // console.log(req.body); + if (!await hasPermission(req.body.requestor, 'putTeam') + // && !await hasIndividualPermission(req.body.requestor.requestorId, 'seeTeamsManagement') + && !await hasPermission(req.body.requestor, 'seeTeamsManagementTab')) { res.status(403).send('You are not authorized to make changes in the teams.'); return; } @@ -93,9 +101,11 @@ const teamcontroller = function (Team) { }; const assignTeamToUsers = async function (req, res) { - // verify requestor is administrator, teamId is passed in request params and is valid mongoose objectid, and request body contains an array of users + // verify requestor is administrator or has the necessary permissions, teamId is passed in request params and is valid mongoose objectid, and request body contains an array of users - if (!await hasPermission(req.body.requestor, 'assignTeamToUsers')) { + if (!await hasPermission(req.body.requestor, 'assignTeamToUsers') + // && !await hasIndividualPermission(req.body.requestor.requestorId, 'seeTeamsManagement') + && !await hasPermission(req.body.requestor, 'seeTeamsManagementTab')) { res.status(403).send({ error: 'You are not authorized to perform this operation' }); return; } diff --git a/src/controllers/userProfileController.js b/src/controllers/userProfileController.js index 737b1bc6a..95a5ec0bc 100644 --- a/src/controllers/userProfileController.js +++ b/src/controllers/userProfileController.js @@ -59,27 +59,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) { @@ -93,14 +91,14 @@ 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); - } + }, ); }; @@ -118,15 +116,15 @@ 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; } @@ -145,8 +143,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; } @@ -160,8 +158,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; } @@ -188,15 +186,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.save() @@ -218,11 +216,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) { @@ -233,12 +231,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; } @@ -250,7 +248,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 @@ -269,8 +267,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; @@ -292,25 +289,25 @@ 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; record.teamCode = req.body.teamCode; - 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')) { @@ -325,11 +322,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(); } @@ -342,8 +339,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)); @@ -375,8 +371,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'; @@ -391,7 +386,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; @@ -413,7 +408,7 @@ const userProfileController = function (UserProfile) { results.infringements, results.firstName, results.lastName, - results.email + results.email, ); res.status(200).json({ _id: record._id, @@ -422,10 +417,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)); }); }; @@ -570,15 +565,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 diff --git a/src/controllers/wbsController.js b/src/controllers/wbsController.js index fa7f4427f..1776d1c32 100644 --- a/src/controllers/wbsController.js +++ b/src/controllers/wbsController.js @@ -1,4 +1,4 @@ -const { hasPermission } = require('../utilities/permissions'); +const { hasPermission, hasIndividualPermission } = require('../utilities/permissions'); const wbsController = function (WBS) { const getAllWBS = function (req, res) { @@ -11,7 +11,11 @@ const wbsController = function (WBS) { }; const postWBS = async function (req, res) { - if (!await hasPermission(req.body.requestor, 'postWbs')) { + // verify if the requestor has the necessary permissions + + if (!await hasPermission(req.body.requestor.role, 'postWbs') + // && !await hasIndividualPermission(req.body.requestor.requestorId, 'seeProjectManagement') + && !await hasIndividualPermission(req.body.requestor.requestorId, 'seeProjectManagementTab')) { res.status(403).send({ error: 'You are not authorized to create new projects.' }); return; } diff --git a/src/helpers/dashboardhelper.js b/src/helpers/dashboardhelper.js index 34d464583..fe2007281 100644 --- a/src/helpers/dashboardhelper.js +++ b/src/helpers/dashboardhelper.js @@ -192,7 +192,7 @@ const dashboardhelper = function () { // leaderboard user roles hierarchy $or: [ { - role: { $in: ['Owner', 'Core Team'] }, + role: { $in: ['Owner', 'Core Team'] }, }, { $and: [ @@ -200,7 +200,7 @@ const dashboardhelper = function () { role: 'Administrator', }, { 'persondata.0.role': { $nin: ['Owner', 'Administrator'] } }, - ] + ], }, { $and: [ diff --git a/src/helpers/reporthelper.js b/src/helpers/reporthelper.js index 0c2a8104d..3826aa8ed 100644 --- a/src/helpers/reporthelper.js +++ b/src/helpers/reporthelper.js @@ -1,5 +1,5 @@ -const moment = require("moment-timezone"); -const userProfile = require("../models/userProfile"); +const moment = require('moment-timezone'); +const userProfile = require('../models/userProfile'); /** * @@ -8,9 +8,9 @@ const userProfile = require("../models/userProfile"); * @returns The absolute value of the difference in weeks between the two input dates. */ const absoluteDifferenceInWeeks = (dateOfWork, pstEnd) => { - dateOfWork = moment(dateOfWork).endOf("week"); - pstEnd = moment(pstEnd).tz("America/Los_Angeles").endOf("week"); - return Math.abs(dateOfWork.diff(pstEnd, "weeks")); + dateOfWork = moment(dateOfWork).endOf('week'); + pstEnd = moment(pstEnd).tz('America/Los_Angeles').endOf('week'); + return Math.abs(dateOfWork.diff(pstEnd, 'weeks')); }; const reporthelper = function () { @@ -23,14 +23,14 @@ const reporthelper = function () { */ const weeklySummaries = async (startWeekIndex, endWeekIndex) => { const pstStart = moment() - .tz("America/Los_Angeles") - .startOf("week") - .subtract(startWeekIndex, "week") + .tz('America/Los_Angeles') + .startOf('week') + .subtract(startWeekIndex, 'week') .toDate(); const pstEnd = moment() - .tz("America/Los_Angeles") - .endOf("week") - .subtract(endWeekIndex, "week") + .tz('America/Los_Angeles') + .endOf('week') + .subtract(endWeekIndex, 'week') .toDate(); const results = await userProfile.aggregate([ @@ -39,33 +39,33 @@ const reporthelper = function () { }, { $lookup: { - from: "timeEntries", - localField: "_id", - foreignField: "personId", - as: "timeEntries", + from: 'timeEntries', + localField: '_id', + foreignField: 'personId', + as: 'timeEntries', }, }, { - $set: { totalTangibleHrs: { $objectToArray: "$hoursByCategory" } }, + $set: { totalTangibleHrs: { $objectToArray: '$hoursByCategory' } }, }, { $project: { timeEntries: { $filter: { - input: "$timeEntries", - as: "timeEntry", + input: '$timeEntries', + as: 'timeEntry', cond: { $and: [ { $gte: [ - "$$timeEntry.dateOfWork", - moment(pstStart).format("YYYY-MM-DD"), + '$$timeEntry.dateOfWork', + moment(pstStart).format('YYYY-MM-DD'), ], }, { $lte: [ - "$$timeEntry.dateOfWork", - moment(pstEnd).format("YYYY-MM-DD"), + '$$timeEntry.dateOfWork', + moment(pstEnd).format('YYYY-MM-DD'), ], }, ], @@ -86,22 +86,22 @@ const reporthelper = function () { bioPosted: 1, badgeCollection: { $filter: { - input: "$badgeCollection", - as: "badge", + input: '$badgeCollection', + as: 'badge', cond: { $or: [ { $and: [ { $gte: [ - "$$badge.earnedDate", - moment(pstStart).format("YYYY-MM-DD"), + '$$badge.earnedDate', + moment(pstStart).format('YYYY-MM-DD'), ], }, { $lte: [ - "$$badge.earnedDate", - moment(pstEnd).format("YYYY-MM-DD"), + '$$badge.earnedDate', + moment(pstEnd).format('YYYY-MM-DD'), ], }, ], @@ -109,10 +109,10 @@ const reporthelper = function () { { $and: [ { - $gte: ["$$badge.lastModified", pstStart], + $gte: ['$$badge.lastModified', pstStart], }, { - $lte: ["$$badge.lastModified", pstEnd], + $lte: ['$$badge.lastModified', pstEnd], }, ], }, @@ -126,15 +126,15 @@ const reporthelper = function () { role: 1, weeklySummaries: { $filter: { - input: "$weeklySummaries", - as: "ws", + input: '$weeklySummaries', + as: 'ws', cond: { $and: [ { - $gte: ["$$ws.dueDate", pstStart], + $gte: ['$$ws.dueDate', pstStart], }, { - $lte: ["$$ws.dueDate", pstEnd], + $lte: ['$$ws.dueDate', pstEnd], }, ], }, @@ -142,13 +142,13 @@ const reporthelper = function () { }, weeklySummariesCount: 1, isTangible: 1, - totalTangibleHrs: { $sum: "$totalTangibleHrs.v" }, + totalTangibleHrs: { $sum: '$totalTangibleHrs.v' }, daysInTeam: { $dateDiff: { - startDate: "$createdDate", + startDate: '$createdDate', endDate: new Date(), - unit: "day", - timezone: "America/Los_Angeles", + unit: 'day', + timezone: 'America/Los_Angeles', }, }, }, @@ -162,8 +162,8 @@ const reporthelper = function () { result.timeEntries.forEach((entry) => { const index = absoluteDifferenceInWeeks(entry.dateOfWork, pstEnd); if ( - result.totalSeconds[index] === undefined || - result.totalSeconds[index] === null + result.totalSeconds[index] === undefined + || result.totalSeconds[index] === null ) { result.totalSeconds[index] = 0; } @@ -189,16 +189,16 @@ const reporthelper = function () { */ const doesDateBelongToWeek = function (dueDate, weekIndex) { const pstStartOfWeek = moment() - .tz("America/Los_Angeles") - .startOf("week") - .subtract(weekIndex, "week"); + .tz('America/Los_Angeles') + .startOf('week') + .subtract(weekIndex, 'week'); const pstEndOfWeek = moment() - .tz("America/Los_Angeles") - .endOf("week") - .subtract(weekIndex, "week"); + .tz('America/Los_Angeles') + .endOf('week') + .subtract(weekIndex, 'week'); const fromDate = moment(pstStartOfWeek).toDate(); const toDate = moment(pstEndOfWeek).toDate(); - return moment(dueDate).isBetween(fromDate, toDate, undefined, "[]"); + return moment(dueDate).isBetween(fromDate, toDate, undefined, '[]'); }; /** diff --git a/src/helpers/taskHelper.js b/src/helpers/taskHelper.js index a94aaee94..f59dedcbc 100644 --- a/src/helpers/taskHelper.js +++ b/src/helpers/taskHelper.js @@ -43,7 +43,7 @@ const taskHelper = function () { // dashboard tasks user roles hierarchy $or: [ { - role: { $in: ['Owner', 'Core Team'] }, + role: { $in: ['Owner', 'Core Team'] }, }, { $and: [ @@ -51,7 +51,7 @@ const taskHelper = function () { role: 'Administrator', }, { 'persondata.0.role': { $nin: ['Owner', 'Administrator'] } }, - ] + ], }, { $and: [ diff --git a/src/helpers/userHelper.js b/src/helpers/userHelper.js index c75dd7b45..cca8715cf 100644 --- a/src/helpers/userHelper.js +++ b/src/helpers/userHelper.js @@ -1,28 +1,28 @@ /* eslint-disable no-continue */ /* eslint-disable no-await-in-loop */ -const mongoose = require("mongoose"); -const moment = require("moment-timezone"); -const _ = require("lodash"); -const userProfile = require("../models/userProfile"); -const timeEntries = require("../models/timeentry"); -const badge = require("../models/badge"); -const myTeam = require("./helperModels/myTeam"); -const dashboardHelper = require("./dashboardhelper")(); -const reportHelper = require("./reporthelper")(); -const emailSender = require("../utilities/emailSender"); -const logger = require("../startup/logger"); -const hasPermission = require("../utilities/permissions"); -const Reason = require("../models/reason"); -const token = require("../models/profileInitialSetupToken") +const mongoose = require('mongoose'); +const moment = require('moment-timezone'); +const _ = require('lodash'); +const userProfile = require('../models/userProfile'); +const timeEntries = require('../models/timeentry'); +const badge = require('../models/badge'); +const myTeam = require('./helperModels/myTeam'); +const dashboardHelper = require('./dashboardhelper')(); +const reportHelper = require('./reporthelper')(); +const emailSender = require('../utilities/emailSender'); +const logger = require('../startup/logger'); +const hasPermission = require('../utilities/permissions'); +const Reason = require('../models/reason'); +const token = require('../models/profileInitialSetupToken'); const userHelper = function () { const getTeamMembers = function (user) { const userId = mongoose.Types.ObjectId(user._id); // var teamid = userdetails.teamId; return myTeam.findById(userId).select({ - "myTeam._id": 0, - "myTeam.role": 0, - "myTeam.fullName": 0, + 'myTeam._id': 0, + 'myTeam.role': 0, + 'myTeam.fullName': 0, _id: 0, }); }; @@ -46,40 +46,39 @@ const userHelper = function () { const getUserName = async function (userId) { const userid = mongoose.Types.ObjectId(userId); - return userProfile.findById(userid, "firstName lastName"); + return userProfile.findById(userid, 'firstName lastName'); }; const validateProfilePic = function (profilePic) { - const picParts = profilePic.split("base64"); + const picParts = profilePic.split('base64'); let result = true; const errors = []; if (picParts.length < 2) { return { result: false, - errors: "Invalid image" + errors: 'Invalid image', }; } // validate size const imageSize = picParts[1].length; - const sizeInBytes = - (4 * Math.ceil(imageSize / 3) * 0.5624896334383812) / 1024; + const sizeInBytes = (4 * Math.ceil(imageSize / 3) * 0.5624896334383812) / 1024; if (sizeInBytes > 50) { - errors.push("Image size should not exceed 50KB"); + errors.push('Image size should not exceed 50KB'); result = false; } - const imageType = picParts[0].split("/")[1]; - if (imageType !== "jpeg;" && imageType !== "png;") { - errors.push("Image type shoud be either jpeg or png."); + const imageType = picParts[0].split('/')[1]; + if (imageType !== 'jpeg;' && imageType !== 'png;') { + errors.push('Image type shoud be either jpeg or png.'); result = false; } return { result, - errors + errors, }; }; @@ -88,7 +87,7 @@ const userHelper = function () { lastName, infringement, totalInfringements, - timeRemaining + timeRemaining, ) { let final_paragraph = ''; @@ -125,11 +124,11 @@ const userHelper = function () { */ const emailWeeklySummariesForAllUsers = async (weekIndex = 1) => { const currentFormattedDate = moment() - .tz("America/Los_Angeles") + .tz('America/Los_Angeles') .format(); logger.logInfo( - `Job for emailing all users' weekly summaries starting at ${currentFormattedDate}` + `Job for emailing all users' weekly summaries starting at ${currentFormattedDate}`, ); const emails = []; @@ -137,13 +136,11 @@ const userHelper = function () { try { const results = await reportHelper.weeklySummaries(weekIndex, weekIndex); - let emailBody = "Total Valid Weekly Summaries: ${weeklySummariesCount}
` - : `Total Valid Weekly Summaries: ${weeklySummariesCount || - "No valid submissions yet!"}
` + : `Total Valid Weekly Summaries: ${weeklySummariesCount + || 'No valid submissions yet!'}
` } ${hoursLogged >= weeklycommittedHours ? `Hours logged: ${hoursLogged.toFixed(2)} / ${weeklycommittedHours}
` : `Hours logged: ${hoursLogged.toFixed( - 2 + 2, )} / ${weeklycommittedHours}
` } ${weeklySummaryMessage} @@ -236,10 +233,8 @@ const userHelper = function () { // Necessary because our version of node is outdated // and doesn't have String.prototype.replaceAll let emailString = [...new Set(emails)].toString(); - while (emailString.includes(",")) - emailString = emailString.replace(",", "\n"); - while (emailString.includes("\n")) - emailString = emailString.replace("\n", ", "); + while (emailString.includes(',')) emailString = emailString.replace(',', '\n'); + while (emailString.includes('\n')) emailString = emailString.replace('\n', ', '); emailBody += `\n