feat: add getAllUsers function and integrate user fetching in dashboard

This commit is contained in:
2025-06-30 20:23:08 +02:00
parent c165a0f71b
commit 0bae4d3c01
3 changed files with 104 additions and 1 deletions

View File

@@ -4,7 +4,13 @@ const app = express();
const port = 4000;
// Importing database functions for user operations
import { loginUser, createUser, updateUser, deleteUser } from "./database.js";
import {
loginUser,
createUser,
updateUser,
deleteUser,
getAllUsers,
} from "./database.js";
// Middleware to parse URL-encoded bodies (form submissions)
app.use(express.urlencoded({ extended: true }));
@@ -39,9 +45,23 @@ app.get("/", (req, res) => {
// Variable to keep track of the latest logged-in user
let latestUser;
let response;
// static function to get all users
function allUsers() {
getAllUsers().then((resultFromFunc) => {
if (resultFromFunc.success) {
response = resultFromFunc.result;
} else {
response = resultFromFunc.result;
}
});
}
// Route to handle user login
app.post("/login", (req, res) => {
allUsers();
// Attempt to log in the user with provided credentials
loginUser(req.body.username, req.body.password).then((result) => {
if (result.success) {
@@ -51,6 +71,7 @@ app.post("/login", (req, res) => {
newLink: `/dashboard/${result.user.id}`,
alert: null,
success: null,
users: response,
});
latestUser = result;
} else {
@@ -77,12 +98,22 @@ app.post(["/createUser", "/updateUser", "/deleteUser"], (req, res) => {
if (latestUser && req.body.username !== latestUser.user.username) {
funcName = deleteUser;
} else {
let response;
getAllUsers().then((resultFromFunc) => {
if (resultFromFunc.success) {
response = resultFromFunc.result;
} else {
response = resultFromFunc.result;
}
});
// Render dashboard with alert if trying to delete logged-in user
res.status(400).render("dashboard.ejs", {
sqlResult: latestUser,
newLink: latestUser ? `/dashboard/${latestUser.id}` : "#",
alert: "Cannot delete the currently logged-in user!",
success: null,
users: response,
});
return;
}
@@ -100,20 +131,41 @@ app.post(["/createUser", "/updateUser", "/deleteUser"], (req, res) => {
req.body.email
).then((result) => {
if (result.success === true) {
let response;
getAllUsers().then((resultFromFunc) => {
if (resultFromFunc.success) {
response = resultFromFunc.result;
} else {
response = resultFromFunc.result;
}
});
// On success, render dashboard with success message
res.status(201).render("dashboard.ejs", {
sqlResult: latestUser,
newLink: `/dashboard/${latestUser.id}`,
alert: null,
success: "User action successful!",
users: response,
});
} else {
let response;
getAllUsers().then((resultFromFunc) => {
if (resultFromFunc.success) {
response = resultFromFunc.result;
} else {
response = resultFromFunc.result;
}
});
// On failure, render dashboard with alert
res.status(400).render("dashboard.ejs", {
sqlResult: latestUser,
newLink: `/dashboard/${latestUser.id}`,
alert: "User action failed!",
success: null,
users: response,
});
}
});