Im a newbie currently working on a todo/tasks web app using node and express, im having a hard time to create a unique session for every user and storing the tasks for each user accordingly, for now i am trying to achieve this without authentication. for context, if you add any task anyone accessing the website will be able to see them. the code is for my app.js:
import express from "express";
import bodyParser from "body-parser";
import session from "express-session";
import mongoose from "mongoose";
import { default as connectMongoDBSession } from "connect-mongodb-session";
import { v4 as uuidv4 } from "uuid";
//* constants
const resetTime = 1000 * 60 * 60 * 24 * 30;
const app = express();
const port = process.env.PORT || 3000;
const sessionSecret = "UniqueSessionSecret";
const mongoURI = process.env.mongodb_URI;
const MongoDBStore = connectMongoDBSession(session);
mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const store = new MongoDBStore({
uri: mongoURI,
collection: "sessions",
expires: resetTime / 1000,
});
store.on("error", (error) => {
console.error(`MongoDBStore Error: ${error}`);
});
//* express
app.use(
session({
name: "tasks.sid",
secret: sessionSecret,
resave: false,
saveUninitialized: true,
store: store,
})
);
app.use("/public", express.static("public"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/", express.static("./node_modules/bootstrap/dist/"));
//* variables
//* app requsts
app.get("/", (req, res) => {
if (!req.session.userId) {
// Assign a unique identifier to the session
req.session.userId = uuidv4();
}
res.render("index.ejs", { dateAndDay, addedTasks, exist });
});
app.get("/work", (req, res) => {
res.render("work.ejs", { dateAndDay, addedWorkTasks, existWork });
});
app.post("/", (req, res) => {
if (addedTasks.includes(req.body["newNote"]) === false) {
if (req.body["newNote"] != "") {
exist = false;
addedTasks.unshift(req.body["newNote"]);
}
// } else {
// var exist = true;
}
res.render("index.ejs", { dateAndDay, addedTasks, exist });
waitFiveMinutes();
});
app.post("/work", (req, res) => {
if (addedWorkTasks.includes(req.body["newWorkNote"]) === false) {
if (req.body["newWorkNote"] != "") {
existWork = false;
addedWorkTasks.unshift(req.body["newWorkNote"]);
}
}
// else {
// existWork = true;
// }
res.render("work.ejs", { dateAndDay, addedWorkTasks, existWork });
waitFiveMinutesWork();
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
this is my latest commit, i remeoved unnessacry code that would take space for no use so if you want to check the full repo you can find it in the footer of the same web app: www.todowebapp.com




