diff --git a/src/controllers/permissionChangeLogsController.js b/src/controllers/permissionChangeLogsController.js index 33ddb5d72..36e8486d4 100644 --- a/src/controllers/permissionChangeLogsController.js +++ b/src/controllers/permissionChangeLogsController.js @@ -1,6 +1,6 @@ const UserProfile = require('../models/userProfile'); -const permissionChangeLogController = function (PermissionChangeLog) { +const permissionChangeLogController = function (PermissionChangeLog,userPermissionChangeLog) { const getPermissionChangeLogs = async function (req, res) { try { const userProfile = await UserProfile.findOne({ _id: req.params.userId }).exec(); @@ -9,8 +9,24 @@ const permissionChangeLogController = function (PermissionChangeLog) { if (userProfile.role !== 'Owner') { res.status(204).send([]); } else { - const changeLogs = await PermissionChangeLog.find({}); - res.status(200).send(changeLogs); + const userChangeLogs = await userPermissionChangeLog.find(); + const rolePermissionChangeLogs = await PermissionChangeLog.find(); + + const formattedUserChangeLogs = userChangeLogs.map(log => ({ + ...log.toObject(), + name: log.individualName, + })); + + const formattedRolePermissionChangeLogs = rolePermissionChangeLogs.map(log => ({ + ...log.toObject(), + name: log.roleName, + })); + + const mergedLogs = [...formattedUserChangeLogs, ...formattedRolePermissionChangeLogs].sort( + (a, b) => new Date(b.logDateTime) - new Date(a.logDateTime) + ); + + res.status(200).json(mergedLogs); } } else { res.status(403).send(`User (${req.params.userId}) not found.`); diff --git a/src/controllers/userProfileController.js b/src/controllers/userProfileController.js index 6a23dd34b..d89e26f41 100644 --- a/src/controllers/userProfileController.js +++ b/src/controllers/userProfileController.js @@ -17,6 +17,7 @@ const userService = require('../services/userService'); // const { authorizedUserSara, authorizedUserJae } = process.env; const authorizedUserSara = `nathaliaowner@gmail.com`; // To test this code please include your email here const authorizedUserJae = `jae@onecommunityglobal.org`; +const logUserPermissionChangeByAccount = require('../utilities/logUserPermissionChangeByAccount'); const { hasPermission, canRequestorUpdateUser } = require('../utilities/permissions'); const helper = require('../utilities/permissions'); @@ -696,6 +697,7 @@ const userProfileController = function (UserProfile, Project) { (await hasPermission(req.body.requestor, 'putUserProfilePermissions')) ) { record.permissions = req.body.permissions; + await logUserPermissionChangeByAccount(req); } if (req.body.endDate !== undefined) { diff --git a/src/models/userPermissionChangeLog.js b/src/models/userPermissionChangeLog.js new file mode 100644 index 000000000..051a597dc --- /dev/null +++ b/src/models/userPermissionChangeLog.js @@ -0,0 +1,23 @@ +const mongoose = require('mongoose'); + +const { Schema } = mongoose; + +const User = require('./userProfile'); + + +const UserPermissionChangeLog = new Schema({ + logDateTime: { type: String, required: true }, + userId: { + type: mongoose.Types.ObjectId, + ref: User, + required: true, + }, + individualName: { type: String }, + permissions: { type: [String], required: true }, + permissionsAdded: { type: [String], default: [] }, + permissionsRemoved: { type: [String], default: [] }, + requestorRole: { type: String }, + requestorEmail: { type: String, required: true }, +}); + +module.exports = mongoose.model('UserPermissionChangeLog', UserPermissionChangeLog, 'UserPermissionChangeLogs'); diff --git a/src/routes/permissionChangeLogsRouter.js b/src/routes/permissionChangeLogsRouter.js index 50ed7696b..32d3323fd 100644 --- a/src/routes/permissionChangeLogsRouter.js +++ b/src/routes/permissionChangeLogsRouter.js @@ -1,7 +1,7 @@ const express = require('express'); -const routes = function (permissionChangeLog) { - const controller = require('../controllers/permissionChangeLogsController')(permissionChangeLog); +const routes = function (permissionChangeLog, userPermissionChangeLog) { + const controller = require('../controllers/permissionChangeLogsController')(permissionChangeLog, userPermissionChangeLog); const permissionChangeLogRouter = express.Router(); diff --git a/src/startup/routes.js b/src/startup/routes.js index 8274188bc..57b1e5d80 100644 --- a/src/startup/routes.js +++ b/src/startup/routes.js @@ -26,6 +26,7 @@ const profileInitialSetuptoken = require('../models/profileInitialSetupToken'); const reason = require('../models/reason'); const mouseoverText = require('../models/mouseoverText'); const permissionChangeLog = require('../models/permissionChangeLog'); +const userPermissionChangeLog = require('../models/userPermissionChangeLog'); const mapLocations = require('../models/mapLocation'); const buildingProject = require('../models/bmdashboard/buildingProject'); const buildingNewLesson = require('../models/bmdashboard/buildingNewLesson'); @@ -78,7 +79,7 @@ const profileInitialSetupRouter = require('../routes/profileInitialSetupRouter') mapLocations, ); const permissionChangeLogRouter = require('../routes/permissionChangeLogsRouter')( - permissionChangeLog, + permissionChangeLog, userPermissionChangeLog, ); const isEmailExistsRouter = require('../routes/isEmailExistsRouter')(); diff --git a/src/utilities/logPermissionChangeByAccount.js b/src/utilities/logPermissionChangeByAccount.js index f47c0c5b2..b08e8ee34 100644 --- a/src/utilities/logPermissionChangeByAccount.js +++ b/src/utilities/logPermissionChangeByAccount.js @@ -24,6 +24,10 @@ const changedPermissionsLogger = async (req, res, next) => { permissionsAdded = permissions; } + if (permissionsAdded.length === 0 && permissionsRemoved.length === 0) { + return next(); // No changes, proceed without saving a log + } + const logEntry = new PermissionChangeLog({ logDateTime: dateTime, roleId, diff --git a/src/utilities/logUserPermissionChangeByAccount.js b/src/utilities/logUserPermissionChangeByAccount.js new file mode 100644 index 000000000..700bceaf1 --- /dev/null +++ b/src/utilities/logUserPermissionChangeByAccount.js @@ -0,0 +1,58 @@ +const moment = require('moment-timezone'); +const UserPermissionChangeLog = require('../models/userPermissionChangeLog'); +const UserProfile = require('../models/userProfile'); + +const logUserPermissionChangeByAccount = async (req) => { + const { permissions, firstName, lastName, requestor } = req.body; + const dateTime = moment().tz('America/Los_Angeles').format(); + + try { + let permissionsAdded = []; + let permissionsRemoved = []; + const { userId } = req.params; + const Permissions = permissions.frontPermissions; + const requestorEmailId = await UserProfile.findById(requestor.requestorId).select('email').exec(); + const document = await findLatestRelatedLog(userId); + + if (document) { + const docPermissions = Array.isArray(document.permissions) ? document.permissions : []; + if(JSON.stringify(docPermissions) === JSON.stringify(Permissions)) { + return; + } + permissionsRemoved = docPermissions.filter((item) => !Permissions.includes(item)); + permissionsAdded = Permissions.filter((item) => !docPermissions.includes(item)); + } else { + permissionsAdded = Permissions; + } + + const logEntry = new UserPermissionChangeLog({ + logDateTime: dateTime, + userId, + individualName: `INDIVIDUAL: ${firstName} ${lastName}`, + permissions: Permissions, + permissionsAdded, + permissionsRemoved, + requestorRole: requestor.role, + requestorEmail: requestorEmailId.email, + }); + + await logEntry.save(); + console.log('Permission change logged successfully'); + } catch (error) { + console.error('Error logging permission change:', error); + } +}; + +const findLatestRelatedLog = (userId) => new Promise((resolve, reject) => { + UserPermissionChangeLog.findOne({ userId }) + .sort({ logDateTime: -1 }) + .exec((err, document) => { + if (err) { + reject(err); + return; + } + resolve(document); + }); +}); + +module.exports = logUserPermissionChangeByAccount;