Skip to content

Commit

Permalink
Merge pull request #569 from OneCommunityGlobal/Roberto_Create_Notifi…
Browse files Browse the repository at this point in the history
…cation_For_OwnerAdmin_changes

Roberto - For Dev Branch- Adds email notification for Owner create/reset password
  • Loading branch information
one-community authored Apr 6, 2024
2 parents 5e75b5c + 191a70e commit 543d36a
Showing 1 changed file with 137 additions and 53 deletions.
190 changes: 137 additions & 53 deletions src/controllers/userProfileController.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const { authorizedUserSara, authorizedUserJae } = process.env;
const { hasPermission, canRequestorUpdateUser } = require('../utilities/permissions');
const helper = require('../utilities/permissions');
const escapeRegex = require('../utilities/escapeRegex');
const emailSender = require('../utilities/emailSender');
const config = require('../config');

async function ValidatePassword(req, res) {
Expand Down Expand Up @@ -255,26 +256,65 @@ const userProfileController = function (UserProfile) {
up.isVisible = !['Mentor'].includes(req.body.role);

try {
const createdUserProfile = await up.save();
res.status(200).send({
_id: createdUserProfile._id,

const requestor = await UserProfile.findById(req.body.requestor.requestorId).select('firstName lastName email role').exec();

await up.save().then(() => {
// if connected to dev db just check for Owner roles, else it's main branch so also check admin too
const condition = process.env.dbName === 'hgnData_dev' ? (up.role === 'Owner') : (up.role === 'Owner' || up.role === 'Administrator');
if (condition) {
const subject = `${process.env.dbName !== 'hgnData_dev' ? '*Main Site* -' : ''}New ${up.role} Role Created`;

const emailBody = `<p> Hi Admin! </p>
<p><strong>New Account Details</strong></p>
<p>This email is to inform you that <strong>${up.firstName} ${up.lastName}</strong> has been created as a new ${up.role} account on the Highest Good Network application.</p>
<p><strong>Here are the details for the new ${up.role} account:</strong></p>
<ul>
<li><strong>Name:</strong> ${up.firstName} ${up.lastName}</li>
<li><strong>Email:</strong> <a href="mailto:${up.email}">${up.email}</a></li>
</ul>
<p><strong>Who created this new account?</strong></p>
<ul>
<li><strong>Name:</strong> ${requestor.firstName} ${requestor.lastName}</li>
<li><strong>Email:</strong> <a href="mailto:${requestor.email}">${requestor.email}</a></li>
</ul>
<p>If you have any questions or notice any issues, please investigate further.</p>
<p>Thank you for your attention to this matter.</p>
<p>Sincerely,</p>
<p>The HGN A.I. (and One Community)</p>`;

emailSender('[email protected]', subject, emailBody, null, null);
}
});

// update backend cache if it exists
if (cache.getCache('allusers')) {
const userCache = {
permissions: up.permissions,
isActive: true,
weeklycommittedHours: up.weeklycommittedHours,
createdDate: up.createdDate.toISOString(),
_id: up._id,
role: up.role,
firstName: up.firstName,
lastName: up.lastName,
email: up.email,
};
const allUserCache = JSON.parse(cache.getCache('allusers'));
allUserCache.push(userCache);
cache.setCache('allusers', JSON.stringify(allUserCache));
}

// update backend cache
const userCache = {
permissions: up.permissions,
isActive: true,
weeklycommittedHours: up.weeklycommittedHours,
createdDate: up.createdDate.toISOString(),
res.status(200).send({
_id: up._id,
role: up.role,
firstName: up.firstName,
lastName: up.lastName,
email: up.email,
};
const allUserCache = JSON.parse(cache.getCache('allusers'));
allUserCache.push(userCache);
cache.setCache('allusers', JSON.stringify(allUserCache));
});

} catch (error) {
res.status(501).send(error);
}
Expand Down Expand Up @@ -582,15 +622,20 @@ const userProfileController = function (UserProfile) {
}

cache.removeCache(`user-${userId}`);
const allUserData = JSON.parse(cache.getCache('allusers'));
const userIdx = allUserData.findIndex((users) => users._id === userId);
allUserData.splice(userIdx, 1);
cache.setCache('allusers', JSON.stringify(allUserData));
if (cache.getCache('allusers')) {
const allUserData = JSON.parse(cache.getCache('allusers'));
const userIdx = allUserData.findIndex((users) => users._id === userId);
allUserData.splice(userIdx, 1);
cache.setCache('allusers', JSON.stringify(allUserData));
}

await UserProfile.deleteOne({
_id: userId,
}).then(() => {
res.status(200).send({ message: 'Executed Successfully' });
}).catch((err) => {
res.status(500).send(err);
});
res.status(200).send({ message: 'Executed Successfully' });
};

const getUserById = function (req, res) {
Expand Down Expand Up @@ -679,11 +724,9 @@ const userProfileController = function (UserProfile) {
// remove user from cache, it should be loaded next time
cache.removeCache(`user-${userId}`);
if (!key || value === undefined) {
// eslint-disable-next-line consistent-return
return res.status(400).send({ error: 'Missing property or value' });
}

// eslint-disable-next-line consistent-return
return UserProfile.findById(userId)
.then((user) => {
user.set({
Expand Down Expand Up @@ -718,15 +761,8 @@ const userProfileController = function (UserProfile) {
// Check if the requestor has the permission to update passwords.
const hasUpdatePasswordPermission = await hasPermission(requestor, 'updatePassword');

// If the requestor is updating their own password, allow them to proceed.
if (userId === requestor.requestorId) {
console.log('Requestor is updating their own password');
}
// Else if they're updating someone else's password, they need the 'updatePassword' permission.
else if (!hasUpdatePasswordPermission) {
console.log(
"Requestor is trying to update someone else's password but lacks the 'updatePassword' permission",
);
// if they're updating someone else's password, they need the 'updatePassword' permission.
if (!hasUpdatePasswordPermission) {
return res.status(403).send({
error: "You are unauthorized to update this user's password",
});
Expand Down Expand Up @@ -895,28 +931,76 @@ const userProfileController = function (UserProfile) {
});
};

const resetPassword = function (req, res) {
ValidatePassword(req);
const resetPassword = async function (req, res) {
try {
ValidatePassword(req);

UserProfile.findById(req.params.userId, 'password')
.then((user) => {
user.set({
password: req.body.newpassword,
});
user
.save()
.then(() => {
res.status(200).send({
message: ' password Reset',
});
})
.catch((error) => {
res.status(500).send(error);
});
})
.catch((error) => {
res.status(500).send(error);
const requestor = await UserProfile.findById(req.body.requestor.requestorId).select('firstName lastName email role').exec();

if (!requestor) {
res.status(404).send({ error: 'Requestor not found' });
return;
}

const user = await UserProfile.findById(req.params.userId).select('firstName lastName email role').exec();

if (!user) {
res.status(404).send({ error: 'User not found' });
return;
}

if (!await hasPermission(requestor, 'putUserProfileImportantInfo')) {
res.status(403).send('You are not authorized to reset this users password');
return;
}

if (user.role === 'Owner' && !await hasPermission(requestor, 'addDeleteEditOwners')) {
res.status(403).send('You are not authorized to reset this user password');
return;
}

user.password = req.body.newpassword;

await user.save();

const condition = process.env.dbName === 'hgnData_dev' ? (user.role === 'Owner') : (user.role === 'Owner' || user.role === 'Administrator');
if (condition) {
const subject = `${process.env.dbName !== 'hgnData_dev' ? '*Main Site* -' : ''}${user.role} Password Reset Notification`;
const emailBody = `<p>Hi Admin! </p>
<p><strong>Account Details</strong></p>
<p>This email is to inform you that a password reset has been executed for an ${user.role} account:</p>
<ul>
<li><strong>Name:</strong> ${user.firstName} ${user.lastName}</li>
<li><strong>Email:</strong> <a href="mailto:${user.email}">${user.email}</a></li>
</ul>
<p><strong>Account that reset the ${user.role}'s password</strong></p>
<p>The password reset was made by:</p>
<ul>
<li><strong>Name:</strong> ${requestor.firstName} ${requestor.lastName}</li>
<li><strong>Email:</strong> <a href="mailto:${requestor.email}">${requestor.email}</a></li>
</ul>
<p>If you have any questions or need to verify this password reset, please investigate further.</p>
<p>Thank you for your attention to this matter.</p>
<p>Sincerely,</p>
<p>The HGN A.I. (and One Community)</p>
`;

emailSender('[email protected]', subject, emailBody, null, null);
}

res.status(200).send({
message: 'Password Reset',
});
} catch (error) {
res.status(500).send(error);
}
};

const getAllUsersWithFacebookLink = function (req, res) {
Expand Down

0 comments on commit 543d36a

Please sign in to comment.