Merge pull request #19 from Newtbot/ANTI-CSRF-FUNCTION-ALL

ANTI CSRF FUNCTION
This commit is contained in:
noot 2024-01-13 17:13:47 +08:00 committed by GitHub
commit 5cd52f9991
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 205 additions and 231 deletions

View File

@ -243,6 +243,7 @@ async (req, res) => {
// Log anti-CSRF token // Log anti-CSRF token
console.log(`Generated Anti-CSRF Token: ${req.session.csrfToken}`); console.log(`Generated Anti-CSRF Token: ${req.session.csrfToken}`);
// Set CSRF token as a cookie
// Implement secure session handling: // Implement secure session handling:
// 1. Set secure, HttpOnly, and SameSite flags // 1. Set secure, HttpOnly, and SameSite flags
@ -269,7 +270,12 @@ async (req, res) => {
} }
}); });
function setCSRFToken(req, res, next) {
res.locals.csrfToken = req.session.csrfToken;
next();
}
app.use(setCSRFToken);
app.get("/logout", (req, res) => { app.get("/logout", (req, res) => {
try { try {
@ -342,7 +348,7 @@ app.get("/inusers", isAuthenticated, (req, res) => {
} }
// Render the inusers page with JSON data // Render the inusers page with JSON data
res.render("inusers", { allUsers }); res.render("inusers", { allUsers ,csrfToken: req.session.csrfToken });
}); });
}); });
function isStrongPassword(password) { function isStrongPassword(password) {
@ -399,201 +405,144 @@ const logUserCreationActivity = async (creatorUsername, success, message) => {
}; };
app.post( app.post(
'/createUser', '/createUser',
[ [
body('name').trim().isLength({ min: 1 }).withMessage('Name must not be empty').escape(), body('name').trim().isLength({ min: 1 }).withMessage('Name must not be empty').escape(),
body('username').trim().isLength({ min: 1 }).withMessage('Username must not be empty').escape(), body('username').trim().isLength({ min: 1 }).withMessage('Username must not be empty').escape(),
body('email').isEmail().withMessage('Invalid email address').normalizeEmail(), body('email').isEmail().withMessage('Invalid email address').normalizeEmail(),
body('password').custom((value) => { body('password').custom((value) => {
if (!isStrongPassword(value)) { if (!isStrongPassword(value)) { throw new Error('Password does not meet complexity requirements'); } return true;
throw new Error('Password does not meet complexity requirements'); }),
} body('jobTitle').trim().isLength({ min: 1 }).withMessage('Job title must not be empty').escape(),
return true; ],
}), async (req, res) => {
body('jobTitle').trim().isLength({ min: 1 }).withMessage('Job title must not be empty').escape(), try {
], const errors = validationResult(req);
async (req, res) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) { if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() }); return res.status(400).json({ errors: errors.array() });
} }
const { name, username, email, password, jobTitle } = req.body; // Validate the anti-CSRF token
console.log("Sanitized Input:", { const submittedCSRFToken = req.body.csrf_token;
name,
username,
email,
password: "*****", // Avoid logging passwords
jobTitle,
});
// 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
// Validate password complexity (additional check) if (!req.session.csrfToken || submittedCSRFToken !== req.session.csrfToken) {
if (!isStrongPassword(password)) { return res.status(403).json({ error: 'CSRF token mismatch' });
return res }
.status(400)
.json({ error: "Password does not meet complexity requirements" });
}
// Check if the username is already taken // Extract user input
const checkUsernameQuery = "SELECT * FROM users WHERE username = ?"; const { name, username, email, password, jobTitle } = req.body;
connection.query(
checkUsernameQuery,
[username],
(usernameQueryErr, usernameResults) => {
if (usernameQueryErr) {
console.error("Error checking username:", usernameQueryErr);
return res.status(500).json({ error: "Internal Server Error" });
}
if (usernameResults.length > 0) { // Extract the username of the user creating a new user
// Log unsuccessful user creation due to username taken const creatorUsername = req.session.username; // Adjust this based on how you store the creator's username in your session
logUserCreationActivity(creatorUsername, false, "username taken");
return res
.status(400)
.json({
error: "Username is already taken",
message: "Username is already taken. Please choose a different username.",
});
}
// Check if the email is already taken // Additional password complexity check
const checkEmailQuery = "SELECT * FROM users WHERE email = ?"; if (!isStrongPassword(password)) {
connection.query( return res.status(400).json({ error: "Password does not meet complexity requirements" });
checkEmailQuery, }
[email],
(emailQueryErr, emailResults) => {
if (emailQueryErr) {
console.error("Error checking email:", emailQueryErr);
return res.status(500).json({ error: "Internal Server Error" });
}
if (emailResults.length > 0) { // Check if the username is already taken
// Log unsuccessful user creation due to email taken const checkUsernameQuery = "SELECT * FROM users WHERE username = ?";
logUserCreationActivity(creatorUsername, false, "email taken"); connection.query(checkUsernameQuery, [username], (usernameQueryErr, usernameResults) => {
return res if (usernameQueryErr) {
.status(400) console.error("Error checking username:", usernameQueryErr);
.json({ return res.status(500).json({ error: "Internal Server Error" });
error: "Email is already in use", }
message: "Email is already in use. Please choose another email.",
});
}
// Hash the password before storing it in the database if (usernameResults.length > 0) {
bcrypt.hash(password, 10, (hashError, hashedPassword) => { // Log unsuccessful user creation due to username taken
if (hashError) { logUserCreationActivity(creatorUsername, false, "username taken");
console.error("Error hashing password:", hashError); return res.status(400).json({
return res.status(500).json({ error: "Internal Server Error" }); error: "Username is already taken",
} message: "Username is already taken. Please choose a different username."
});
}
// Start a transaction // Check if the email is already taken
connection.beginTransaction((transactionErr) => { const checkEmailQuery = "SELECT * FROM users WHERE email = ?";
if (transactionErr) { connection.query(checkEmailQuery, [email], (emailQueryErr, emailResults) => {
console.error("Error starting transaction:", transactionErr); if (emailQueryErr) {
return res console.error("Error checking email:", emailQueryErr);
.status(500) return res.status(500).json({ error: "Internal Server Error" });
.json({ error: "Internal Server Error" }); }
}
// Define the insert query if (emailResults.length > 0) {
const insertUserQuery = // Log unsuccessful user creation due to email taken
"INSERT INTO users (name, username, email, password, lastLogin, jobTitle) VALUES (?, ?, ?, ?, NULL, ?)"; logUserCreationActivity(creatorUsername, false, "email taken");
return res.status(400).json({
error: "Email is already in use",
message: "Email is already in use. Please choose another email."
});
}
// Log the query and its parameters // Hash the password before storing it in the database
console.log("Insert Query:", insertUserQuery); bcrypt.hash(password, 10, (hashError, hashedPassword) => {
console.log("Query Parameters:", [ if (hashError) {
name, console.error("Error hashing password:", hashError);
username, return res.status(500).json({ error: "Internal Server Error" });
email, }
hashedPassword,
jobTitle,
]);
// Execute the query with user data // Start a transaction
connection.query( connection.beginTransaction((transactionErr) => {
insertUserQuery, if (transactionErr) {
[name, username, email, hashedPassword, jobTitle], console.error("Error starting transaction:", transactionErr);
(queryErr, results) => { return res.status(500).json({ error: "Internal Server Error" });
if (queryErr) { }
console.error("Error executing query:", queryErr);
// Rollback the transaction in case of an error // Define the insert query
connection.rollback((rollbackErr) => { const insertUserQuery =
if (rollbackErr) { "INSERT INTO users (name, username, email, password, lastLogin, jobTitle) VALUES (?, ?, ?, ?, NULL, ?)";
console.error(
"Error rolling back transaction:",
rollbackErr
);
}
// Log unsuccessful user creation due to an error
logUserCreationActivity(
creatorUsername,
false,
"internal error"
);
return res
.status(500)
.json({ error: "Internal Server Error" });
});
return;
}
// Commit the transaction // Log the query and its parameters
connection.commit((commitErr) => { console.log("Insert Query:", insertUserQuery);
if (commitErr) { console.log("Query Parameters:", [name, username, email, hashedPassword, jobTitle]);
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" });
}
// Log successful user creation // Execute the query with user data
logUserCreationActivity( connection.query(insertUserQuery, [name, username, email, hashedPassword, jobTitle], (queryErr, results) => {
creatorUsername, if (queryErr) {
true, console.error("Error executing query:", queryErr);
"user created successfully"
);
// Log the results of the query // Rollback the transaction in case of an error
console.log("Query Results:", results); connection.rollback((rollbackErr) => {
if (rollbackErr) {
console.error("Error rolling back transaction:", rollbackErr);
}
// Log unsuccessful user creation due to an error
logUserCreationActivity(creatorUsername, false, "internal error");
return res.status(500).json({ error: "Internal Server Error" });
});
return;
}
// Respond with a success message // Commit the transaction
res connection.commit((commitErr) => {
.status(201) if (commitErr) {
.json({ message: "User created successfully" }); 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" });
}); }
});
} // Log successful user creation
); logUserCreationActivity(creatorUsername, true, "user created successfully");
}
); // Redirect to "/inusers"
} catch (error) { res.redirect('/inusers');
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);
// 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" });
}
}
);
app.get("/forgot-password", (req, res) => {
res.render("forgot-password"); // Assuming you have an EJS template for this
});
app.get("/forgot-password", (req, res) => { app.get("/forgot-password", (req, res) => {
res.render("forgot-password", { error: null, success: null }); res.render("forgot-password", { error: null, success: null });
@ -777,8 +726,14 @@ app.get("/reset-password/:token", (req, res) => {
}); });
}); });
app.post("/reset-password", async (req, res) => { app.post("/reset-password", async (req, res) => {
const { username, password, confirmPassword } = req.body;
const { username, password, confirmPassword, csrf_token } = req.body;
const creatorUsername = req.session.username; const creatorUsername = req.session.username;
const submittedCSRFToken = req.body.csrf_token;
if (!req.session.csrfToken || submittedCSRFToken !== req.session.csrfToken) {
return res.status(403).json({ error: 'CSRF token mismatch' });
}
// Sanitize the inputs // Sanitize the inputs
const sanitizedUsername = validator.escape(username); const sanitizedUsername = validator.escape(username);
@ -899,13 +854,20 @@ app.get('/api/users', (req, res) => {
}); });
}); });
// Route to delete a user by username
app.delete('/api/deleteUser/:username', async (req, res) => { app.delete('/api/deleteUser/:username', async (req, res) => {
const { username } = req.params; const { username } = req.params;
const query = 'DELETE FROM users WHERE username = ?'; const query = 'DELETE FROM users WHERE username = ?';
const creatorUsername = req.session.username; const creatorUsername = req.session.username;
try { try {
// Extract CSRF token from the request body
const { csrfToken } = req.body;
// Compare CSRF token with the one stored in the session
if (csrfToken !== req.session.csrfToken) {
return res.status(403).json({ success: false, error: 'CSRF token mismatch' });
}
// Log deletion activity to USER_LOGS // Log deletion activity to USER_LOGS
const deletionActivity = `User ${username} has been successfully deleted`; const deletionActivity = `User ${username} has been successfully deleted`;
const logQuery = 'INSERT INTO USER_LOGS (USERNAME, ACTIVITY, TIMESTAMP) VALUES (?, ?, CURRENT_TIMESTAMP)'; const logQuery = 'INSERT INTO USER_LOGS (USERNAME, ACTIVITY, TIMESTAMP) VALUES (?, ?, CURRENT_TIMESTAMP)';
@ -925,6 +887,7 @@ app.get('/api/users', (req, res) => {
} }
}); });
async function executeQuery(sql, values) { async function executeQuery(sql, values) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
connection.query(sql, values, (err, results) => { connection.query(sql, values, (err, results) => {

View File

@ -122,6 +122,7 @@
<input type="password" name="confirmPassword" id="resetConfirmPassword" placeholder="Confirm new password" required> <input type="password" name="confirmPassword" id="resetConfirmPassword" placeholder="Confirm new password" required>
</div> </div>
</div> </div>
<input type="hidden" name="csrf_token" value="<%= csrfToken %>">
<div class="button"> <div class="button">
<input type="submit" value="Reset Password"> <input type="submit" value="Reset Password">
</div> </div>
@ -129,6 +130,7 @@
</div> </div>
</div> </div>
</div> </div>
</div>
<div id="deleteUserContainer" style="display: none;"> <div id="deleteUserContainer" style="display: none;">
<h3>Delete User</h3> <h3>Delete User</h3>
<div class="search-container"> <div class="search-container">
@ -137,7 +139,9 @@
</div> </div>
<div id="searchResultsContainer" style="display: none;"> <div id="searchResultsContainer" style="display: none;">
<h4>Search Results</h4> <h4>Search Results</h4>
<ul id="searchResultsList"></ul> <ul id="searchResultsList">
<input type="hidden" name="csrf_token" value="<%= csrfToken %>">
</ul>
</div> </div>
</div> </div>

View File

@ -1,5 +1,3 @@
$(document).ready(function () { $(document).ready(function () {
$('#resetPasswordLink').on('click', function () { $('#resetPasswordLink').on('click', function () {
$('#resetPasswordFormContainer').show(); $('#resetPasswordFormContainer').show();
@ -177,13 +175,22 @@ function displaySearchResults(users) {
$('#searchResultsContainer').hide(); $('#searchResultsContainer').hide();
} }
} }
// Event listener for delete user button in search results // Event listener for delete user button in search results
$('#searchResultsList').on('click', '.deleteUserButton', function () { $('#searchResultsList').on('click', '.deleteUserButton', function () {
const usernameToDelete = $(this).data('username'); const usernameToDelete = $(this).data('username');
const csrfToken = $('[name="csrf_token"]').val(); // Access the CSRF token by name
console.log(csrfToken);
console.log('Before fetch for user deletion'); console.log('Before fetch for user deletion');
// Make a fetch request to delete the user
// Make a fetch request to delete the user with CSRF token in headers
fetch(`/api/deleteUser/${usernameToDelete}`, { fetch(`/api/deleteUser/${usernameToDelete}`, {
method: 'DELETE', method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ csrfToken }), // Include CSRF token in the request body
}) })
.then(response => { .then(response => {
console.log('Inside fetch response handler'); console.log('Inside fetch response handler');
@ -277,8 +284,7 @@ function resetFormFields() {
$('#confirmPassword').val(''); $('#confirmPassword').val('');
$('#jobTitle').val(''); $('#jobTitle').val('');
} }
const csrf_token = $('#userForm input[name="csrf_token"]').val();
$('#userForm').on('submit', function (e) { $('#userForm').on('submit', function (e) {
e.preventDefault(); e.preventDefault();
@ -302,34 +308,36 @@ function resetFormFields() {
fetch('/createUser', { fetch('/createUser', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({
name: name, name: name,
username: username, username: username,
email: email, email: email,
password: password, password: password,
jobTitle: jobTitle, jobTitle: jobTitle,
csrf_token: csrf_token, // Include the CSRF token in the body
}), }),
}) })
.then(response => { .then(response => {
if (response.status === 201) { if (response.status === 201) {
// Status 201 indicates successful creation // Status 201 indicates successful creation
return response.json(); return response.json();
} else { } else {
return response.json().then(data => { return response.json().then(data => {
throw new Error(data.error || `HTTP error! Status: ${response.status}`); throw new Error(data.error || `HTTP error! Status: ${response.status}`);
}); });
} }
}) })
.then(data => { .then(data => {
console.log('User registration success:', data); console.log('User registration success:', data);
alert('User registered successfully!'); alert('User registered successfully!');
resetFormFields(); resetFormFields();
}) })
.catch(error => { .catch(error => {
console.error('User registration error:', error); console.error('User registration error:', error);
handleRegistrationError(error); handleRegistrationError(error);
}); });
}); });
@ -368,7 +376,7 @@ $('#resetPasswordForm').on('submit', function (e) {
const username = $('#resetUsername').val(); const username = $('#resetUsername').val();
const password = $('#resetPassword').val(); const password = $('#resetPassword').val();
const confirmPassword = $('#resetConfirmPassword').val(); const confirmPassword = $('#resetConfirmPassword').val();
const csrf_token = $('#userForm input[name="csrf_token"]').val();
console.log('Username:', username); console.log('Username:', username);
console.log('New Password:', password); console.log('New Password:', password);
@ -384,8 +392,7 @@ $('#resetPasswordForm').on('submit', function (e) {
return; return;
} }
// Make a fetch request fetch('/reset-password', {
fetch('/reset-password', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -394,6 +401,7 @@ $('#resetPasswordForm').on('submit', function (e) {
username: username, username: username,
password: password, password: password,
confirmPassword: confirmPassword, confirmPassword: confirmPassword,
csrf_token: csrf_token
}), }),
}) })
.then(response => { .then(response => {
@ -431,4 +439,3 @@ $('#resetPasswordForm').on('submit', function (e) {