139 lines
3.6 KiB
JavaScript
139 lines
3.6 KiB
JavaScript
import dotenv from "dotenv";
|
|
import { userModel } from "../../schemas/user.schema.js";
|
|
import jwt from "jsonwebtoken";
|
|
import log4js from "log4js";
|
|
import mongoose from "mongoose";
|
|
import { newAuditLog } from "../../util/index.js";
|
|
import { auditLogModel } from "../../schemas/auditlog.schema.js";
|
|
|
|
dotenv.config();
|
|
|
|
const logger = log4js.getLogger("Users");
|
|
logger.level = process.env.LOG_LEVEL;
|
|
|
|
export const listUsersRouteHandler = async (
|
|
req,
|
|
res,
|
|
page = 1,
|
|
limit = 25,
|
|
property = "",
|
|
filter = {},
|
|
) => {
|
|
try {
|
|
// Calculate the skip value based on the page number and limit
|
|
const skip = (page - 1) * limit;
|
|
|
|
let user;
|
|
let aggregateCommand = [];
|
|
|
|
if (filter != {}) {
|
|
// use filtering if present
|
|
aggregateCommand.push({ $match: filter });
|
|
}
|
|
|
|
if (property != "") {
|
|
aggregateCommand.push({ $group: { _id: `$${property}` } }); // group all same properties
|
|
aggregateCommand.push({ $project: { _id: 0, [property]: "$_id" } }); // rename _id to the property name
|
|
|
|
}
|
|
|
|
aggregateCommand.push({ $skip: skip });
|
|
aggregateCommand.push({ $limit: Number(limit) });
|
|
|
|
console.log(aggregateCommand);
|
|
|
|
user = await userModel.aggregate(aggregateCommand);
|
|
|
|
logger.trace(
|
|
`List of users (Page ${page}, Limit ${limit}, Property ${property}):`,
|
|
user,
|
|
);
|
|
res.send(user);
|
|
} catch (error) {
|
|
logger.error("Error listing users:", error);
|
|
res.status(500).send({ error: error });
|
|
}
|
|
};
|
|
|
|
export const getUserRouteHandler = async (req, res) => {
|
|
try {
|
|
// Get ID from params
|
|
const id = new mongoose.Types.ObjectId(req.params.id);
|
|
// Fetch the user with the given ID
|
|
const user = await userModel.findOne({
|
|
_id: id,
|
|
});
|
|
|
|
if (!user) {
|
|
logger.warn(`User not found with supplied id.`);
|
|
return res.status(404).send({ error: "User not found." });
|
|
}
|
|
|
|
logger.trace(`User with ID: ${id}:`, user);
|
|
|
|
const auditLogs = await auditLogModel.find({
|
|
target: id
|
|
}).populate('owner');
|
|
|
|
res.send({...user._doc, auditLogs: auditLogs});
|
|
} catch (error) {
|
|
logger.error("Error fetching User:", error);
|
|
res.status(500).send({ error: error.message });
|
|
}
|
|
};
|
|
|
|
export const editUserRouteHandler = async (req, res) => {
|
|
try {
|
|
// Get ID from params
|
|
const id = new mongoose.Types.ObjectId(req.params.id);
|
|
// Fetch the user with the given ID
|
|
const user = await userModel.findOne({ _id: id });
|
|
|
|
if (!user) {
|
|
// Error handling
|
|
logger.warn(`User not found with supplied id.`);
|
|
return res.status(404).send({ error: "User not found." });
|
|
}
|
|
|
|
logger.trace(`User with ID: ${id}:`, user);
|
|
|
|
try {
|
|
const updateData = {
|
|
updatedAt: new Date(),
|
|
username: req.body.username,
|
|
name: req.body.name,
|
|
firstName: req.body.firstName,
|
|
lastName: req.body.lastName,
|
|
email: req.body.email,
|
|
};
|
|
|
|
console.log(req.user)
|
|
|
|
// Create audit log before updating
|
|
await newAuditLog(
|
|
user.toObject(),
|
|
updateData,
|
|
id,
|
|
'User',
|
|
req.user._id,
|
|
'User'
|
|
);
|
|
|
|
const result = await userModel.updateOne(
|
|
{ _id: id },
|
|
{ $set: updateData },
|
|
);
|
|
if (result.nModified === 0) {
|
|
logger.error("No User updated.");
|
|
res.status(500).send({ error: "No users updated." });
|
|
}
|
|
} catch (updateError) {
|
|
logger.error("Error updating user:", updateError);
|
|
res.status(500).send({ error: updateError.message });
|
|
}
|
|
res.send("OK");
|
|
} catch (fetchError) {
|
|
logger.error("Error fetching user:", fetchError);
|
|
res.status(500).send({ error: fetchError.message });
|
|
}
|
|
};
|