72 lines
1.6 KiB
JavaScript
72 lines
1.6 KiB
JavaScript
// static variables and imports
|
|
import express from "express";
|
|
import {
|
|
loginUser,
|
|
createUser,
|
|
updateUser,
|
|
deleteUser,
|
|
getAllUsers,
|
|
} from "../shared/database.js";
|
|
import dotenv from "dotenv";
|
|
import path from "path";
|
|
import axios from "axios";
|
|
import session from "express-session";
|
|
import { fileURLToPath } from "url";
|
|
const app = express();
|
|
dotenv.config();
|
|
const port = 4001;
|
|
|
|
app.use(express.json());
|
|
app.use(express.static("public"));
|
|
|
|
app.use(express.urlencoded({ extended: true }));
|
|
app.set("view engine", "ejs");
|
|
|
|
app.use(
|
|
session({
|
|
secret: "p0wP3asqAx1Ab0",
|
|
resave: false,
|
|
saveUninitialized: false,
|
|
cookie: { secure: false }, // Set to true if using HTTPS
|
|
})
|
|
);
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Server is running on http://localhost:${port}`);
|
|
});
|
|
|
|
// -- here comes the main code --
|
|
app.get("/", (req, res) => {
|
|
res.render("index.ejs", { error: null });
|
|
});
|
|
|
|
// login code
|
|
app.post("/login", async (req, res) => {
|
|
const { username, password } = req.body;
|
|
loginUser(username, password).then((result) => {
|
|
if (result.success === true) {
|
|
req.session.user = result.user;
|
|
res.render("userView.ejs", { user: result.user });
|
|
} else {
|
|
res.render("index.ejs", { error: result.message });
|
|
}
|
|
});
|
|
});
|
|
|
|
// logout code
|
|
app.get("/logout", (req, res) => {
|
|
req.session.destroy(() => {
|
|
res.redirect("/");
|
|
});
|
|
});
|
|
|
|
// error handling code
|
|
app.use((err, req, res, next) => {
|
|
// Log the error stack and send a generic error response
|
|
console.error(err.stack);
|
|
res.status(500).send("Something broke!");
|
|
});
|