RBAC ADDED AND LOG FILTERING

This commit is contained in:
BIG2EYEZ 2024-01-16 17:54:33 +08:00
parent 1fbfa68f1a
commit 35d8c74990
4 changed files with 242 additions and 138 deletions

View File

@ -21,17 +21,18 @@ connection.connect((err) => {
});
*/
/*
const connection = mysql.createConnection({
host: process.env.host,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: "database",
database: "adminusers",
timezone: "Z", // Set the timezone to UTC
ssl: {
ca: fs.readFileSync(path.resolve(__dirname, '../../cert/DigiCertGlobalRootCA.crt.pem')),
}
});
*/
/*
const connection = mysql.createConnection({
host: process.env.host,
user: process.env.DB_USER,
@ -39,9 +40,9 @@ const connection = mysql.createConnection({
database: "adminusers",
timezone: "Z", // Set the timezone to UTC
});
*/
module.exports = { connection, };
module.exports = { connection };

View File

@ -288,7 +288,7 @@ app.use(setCSRFToken);
} else {
console.log(`Session destroyed.`);
res.clearCookie('sessionToken');
// Log the logout activity using a separate async function
await logLogoutActivity(username, true, "User logged out. Session destroyed.");
}
@ -321,9 +321,9 @@ app.get("/inusers", isAuthenticated, (req, res) => {
res.status(500).send("Internal Server Error");
return;
}
const currentUsername = req.session.username;
// Render the inusers page with JSON data
res.render("inusers", { allUsers ,csrfToken: req.session.csrfToken });
res.render("inusers", { allUsers ,csrfToken: req.session.csrfToken, currentUsername:currentUsername });
});
});
function isStrongPassword(password) {
@ -407,7 +407,7 @@ app.post(
// Extract user input
const { name, username, email, password, jobTitle } = req.body;
console.log(submittedCSRFToken);
// Extract the username of the user creating a new user
const creatorUsername = req.session.username; // Adjust this based on how you store the creator's username in your session
@ -449,20 +449,23 @@ app.post(
message: "Email is already in use. Please choose another email."
});
}
bcrypt.genSalt(10, (saltError, salt) => {
if (saltError) {
console.error("Error generating salt:", saltError);
return res.status(500).json({ error: "Internal Server Error" });
}
// Hash the password before storing it in the database
bcrypt.hash(password, 10, (hashError, hashedPassword) => {
if (hashError) {
console.error("Error hashing password:", hashError);
return res.status(500).json({ error: "Internal Server Error" });
}
bcrypt.hash(req.body.password, salt, (hashError, hashedPassword) => {
if (hashError) {
console.error("Error hashing password:", hashError);
return res.status(500).json({ error: "Internal Server Error" });
}
// Start a transaction
connection.beginTransaction((transactionErr) => {
if (transactionErr) {
console.error("Error starting transaction:", transactionErr);
return res.status(500).json({ error: "Internal Server Error" });
}
connection.beginTransaction((transactionErr) => {
if (transactionErr) {
console.error("Error starting transaction:", transactionErr);
return res.status(500).json({ error: "Internal Server Error" });
}
// Define the insert query
const insertUserQuery =
@ -491,32 +494,28 @@ app.post(
// Commit the transaction
connection.commit((commitErr) => {
if (commitErr) {
console.error("Error committing transaction:", commitErr);
// Log unsuccessful user creation due to an error
logUserCreationActivity(creatorUsername, false, "internal error");
return res.status(500).json({ error: "Internal Server Error" });
}
if (commitErr) {
console.error("Error committing transaction:", commitErr);
return res.status(500).json({ error: "Internal Server Error" });
}
// Log successful user creation
logUserCreationActivity(creatorUsername, true, "user created successfully");
res.status(200).json({ message: "User created successfully" });
logUserCreationActivity(creatorUsername, true, "user created successfully");
// Redirect to "/inusers"
res.redirect('/inusers');
});
});
});
});
});
});
} catch (error) {
console.error("Error creating user:", error);
// Log unsuccessful user creation due to an error
logUserCreationActivity(req.session.username, false, "internal error"); // Adjust this based on how you store the creator's username in your session
res.status(500).json({ error: "Internal Server Error" });
}
}
);
});
});
});
});
});
});
});
} catch (error) {
console.error("Error creating user:", error);
return res.status(500).json({ error: "Internal Server Error" });
}
}
);
app.get("/forgot-password", (req, res) => {
@ -655,13 +654,30 @@ app.post("/reset-password/:token", async (req, res) => {
}
// Hash the new password
const hashedPassword = await bcrypt.hash(sanitizedPassword, 10);
const hashedPassword = await new Promise((resolve, reject) => {
bcrypt.genSalt(10, (saltError, salt) => {
if (saltError) {
console.error("Error generating salt:", saltError);
reject("Internal Server Error");
}
// Use the generated salt to hash the password
bcrypt.hash(sanitizedPassword, salt, (hashError, hashed) => {
if (hashError) {
console.error("Error hashing password:", hashError);
reject("Internal Server Error");
}
resolve(hashed);
});
});
});
// Update user's password and clear reset token
const updateQuery =
"UPDATE users SET password = ?, reset_token = NULL, reset_token_expiry = NULL WHERE reset_token = ?";
connection.query(updateQuery, [hashedPassword, sanitizedToken], async (updateErr, updateResults) => {
if (updateErr) {
"UPDATE users SET password = ?, reset_token = NULL, reset_token_expiry = NULL WHERE reset_token = ?";
connection.query(updateQuery, [hashedPassword, sanitizedToken], async (updateErr, updateResults) => {
if (updateErr) {
console.error("Error updating password:", updateErr);
// Pass the error to the template when rendering the reset-password page
res.render("reset-password", {
@ -701,14 +717,13 @@ app.get("/reset-password/:token", (req, res) => {
});
});
app.post("/reset-password", async (req, res) => {
const { username, password, confirmPassword, csrf_token } = req.body;
const creatorUsername = req.session.username;
const submittedCSRFToken = req.body.csrf_token;
const submittedCSRFToken = req.body.csrf_token;
if (!req.session.csrfToken || submittedCSRFToken !== req.session.csrfToken) {
return res.status(403).json({ error: 'CSRF token mismatch' });
}
if (!req.session.csrfToken || submittedCSRFToken !== req.session.csrfToken) {
return res.status(403).json({ error: 'CSRF token mismatch' });
}
// Sanitize the inputs
const sanitizedUsername = validator.escape(username);
@ -728,8 +743,12 @@ app.post("/reset-password", async (req, res) => {
});
}
// Hash the new password
const hashedPassword = await bcrypt.hash(sanitizedPassword, 10);
// Generate a random salt
const saltRounds = 10; // You can adjust the number of rounds based on your security requirements
const salt = await bcrypt.genSalt(saltRounds);
// Hash the new password with the generated salt
const hashedPassword = await bcrypt.hash(sanitizedPassword, salt);
// Check if the user exists in the database before updating the password
const userExists = await checkIfUserExists(sanitizedUsername);
@ -739,8 +758,8 @@ app.post("/reset-password", async (req, res) => {
}
// Update user's password based on the username
const updateQuery = "UPDATE users SET password = ? WHERE username = ?";
connection.query(updateQuery, [hashedPassword, sanitizedUsername], async (updateErr, updateResults) => {
const updateQuery = "UPDATE users SET password = ?, salt = ? WHERE username = ?";
connection.query(updateQuery, [hashedPassword, salt, sanitizedUsername], async (updateErr, updateResults) => {
if (updateErr) {
console.error("Error updating password:", updateErr);
return res.status(500).json({ error: "Error updating password" });
@ -768,6 +787,7 @@ app.post("/reset-password", async (req, res) => {
});
});
async function checkIfUserExists(username) {
return new Promise((resolve, reject) => {
const query = "SELECT * FROM users WHERE username = ?";

View File

@ -10,6 +10,7 @@
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.3.0/css/bootstrap.min.css">
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/user-creation.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
@ -92,7 +93,7 @@
<span class="details">Job Title</span>
<select name="jobTitle" id="jobTitle">
<option value="admin">Admin</option>
<option value="dataAnalyst">Data Analyst</option>
<option value="user">User</option>
</select>
</div>
</div>
@ -147,9 +148,12 @@
<div id="logsContainer" style="display: none;">
<!-- Content for logs will be added here -->
</div>
<script>
const allUsers = <%- JSON.stringify(allUsers) %>;
const currentUsername = '<%= currentUsername %>';
</script>
@ -159,6 +163,7 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.2.1/exceljs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.js"></script>
<script src="inusers.js"></script>
</div>

View File

@ -59,81 +59,7 @@ $('#logsLink').on('click', function () {
fetchLogs();
});
function fetchLogs() {
// Make a fetch request to your server endpoint for logs
fetch('/api/getLogs')
.then(response => response.json())
.then(logs => {
// Process and display logs in the logs container
displayLogs(logs);
})
.catch(error => {
console.error('Error fetching logs:', error);
// Handle errors, e.g., display an alert
});
}
// Update the displayLogs function to generate a table
function displayLogs(logs) {
const logsContainer = $('#logsContainer');
// Clear previous logs
logsContainer.empty();
if (logs && logs.length > 0) {
// Create the table and header row
const table = $('<table>').addClass('logs-table');
const headerRow = '<tr><th>ID</th><th>Username</th><th>Activity</th><th>Timestamp</th></tr>';
table.append(headerRow);
// Add each log as a row in the table
logs.forEach(log => {
const row = `<tr><td>${log.id}</td><td>${log.username}</td><td>${log.activity}</td><td>${log.timestamp}</td></tr>`;
table.append(row);
});
// Append the table to the logsContainer
logsContainer.append(table);
// Add a download button at the top with the current date and time in the file name
const currentDate = new Date();
const formattedDate = currentDate.toISOString().split('T')[0];
const formattedTime = currentDate.toTimeString().split(' ')[0].replace(/:/g, '-');
const downloadButton = $('<button>').text('Download Log').on('click', function () {
downloadLogs(logs, `log_${formattedDate}_${formattedTime}.csv`);
});
// Prepend the download button to the logsContainer
logsContainer.prepend(downloadButton);
} else {
// Display a message if no logs are available
logsContainer.html('<p>No logs available.</p>');
}
}
function downloadLogs(logs, filename) {
if (logs && logs.length > 0) {
const csvContent = 'data:text/csv;charset=utf-8,';
const header = 'ID,Username,Activity,Timestamp\n';
const rows = logs.map(log => `${log.id},${log.username},${log.activity},"${log.timestamp}"`).join('\n');
const data = header + rows;
const encodedData = encodeURI(csvContent + data);
// Create a hidden anchor element to trigger the download
const link = document.createElement('a');
link.setAttribute('href', encodedData);
link.setAttribute('download', 'logs.csv');
document.body.appendChild(link);
// Trigger the download
link.click();
// Remove the link from the DOM
document.body.removeChild(link);
} else {
console.error('No logs available for download.');
}
}
});
function searchUser(username) {
@ -321,7 +247,7 @@ function resetFormFields() {
}),
})
.then(response => {
if (response.status === 201) {
if (response.ok) {
// Status 201 indicates successful creation
return response.json();
} else {
@ -436,6 +362,158 @@ $('#resetPasswordForm').on('submit', function (e) {
});
});
// Declare a variable to store fetched logs
let logs = [];
// Function to fetch logs from the server
function fetchLogs() {
// Make a fetch request to your server endpoint for logs
fetch('/api/getLogs')
.then(response => response.json())
.then(data => {
// Assign the logs to the variable
logs = data;
// Process and display logs in the logs container
displayLogs(logs);
})
.catch(error => {
console.error('Error fetching logs:', error);
// Handle errors, e.g., display an alert
});
}
// Update the displayLogs function to generate a table
function displayLogs(logs) {
const logsContainer = $('#logsContainer');
// Clear previous logs and date filter elements
logsContainer.empty();
if (logs && logs.length > 0) {
// Add date filter elements
logsContainer.append(`
<label for="datePicker">Filter by Date:</label>
<input type="text" id="datePicker">
<button onclick="applyDateFilter()">Apply Filter</button>
`);
// Create the table and header row
const table = $('<table>').addClass('logs-table');
const headerRow = '<tr><th>ID</th><th>Username</th><th>Activity</th><th>Timestamp</th></tr>';
table.append(headerRow);
// Add each log as a row in the table
logs.forEach(log => {
const row = `<tr><td>${log.id}</td><td>${log.username}</td><td>${log.activity}</td><td>${log.timestamp}</td></tr>`;
table.append(row);
});
// Append the table to the logsContainer
logsContainer.append(table);
// Add a download button at the top with the current date and time in the file name
const currentDate = new Date();
const formattedDate = currentDate.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
const formattedTime = currentDate.toTimeString().split(' ')[0].replace(/:/g, '-');
const downloadButton = $('<button>').text('Download Log').on('click', function () {
downloadLogs(logs, `log_${formattedDate}_${formattedTime}.csv`);
});
// Prepend the download button to the logsContainer
logsContainer.prepend(downloadButton);
} else {
// Display a message if no logs are available
logsContainer.html('<p>No logs available.</p>');
}
// Initialize Flatpickr for the date picker
flatpickr("#datePicker", {
dateFormat: "m/d/Y, h:i:S K", // Adjust the format to match your logs timestamp format
});
}
// Function to apply date filter
function applyDateFilter() {
const selectedDate = $("#datePicker").val();
const formattedSelectedDate = new Date(selectedDate).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
const filteredLogs = logs.filter(log => {
const formattedLogDate = new Date(log.timestamp).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
return formattedLogDate === formattedSelectedDate;
});
displayLogs(filteredLogs);
}
function downloadLogs(logs, filename) {
if (logs && logs.length > 0) {
const csvContent = 'data:text/csv;charset=utf-8,';
const header = 'ID,Username,Activity,Timestamp\n';
const rows = logs.map(log => `${log.id},${log.username},${log.activity},"${log.timestamp}"`).join('\n');
const data = header + rows;
const encodedData = encodeURI(csvContent + data);
// Create a hidden anchor element to trigger the download
const link = document.createElement('a');
link.setAttribute('href', encodedData);
link.setAttribute('download', 'logs.csv');
document.body.appendChild(link);
// Trigger the download
link.click();
// Remove the link from the DOM
document.body.removeChild(link);
} else {
console.error('No logs available for download.');
}
}
fetchLogs();
// Assuming EJS is properly configured to evaluate expressions
// Assuming allUsers is an array containing user information
const user = allUsers.find(user => user.username === currentUsername);
const userRole = user?.jobTitle;
console.log('All Users:', allUsers);
console.log('Current Username:', currentUsername);
// Log the user role to the console
console.log('User Role:', userRole);
// Function to enable/disable actions based on user role
function handleUserRoleAccess() {
// Disable user creation, deletion, and password reset for non-admin users
if (userRole !== 'admin') {
document.getElementById('addUserLink').style.display = 'none';
document.getElementById('deleteUserLink').style.display = 'none';
document.getElementById('resetPasswordLink').style.display = 'none';
}
// Allow admin users to view logs
if (userRole === 'admin') {
document.getElementById('logsLink').classList.remove('hidden');
}
}
// Call the function to handle user role access when the page loads
handleUserRoleAccess();