Skip to content

Commit

Permalink
Merge pull request #1149 from OneCommunityGlobal/Yashwanth_individual…
Browse files Browse the repository at this point in the history
…_permission_change_show_backend

Yashwanth_Backend_for_permission_log_table
  • Loading branch information
one-community authored Dec 29, 2024
2 parents eafa526 + 5eba92b commit 70b6b76
Show file tree
Hide file tree
Showing 7 changed files with 110 additions and 6 deletions.
22 changes: 19 additions & 3 deletions src/controllers/permissionChangeLogsController.js
Original file line number Diff line number Diff line change
@@ -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();
Expand All @@ -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.`);
Expand Down
2 changes: 2 additions & 0 deletions src/controllers/userProfileController.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const userService = require('../services/userService');
// const { authorizedUserSara, authorizedUserJae } = process.env;
const authorizedUserSara = `[email protected]`; // To test this code please include your email here
const authorizedUserJae = `[email protected]`;
const logUserPermissionChangeByAccount = require('../utilities/logUserPermissionChangeByAccount');

const { hasPermission, canRequestorUpdateUser } = require('../utilities/permissions');
const helper = require('../utilities/permissions');
Expand Down Expand Up @@ -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) {
Expand Down
23 changes: 23 additions & 0 deletions src/models/userPermissionChangeLog.js
Original file line number Diff line number Diff line change
@@ -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');
4 changes: 2 additions & 2 deletions src/routes/permissionChangeLogsRouter.js
Original file line number Diff line number Diff line change
@@ -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();

Expand Down
3 changes: 2 additions & 1 deletion src/startup/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -78,7 +79,7 @@ const profileInitialSetupRouter = require('../routes/profileInitialSetupRouter')
mapLocations,
);
const permissionChangeLogRouter = require('../routes/permissionChangeLogsRouter')(
permissionChangeLog,
permissionChangeLog, userPermissionChangeLog,
);
const isEmailExistsRouter = require('../routes/isEmailExistsRouter')();

Expand Down
4 changes: 4 additions & 0 deletions src/utilities/logPermissionChangeByAccount.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
58 changes: 58 additions & 0 deletions src/utilities/logUserPermissionChangeByAccount.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 70b6b76

Please sign in to comment.