Fixed signup bug
This commit is contained in:
@@ -1,42 +1,42 @@
|
|||||||
const db = require("../utils/database");
|
const db = require("../utils/database");
|
||||||
|
|
||||||
exports.addToFavorite = (req, res) => {
|
exports.addToFavorite = async (req, res) => {
|
||||||
const { userID, productsID } = req.body;
|
const { userID, productsID } = req.body;
|
||||||
|
|
||||||
// Use parameterized query to prevent SQL injection
|
try {
|
||||||
db.execute(
|
// Use parameterized query to prevent SQL injection
|
||||||
"INSERT INTO Favorites (UserID, ProductID) VALUES (?, ?)",
|
const [result] = await db.execute(
|
||||||
[userID, productsID],
|
"INSERT INTO Favorites (UserID, ProductID) VALUES (?, ?)",
|
||||||
(err, result) => {
|
[userID, productsID]
|
||||||
if (err) {
|
);
|
||||||
console.error("Error adding favorite product:", err);
|
|
||||||
return res.json({ error: "Could not add favorite product" });
|
res.json({
|
||||||
}
|
success: true,
|
||||||
res.json({
|
message: "Product added to favorites successfully",
|
||||||
success: true,
|
});
|
||||||
message: "Product added to favorites successfully",
|
} catch (error) {
|
||||||
});
|
console.error("Error adding favorite product:", error);
|
||||||
}
|
return res.json({ error: "Could not add favorite product" });
|
||||||
);
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
//Get all products
|
//Get all products
|
||||||
exports.getAllProducts = (req, res) => {
|
exports.getAllProducts = async (req, res) => {
|
||||||
const query = "SELECT * FROM Product";
|
try {
|
||||||
db.execute(query, (err, data) => {
|
const [data, fields] = await db.execute("SELECT * FROM Product");
|
||||||
if (err) {
|
|
||||||
console.error("Error finding user:", err);
|
|
||||||
return res.status(500).json({
|
|
||||||
found: false,
|
|
||||||
error: "Database error occurred",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
res.json({
|
res.json({
|
||||||
success: true,
|
success: true,
|
||||||
message: "Product added to favorites successfully",
|
message: "Product added to favorites successfully",
|
||||||
data,
|
data,
|
||||||
});
|
});
|
||||||
});
|
} catch (error) {
|
||||||
|
console.error("Error finding user:", error);
|
||||||
|
return res.status(500).json({
|
||||||
|
found: false,
|
||||||
|
error: "Database error occurred",
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// db_con.query(
|
// db_con.query(
|
||||||
|
|||||||
@@ -17,58 +17,39 @@ exports.sendVerificationCode = async (req, res) => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Check if email already exists in verification table
|
// Check if email already exists in verification table
|
||||||
db.execute(
|
const [results, fields] = await db.execute(
|
||||||
"SELECT * FROM AuthVerification WHERE Email = ?",
|
"SELECT * FROM AuthVerification WHERE Email = ?",
|
||||||
[email],
|
[email]
|
||||||
async (err, results) => {
|
|
||||||
if (err) {
|
|
||||||
console.error("Database error:", err);
|
|
||||||
return res.status(500).json({ error: "Database error" });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (results.length > 0) {
|
|
||||||
// Update existing record
|
|
||||||
db.execute(
|
|
||||||
`UPDATE AuthVerification SET VerificationCode = ?, Authenticated = FALSE, Date = CURRENT_TIMESTAMP
|
|
||||||
WHERE Email = ?`,
|
|
||||||
[verificationCode, email],
|
|
||||||
async (err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error("Database error:", err);
|
|
||||||
return res.status(500).json({ error: "Database error" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send email and respond
|
|
||||||
await sendVerificationEmail(email, verificationCode);
|
|
||||||
res.json({ success: true, message: "Verification code sent" });
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
// Insert new record
|
|
||||||
db.execute(
|
|
||||||
"INSERT INTO AuthVerification (Email, VerificationCode, Authenticated) VALUES (?, ?, FALSE)",
|
|
||||||
[email, verificationCode],
|
|
||||||
async (err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error("Database error:", err);
|
|
||||||
return res.status(500).json({ error: "Database error" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send email and respond
|
|
||||||
await sendVerificationEmail(email, verificationCode);
|
|
||||||
res.json({ success: true, message: "Verification code sent" });
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (results.length > 0) {
|
||||||
|
// Update existing record
|
||||||
|
const [result] = await db.execute(
|
||||||
|
`UPDATE AuthVerification SET VerificationCode = ?, Authenticated = FALSE, Date = CURRENT_TIMESTAMP
|
||||||
|
WHERE Email = ?`,
|
||||||
|
[verificationCode, email]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Send email and respond
|
||||||
|
await sendVerificationEmail(email, verificationCode);
|
||||||
|
res.json({ success: true, message: "Verification code sent" });
|
||||||
|
} else {
|
||||||
|
// Insert new record
|
||||||
|
const [result] = await db.execute(
|
||||||
|
"INSERT INTO AuthVerification (Email, VerificationCode, Authenticated) VALUES (?, ?, FALSE)",
|
||||||
|
[email, verificationCode]
|
||||||
|
);
|
||||||
|
// Send email and respond
|
||||||
|
await sendVerificationEmail(email, verificationCode);
|
||||||
|
res.json({ success: true, message: "Verification code sent" });
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error:", error);
|
console.error("Error:", error);
|
||||||
res.status(500).json({ error: "Server error" });
|
res.status(500).json({ error: "Server error" });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.verifyCode = (req, res) => {
|
exports.verifyCode = async (req, res) => {
|
||||||
const { email, code } = req.body;
|
const { email, code } = req.body;
|
||||||
|
|
||||||
if (!email || !code) {
|
if (!email || !code) {
|
||||||
@@ -77,119 +58,93 @@ exports.verifyCode = (req, res) => {
|
|||||||
|
|
||||||
console.log(`Attempting to verify code for ${email}: ${code}`);
|
console.log(`Attempting to verify code for ${email}: ${code}`);
|
||||||
|
|
||||||
// Check verification code
|
try {
|
||||||
db.execute(
|
// Check verification code
|
||||||
"SELECT * FROM AuthVerification WHERE Email = ? AND VerificationCode = ? AND Authenticated = 0 AND Date > DATE_SUB(NOW(), INTERVAL 15 MINUTE)",
|
const [results, fields] = await db.execute(
|
||||||
[email, code],
|
"SELECT * FROM AuthVerification WHERE Email = ? AND VerificationCode = ? AND Authenticated = 0 AND Date > DATE_SUB(NOW(), INTERVAL 15 MINUTE)",
|
||||||
(err, results) => {
|
[email, code]
|
||||||
if (err) {
|
);
|
||||||
console.error("Database error:", err);
|
if (results.length === 0) {
|
||||||
return res.status(500).json({ error: "Database error" });
|
console.log(`Invalid or expired verification code for email ${email}`);
|
||||||
}
|
return res
|
||||||
|
.status(400)
|
||||||
if (results.length === 0) {
|
.json({ error: "Invalid or expired verification code" });
|
||||||
console.log(`Invalid or expired verification code for email ${email}`);
|
|
||||||
return res
|
|
||||||
.status(400)
|
|
||||||
.json({ error: "Invalid or expired verification code" });
|
|
||||||
}
|
|
||||||
|
|
||||||
const userId = results[0].UserID;
|
|
||||||
|
|
||||||
// Mark as authenticated
|
|
||||||
db.execute(
|
|
||||||
"UPDATE AuthVerification SET Authenticated = TRUE WHERE Email = ?",
|
|
||||||
[email],
|
|
||||||
(err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error("Database error:", err);
|
|
||||||
return res.status(500).json({ error: "Database error" });
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`Email ${email} successfully verified`);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
success: true,
|
|
||||||
message: "Verification successful",
|
|
||||||
userId,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
);
|
|
||||||
|
const userId = results[0].UserID;
|
||||||
|
|
||||||
|
// Mark as authenticated
|
||||||
|
const [result] = await db.execute(
|
||||||
|
"UPDATE AuthVerification SET Authenticated = TRUE WHERE Email = ?",
|
||||||
|
[email]
|
||||||
|
);
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
message: "Verification successful",
|
||||||
|
userId,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error: ", error);
|
||||||
|
res.status(500).json({ error: "Database error!" });
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.completeSignUp = (req, res) => {
|
exports.completeSignUp = async (req, res) => {
|
||||||
const data = req.body;
|
const data = req.body;
|
||||||
|
|
||||||
db.execute(
|
try {
|
||||||
`SELECT * FROM AuthVerification WHERE Email = '${data.email}' AND Authenticated = 1;`,
|
const [results, fields] = await db.execute(
|
||||||
(err, results) => {
|
`SELECT * FROM AuthVerification WHERE Email = ? AND Authenticated = 1;`,
|
||||||
if (err) {
|
[data.email]
|
||||||
console.error("Database error:", err);
|
);
|
||||||
return res.status(500).json({ error: "Database error" });
|
|
||||||
}
|
|
||||||
if (results.length === 0) {
|
|
||||||
return res.status(400).json({ error: "Email not verified" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the user
|
if (results.length === 0) {
|
||||||
db.execute(
|
return res.status(400).json({ error: "Email not verified" });
|
||||||
`INSERT INTO User (Name, Email, UCID, Password, Phone, Address)
|
|
||||||
VALUES ('${data.name}', '${data.email}', '${data.UCID}', '${data.password}', '${data.phone}', '${data.address}')`,
|
|
||||||
(err, result) => {
|
|
||||||
if (err) {
|
|
||||||
console.error("Error creating user:", err);
|
|
||||||
return res.status(500).json({ error: "Could not create user" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Insert role using the user's ID
|
|
||||||
db.execute(
|
|
||||||
`INSERT INTO UserRole (UserID, Client, Admin)
|
|
||||||
VALUES (LAST_INSERT_ID(), ${data.client || true}, ${
|
|
||||||
data.admin || false
|
|
||||||
})`,
|
|
||||||
(roleErr) => {
|
|
||||||
if (roleErr) {
|
|
||||||
console.error("Error creating role:", roleErr);
|
|
||||||
return res.status(500).json({ error: "Could not create role" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete verification record
|
|
||||||
db.execute(
|
|
||||||
`DELETE FROM AuthVerification WHERE Email = '${data.email}'`,
|
|
||||||
(deleteErr) => {
|
|
||||||
if (deleteErr) {
|
|
||||||
console.error("Error deleting verification:", deleteErr);
|
|
||||||
}
|
|
||||||
res.json({
|
|
||||||
success: true,
|
|
||||||
message: "User registration completed successfully",
|
|
||||||
name: data.name,
|
|
||||||
email: data.email,
|
|
||||||
UCID: data.UCID,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
);
|
|
||||||
|
// Create the user
|
||||||
|
const [createResult] = await db.execute(
|
||||||
|
`INSERT INTO User (Name, Email, UCID, Password, Phone, Address)
|
||||||
|
VALUES ('${data.name}', '${data.email}', '${data.UCID}', '${data.password}', '${data.phone}', '${data.address}')`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Insert role using the user's ID
|
||||||
|
const [insertResult] = await db.execute(
|
||||||
|
`INSERT INTO UserRole (UserID, Client, Admin)
|
||||||
|
VALUES (LAST_INSERT_ID(), ${data.client || true}, ${
|
||||||
|
data.admin || false
|
||||||
|
})`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Delete verification record
|
||||||
|
const [deleteResult] = await db.execute(
|
||||||
|
`DELETE FROM AuthVerification WHERE Email = '${data.email}'`
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
message: "User registration completed successfully",
|
||||||
|
name: data.name,
|
||||||
|
email: data.email,
|
||||||
|
UCID: data.UCID,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.log("Error: ", error);
|
||||||
|
res.status(500).json({ error: "Database error!" });
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.getAllUser = (req, res) => {
|
exports.getAllUser = async (req, res) => {
|
||||||
db.execute("SELECT * FROM User;", (err, data) => {
|
try {
|
||||||
if (err) {
|
const [users, fields] = await db.execute("SELECT * FROM User;");
|
||||||
console.error("Errors: ", err);
|
res.json({ Users: users });
|
||||||
return res.status(500).json({ error: "\nCould not fetch users!" });
|
} catch (error) {
|
||||||
}
|
console.error("Errors: ", error);
|
||||||
res.json({ Users: data });
|
return res.status(500).json({ error: "\nCould not fetch users!" });
|
||||||
});
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.findUserByEmail = (req, res) => {
|
exports.findUserByEmail = async (req, res) => {
|
||||||
const { email } = req.body;
|
const { email } = req.body;
|
||||||
|
|
||||||
// Input validation
|
// Input validation
|
||||||
@@ -200,16 +155,10 @@ exports.findUserByEmail = (req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Query to find user with matching email and password
|
try {
|
||||||
const query = "SELECT * FROM User WHERE email = ?";
|
// Query to find user with matching email and password
|
||||||
db.execute(query, [email], (err, data) => {
|
const query = "SELECT * FROM User WHERE email = ?";
|
||||||
if (err) {
|
const [data, fields] = await db.execute(query, [email]);
|
||||||
console.error("Error finding user:", err);
|
|
||||||
return res.status(500).json({
|
|
||||||
found: false,
|
|
||||||
error: "Database error occurred",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if user was found
|
// Check if user was found
|
||||||
if (data && data.length > 0) {
|
if (data && data.length > 0) {
|
||||||
@@ -235,10 +184,16 @@ exports.findUserByEmail = (req, res) => {
|
|||||||
error: "Invalid email or password",
|
error: "Invalid email or password",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
} catch (error) {
|
||||||
|
console.error("Error finding user:", error);
|
||||||
|
return res.status(500).json({
|
||||||
|
found: false,
|
||||||
|
error: "Database error occurred",
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.updateUser = (req, res) => {
|
exports.updateUser = async (req, res) => {
|
||||||
const { userId, ...updateData } = req.body;
|
const { userId, ...updateData } = req.body;
|
||||||
|
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
@@ -264,48 +219,45 @@ exports.updateUser = (req, res) => {
|
|||||||
// Add userId to values array
|
// Add userId to values array
|
||||||
values.push(userId);
|
values.push(userId);
|
||||||
|
|
||||||
const query = `UPDATE User SET ${updateFields.join(", ")} WHERE UserID = ?`;
|
try {
|
||||||
|
const query = `UPDATE User SET ${updateFields.join(", ")} WHERE UserID = ?`;
|
||||||
db.execute(query, values, (err, result) => {
|
const [updateResult] = await db.execute(query, values);
|
||||||
if (err) {
|
if (updateResult.affectedRows === 0) {
|
||||||
console.error("Error updating user:", err);
|
|
||||||
return res.status(500).json({ error: "Could not update user" });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.affectedRows === 0) {
|
|
||||||
return res.status(404).json({ error: "User not found" });
|
return res.status(404).json({ error: "User not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ success: true, message: "User updated successfully" });
|
res.json({ success: true, message: "User updated successfully" });
|
||||||
});
|
} catch (error) {
|
||||||
|
console.error("Error updating user:", error);
|
||||||
|
return res.status(500).json({ error: "Could not update user" });
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.deleteUser = (req, res) => {
|
exports.deleteUser = async (req, res) => {
|
||||||
const { userId } = req.body;
|
const { userId } = req.body;
|
||||||
|
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
return res.status(400).json({ error: "User ID is required" });
|
return res.status(400).json({ error: "User ID is required" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete from UserRole first (assuming foreign key constraint)
|
try {
|
||||||
db.execute("DELETE FROM UserRole WHERE UserID = ?", [userId], (err) => {
|
// Delete from UserRole first (assuming foreign key constraint)
|
||||||
if (err) {
|
const [result1] = await db.execute(
|
||||||
console.error("Error deleting user role:", err);
|
"DELETE FROM UserRole WHERE UserID = ?",
|
||||||
return res.status(500).json({ error: "Could not delete user role" });
|
[userId]
|
||||||
}
|
);
|
||||||
|
|
||||||
// Then delete from User table
|
// Then delete from User table
|
||||||
db.execute("DELETE FROM User WHERE UserID = ?", [userId], (err, result) => {
|
const [result2] = await db.execute("DELETE FROM User WHERE UserID = ?", [
|
||||||
if (err) {
|
userId,
|
||||||
console.error("Error deleting user:", err);
|
]);
|
||||||
return res.status(500).json({ error: "Could not delete user" });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.affectedRows === 0) {
|
if (result2.affectedRows === 0) {
|
||||||
return res.status(404).json({ error: "User not found" });
|
return res.status(404).json({ error: "User not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ success: true, message: "User deleted successfully" });
|
res.json({ success: true, message: "User deleted successfully" });
|
||||||
});
|
} catch (error) {
|
||||||
});
|
console.error("Error: ", error);
|
||||||
|
return res.status(500).json({ error: "Could not delete user!" });
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
const mysql = require("mysql2");
|
const mysql = require("mysql2");
|
||||||
|
|
||||||
//Create a pool of connection to allow multiple query happen at the same time
|
//Create a pool of connections to allow multiple query happen at the same time
|
||||||
const pool = mysql.createPool({
|
const pool = mysql.createPool({
|
||||||
host: "localhost",
|
host: "localhost",
|
||||||
user: "root",
|
user: "root",
|
||||||
@@ -8,4 +8,5 @@ const pool = mysql.createPool({
|
|||||||
password: "12345678",
|
password: "12345678",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
//Export a promise for promise-based query
|
||||||
module.exports = pool.promise();
|
module.exports = pool.promise();
|
||||||
|
|||||||
Reference in New Issue
Block a user