update where no duplicate username and email can be created

This commit is contained in:
BIG2EYEZ 2023-12-26 17:41:10 +08:00
parent a5be62cc46
commit 1db32e3c7a
2 changed files with 347 additions and 145 deletions

View File

@ -207,20 +207,42 @@ app.post('/createUser', (req, res) => {
return res.status(400).json({ error: 'Password does not meet complexity requirements' }); return res.status(400).json({ error: 'Password does not meet complexity requirements' });
} }
// Check if the username is already taken
const checkUsernameQuery = 'SELECT * FROM users WHERE username = ?';
mysqlConnection.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) {
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
const checkEmailQuery = 'SELECT * FROM users WHERE email = ?';
mysqlConnection.query(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) {
return res.status(400).json({ 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 // Hash the password before storing it in the database
bcrypt.hash(password, 10, (hashError, hashedPassword) => { bcrypt.hash(password, 10, (hashError, hashedPassword) => {
if (hashError) { if (hashError) {
console.error('Error hashing password:', hashError); console.error('Error hashing password:', hashError);
res.status(500).json({ error: 'Internal Server Error' }); return res.status(500).json({ error: 'Internal Server Error' });
return;
} }
// Start a transaction // Start a transaction
mysqlConnection.beginTransaction((transactionErr) => { mysqlConnection.beginTransaction((transactionErr) => {
if (transactionErr) { if (transactionErr) {
console.error('Error starting transaction:', transactionErr); console.error('Error starting transaction:', transactionErr);
res.status(500).json({ error: 'Internal Server Error' }); return res.status(500).json({ error: 'Internal Server Error' });
return;
} }
// Define the insert query // Define the insert query
@ -240,7 +262,7 @@ app.post('/createUser', (req, res) => {
if (rollbackErr) { if (rollbackErr) {
console.error('Error rolling back transaction:', rollbackErr); console.error('Error rolling back transaction:', rollbackErr);
} }
res.status(500).json({ error: 'Internal Server Error' }); return res.status(500).json({ error: 'Internal Server Error' });
}); });
return; return;
} }
@ -249,8 +271,7 @@ app.post('/createUser', (req, res) => {
mysqlConnection.commit((commitErr) => { mysqlConnection.commit((commitErr) => {
if (commitErr) { if (commitErr) {
console.error('Error committing transaction:', commitErr); console.error('Error committing transaction:', commitErr);
res.status(500).json({ error: 'Internal Server Error' }); return res.status(500).json({ error: 'Internal Server Error' });
return;
} }
// Log the results of the query // Log the results of the query
@ -262,12 +283,90 @@ app.post('/createUser', (req, res) => {
}); });
}); });
}); });
});
});
} catch (error) { } catch (error) {
console.error('Error creating user:', error); console.error('Error creating user:', error);
res.status(500).json({ error: 'Internal Server Error' }); res.status(500).json({ error: 'Internal Server Error' });
} }
}); });
app.post('/check-username-email', (req, res) => {
try {
const { username, email } = req.body;
// Check if the username is already taken
const checkUsernameQuery = 'SELECT * FROM users WHERE username = ?';
mysqlConnection.query(checkUsernameQuery, [username], (usernameQueryErr, usernameResults) => {
if (usernameQueryErr) {
console.error('Error checking username:', usernameQueryErr);
return res.status(500).json({ error: 'Internal Server Error' });
}
// Check if the email is already taken
const checkEmailQuery = 'SELECT * FROM users WHERE email = ?';
mysqlConnection.query(checkEmailQuery, [email], (emailQueryErr, emailResults) => {
if (emailQueryErr) {
console.error('Error checking email:', emailQueryErr);
return res.status(500).json({ error: 'Internal Server Error' });
}
if (usernameResults.length === 0 && emailResults.length === 0) {
// Both username and email are available
return res.status(200).json({ available: true });
} else {
// Either username or email is already taken
return res.status(400).json({ error: 'Username or email already taken' });
}
});
});
} catch (error) {
console.error('Error checking username and email:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/check-username', (req, res) => {
const { username } = req.body;
const checkUsernameQuery = 'SELECT * FROM users WHERE username = ?';
mysqlConnection.query(checkUsernameQuery, [username], (error, results) => {
if (error) {
console.error('Error checking username:', error);
res.status(500).json({ error: 'Internal Server Error' });
} else {
const isAvailable = results.length === 0;
res.json({ available: isAvailable });
}
});
});
// Assuming you have an instance of express named 'app'
app.post('/check-email', (req, res) => {
const { email } = req.body;
// Check if the email is already taken in the database
const checkEmailQuery = 'SELECT * FROM users WHERE email = ?';
mysqlConnection.query(checkEmailQuery, [email], (error, results) => {
if (error) {
console.error('Error checking email:', error);
res.status(500).json({ error: 'Internal Server Error' });
return;
}
// If results.length is greater than 0, it means the email is already taken
const isEmailAvailable = results.length === 0;
// Return a JSON response indicating whether the email is available or not
res.json({ available: isEmailAvailable });
});
});
app.get('/forgot-password', (req, res) => { app.get('/forgot-password', (req, res) => {
res.render('forgot-password'); // Assuming you have an EJS template for this res.render('forgot-password'); // Assuming you have an EJS template for this
}); });
@ -449,6 +548,9 @@ async function checkIfUserExists(username) {
}); });
}); });
} }
app.use(express.static('views')); app.use(express.static('views'));
app.listen(PORT, () => { app.listen(PORT, () => {

View File

@ -169,10 +169,12 @@ $(document).ready(function () {
$('#downloadButtonContainer').show(); $('#downloadButtonContainer').show();
}); });
}); });
$('#downloadButton').on('click', function () { $('#downloadButton').on('click', function () {
// Call the downloadExcel function with the allUsers data // Call the downloadExcel function with the allUsers data
downloadExcel(allUsers); downloadExcel(allUsers);
}); });
function downloadExcel(allUsers) { function downloadExcel(allUsers) {
if (allUsers && allUsers.length > 0) { if (allUsers && allUsers.length > 0) {
const workbook = new ExcelJS.Workbook(); const workbook = new ExcelJS.Workbook();
@ -234,6 +236,102 @@ $('#downloadButton').on('click', function () {
return true; return true;
} }
function resetFormFields() {
$('#name').val('');
$('#username').val('');
$('#email').val('');
$('#password').val('');
$('#confirmPassword').val('');
$('#jobTitle').val('');
}
$('#userForm').on('submit', function (e) {
e.preventDefault();
const name = $('#name').val();
const username = $('#username').val();
const email = $('#email').val();
const password = $('#password').val();
const confirmPassword = $('#confirmPassword').val();
const jobTitle = $('#jobTitle').val();
if (password !== confirmPassword) {
alert('Passwords do not match. Please enter the same password in both fields.');
return;
}
if (!isStrongPassword(password)) {
alert('Password does not meet complexity requirements. It must be at least 10 characters long and include at least one uppercase letter, one lowercase letter, one digit, and one symbol.');
return;
}
fetch('/createUser', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: name,
username: username,
email: email,
password: password,
jobTitle: jobTitle,
}),
})
.then(response => {
if (response.status === 201) {
// Status 201 indicates successful creation
return response.json();
} else {
return response.json().then(data => {
throw new Error(data.error || `HTTP error! Status: ${response.status}`);
});
}
})
.then(data => {
console.log('User registration success:', data);
alert('User registered successfully!');
resetFormFields();
})
.catch(error => {
console.error('User registration error:', error);
handleRegistrationError(error);
});
});
function handleRegistrationError(error) {
console.error('Registration error:', error); // Log the full error object for debugging
let errorMessage;
if (typeof error === 'string') {
errorMessage = error;
} else if (error instanceof Error) {
errorMessage = error.message;
} else if (error.response && error.response.data && error.response.data.error) {
errorMessage = error.response.data.error;
} else {
errorMessage = 'Unknown error';
}
if (errorMessage.includes('Username is already taken')) {
alert('Username is already taken. Please choose a different username.');
} else if (errorMessage.includes('Email is already in use')) {
alert('Email is already in use. Please choose a different email.');
} else if (errorMessage.includes('Password does not meet complexity requirements')) {
alert('Password does not meet complexity requirements. It must be at least 10 characters long and include at least one uppercase letter, one lowercase letter, one digit, and one symbol.');
} else if (errorMessage.includes('User registration failed')) {
alert('User registration failed. Please try again.');
} else {
alert(`Unknown error: ${errorMessage}`);
}
}
$('#resetPasswordForm').on('submit', function (e) { $('#resetPasswordForm').on('submit', function (e) {
e.preventDefault(); e.preventDefault();
@ -247,13 +345,13 @@ $('#downloadButton').on('click', function () {
// Validate passwords // Validate passwords
if (password !== confirmPassword) { if (password !== confirmPassword) {
alert('Passwords do not match. Please enter the same password in both fields.'); alert('Error: Passwords do not match. Please enter the same password in both fields.');
return; return;
} }
// Check if the new password meets complexity requirements // Check if the new password meets complexity requirements
if (!isStrongPassword(password)) { if (!isStrongPassword(password)) {
alert('Password does not meet complexity requirements. It must be at least 10 characters long and include at least one uppercase letter, one lowercase letter, one digit, and one symbol.'); alert('Error: Password does not meet complexity requirements. It must be at least 10 characters long and include at least one uppercase letter, one lowercase letter, one digit, and one symbol.');
return; return;
} }
@ -271,7 +369,9 @@ $('#downloadButton').on('click', function () {
}) })
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`); return response.text().then(errorText => {
throw new Error(`HTTP error! Status: ${response.status}, Error: ${errorText}`);
});
} }
return response.json(); return response.json();
}) })
@ -292,7 +392,7 @@ $('#downloadButton').on('click', function () {
.catch(error => { .catch(error => {
// Handle 404 error separately to show an alert // Handle 404 error separately to show an alert
if (error.message.includes('HTTP error! Status: 404')) { if (error.message.includes('HTTP error! Status: 404')) {
alert('User not found. Please enter a valid username.'); alert('Error: User not found. Please enter a valid username.');
} else { } else {
console.error('Fetch Error:', error); console.error('Fetch Error:', error);
} }