From 3f55ee5ed66af2314d6e00b2e41b3fbf3f4a2924 Mon Sep 17 00:00:00 2001 From: Dharansh Neema Date: Tue, 3 Oct 2023 02:00:06 +0530 Subject: [PATCH 1/4] Refactored app.js and created config file --- src/app.js | 150 ++++++++++++++++------------------- src/config/dbconfig.js | 17 ++++ src/config/passportConfig.js | 41 ++++++++++ 3 files changed, 125 insertions(+), 83 deletions(-) create mode 100644 src/config/dbconfig.js create mode 100644 src/config/passportConfig.js diff --git a/src/app.js b/src/app.js index 04a14d0..b1ceafd 100644 --- a/src/app.js +++ b/src/app.js @@ -12,7 +12,12 @@ const csrf = require("csurf"); const cookieParser = require("cookie-parser"); const mongoSanitize = require("express-mongo-sanitize"); const dotenv = require("dotenv"); +const path = require("path"); + +const dbConfig = require("./config/dbconfig"); dotenv.config(); +// Connect to MongoDB using the configuration +dbConfig(); const courseModel = require("./db/courseDB"); @@ -27,8 +32,9 @@ const limiter = rateLimit({ message: "Too many requests from this IP, please try again later.", }); +//Views folder should be accessible from anywhere.. +app.set("views", path.join(__dirname, "views")); app.set("view engine", "ejs"); -app.set("views", "src/views"); app.use(express.urlencoded({ extended: true })); app.use(morgan("dev")); @@ -36,58 +42,20 @@ app.use(mongoSanitize()); const addCSRF = require("./middlewares/addCSRF"); -// Connect to MongoDB using the configuration -mongoose - .connect(process.env.MONGODB_URL, { - useNewUrlParser: true, - useUnifiedTopology: true, - }) - .then(() => { - console.log("Connected to MongoDB"); - // Start your application logic here - }) - .catch((err) => { - console.error("Error connecting to MongoDB:", err); - process.exit(1); - }); - -passport.use( - new LocalStrategy(async (username, password, done) => { - try { - const user = await User.findOne({ username: username }); - if (!user) return done(null, false, { message: "Incorrect username." }); - const passwordMatch = await bcrypt.compare(password, user.password); - if (!passwordMatch) - return done(null, false, { message: "Incorrect password." }); - - return done(null, user); - } catch (err) { - return done(err); - } - }) -); - -passport.serializeUser((user, done) => { - done(null, user.id); -}); - -passport.deserializeUser((id, done) => { - User.findById(id) - .then((user) => { - done(null, user); - }) - .catch((err) => { - done(err); - }); -}); - +//Regular middleware app.use(cookieParser()); //app.use(csrf()); //app.use(addCSRF) app.use( - session({ secret: process.env.SECRET_KEY, resave: false, saveUninitialized: true }) + session({ + secret: process.env.SECRET_KEY, + resave: false, + saveUninitialized: true, + }) ); app.use(flash()); +// Initialize Passport and session middleware +require("./config/passportConfig"); app.use(passport.initialize()); app.use(passport.session()); //changes @@ -98,7 +66,10 @@ app.get("/login", limiter, csrfProtection, (req, res) => { if (req.isAuthenticated()) { return res.redirect("/"); } else { - res.render("login", { messages: req.flash("error"), csrfToken: req.csrfToken() }); // Pass flash messages to the template + res.render("login", { + messages: req.flash("error"), + csrfToken: req.csrfToken(), + }); // Pass flash messages to the template } }); @@ -124,12 +95,12 @@ app.post("/login", limiter, csrfProtection, (req, res, next) => { })(req, res, next); }); -app.get('/logout', limiter, (req, res) => { +app.get("/logout", limiter, (req, res) => { req.session.destroy(function (err) { if (err) { console.error("Error during logout:", err); } else { - res.redirect('/login'); + res.redirect("/login"); } }); }); @@ -141,8 +112,11 @@ app.get("/", isAuthenticated, (req, res) => { app.get("/register", (req, res) => { if (req.isAuthenticated()) return res.redirect("/"); - console.log(req.csrfToken()) - res.render("register", { messages: req.flash("error"), csrfToken: req.csrfToken() }); + console.log(req.csrfToken()); + res.render("register", { + messages: req.flash("error"), + csrfToken: req.csrfToken(), + }); }); app.post("/register", limiter, csrfProtection, async (req, res) => { @@ -177,7 +151,7 @@ app.post("/register", limiter, csrfProtection, async (req, res) => { username: username, email: email, password: hashedPassword, - fullName + fullName, // Additional user profile fields can be added here }); @@ -192,44 +166,54 @@ app.post("/register", limiter, csrfProtection, async (req, res) => { } }); -app.get('/profile', isAuthenticated, async (req, res) => { - res.render('profile', { user: req.user, messages: req.flash(), csrfToken: req.csrfToken() }); +app.get("/profile", isAuthenticated, async (req, res) => { + res.render("profile", { + user: req.user, + messages: req.flash(), + csrfToken: req.csrfToken(), + }); }); -app.post('/profile', limiter, isAuthenticated, csrfProtection, async (req, res) => { - /*if (!req.body._csrf || req.body._csrf !== req.csrfToken()) { +app.post( + "/profile", + limiter, + isAuthenticated, + csrfProtection, + async (req, res) => { + /*if (!req.body._csrf || req.body._csrf !== req.csrfToken()) { return res.status(403).send("CSRF token validation failed."); }*/ - const { fullName, avatarUrl, bio, location, website } = req.body; - - try { - // Find the user by their ID (you need to have the user ID stored in the session) - const userId = req.user._id; // Assuming you have a user object in the session - const user = await User.findById(userId); - - if (!user) { - // Handle the case where the user is not found - return res.status(404).send("User not found."); - } + const { fullName, avatarUrl, bio, location, website } = req.body; - // Update the user's profile fields - user.fullName = fullName; - user.avatarUrl = avatarUrl; - user.bio = bio; - user.location = location; - user.website = website; + try { + // Find the user by their ID (you need to have the user ID stored in the session) + const userId = req.user._id; // Assuming you have a user object in the session + const user = await User.findById(userId); - // Save the updated user profile - await user.save(); + if (!user) { + // Handle the case where the user is not found + return res.status(404).send("User not found."); + } - // Redirect to the user's profile page or any other desired page - return res.redirect("/profile"); - } catch (error) { - console.error("Error updating profile:", error); - // Handle the error, display an error message, or redirect to an error page - return res.status(500).send("Error updating profile."); + // Update the user's profile fields + user.fullName = fullName; + user.avatarUrl = avatarUrl; + user.bio = bio; + user.location = location; + user.website = website; + + // Save the updated user profile + await user.save(); + + // Redirect to the user's profile page or any other desired page + return res.redirect("/profile"); + } catch (error) { + console.error("Error updating profile:", error); + // Handle the error, display an error message, or redirect to an error page + return res.status(500).send("Error updating profile."); + } } -}); +); app.use("/courses", limiter, isAuthenticated, async function (req, res) { const courses = await courseModel.find(); diff --git a/src/config/dbconfig.js b/src/config/dbconfig.js new file mode 100644 index 0000000..6ac912a --- /dev/null +++ b/src/config/dbconfig.js @@ -0,0 +1,17 @@ +const mongoose = require("mongoose"); +function dbConfig() { + mongoose + .connect(process.env.MONGODB_URL, { + useNewUrlParser: true, + useUnifiedTopology: true, + }) + .then(() => { + console.log("Connected to MongoDB"); + // Start your application logic here + }) + .catch((err) => { + console.error("Error connecting to MongoDB:", err); + process.exit(1); + }); +} +module.exports = dbConfig; diff --git a/src/config/passportConfig.js b/src/config/passportConfig.js new file mode 100644 index 0000000..12d04ee --- /dev/null +++ b/src/config/passportConfig.js @@ -0,0 +1,41 @@ +const passport = require("passport"); +const LocalStrategy = require("passport-local").Strategy; +const bcrypt = require("bcrypt"); + +const User = require("../db/User"); + +passport.use( + new LocalStrategy(async (username, password, done) => { + try { + const user = await User.findOne({ username: username }); + + if (!user) { + return done(null, false, { message: "Incorrect username." }); + } + + const passwordMatch = await bcrypt.compare(password, user.password); + + if (!passwordMatch) { + return done(null, false, { message: "Incorrect password." }); + } + + return done(null, user); + } catch (err) { + return done(err); + } + }) +); + +passport.serializeUser((user, done) => { + done(null, user.id); +}); + +passport.deserializeUser((id, done) => { + User.findById(id) + .then((user) => { + done(null, user); + }) + .catch((err) => { + done(err); + }); +}); From dfaeffb9e329d530af6ca77067d53f1189443876 Mon Sep 17 00:00:00 2001 From: Dharansh Neema Date: Tue, 3 Oct 2023 02:33:15 +0530 Subject: [PATCH 2/4] Added readme file with set-up instruction --- src/readme.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/readme.md diff --git a/src/readme.md b/src/readme.md new file mode 100644 index 0000000..f429e0a --- /dev/null +++ b/src/readme.md @@ -0,0 +1,33 @@ +# Welcome to Course manager + +Want to contribute? Well your most welcome here is an Set-up instruction to help you out. + +## Setup Instructions + +### 1. Clone the repository: + +```git clone https://github.com/Artlfmj/course-manager.git + + cd course-manager +``` + +### 2. Install dependencies + +`npm install` + +### 3. Set-up .env + +`touch .env` +or make file named as .env and assign this varaibles in that + +``` +MONGODB_URL=mongodb://localhost:27017/ +SECRET_KEY= +``` + +### 4. Start the application + +`npm run` + +or +`node app.js` From 51c16a53aaad0b7d889c5dd01ad306dff9db3921 Mon Sep 17 00:00:00 2001 From: Dharansh Neema Date: Tue, 3 Oct 2023 02:35:27 +0530 Subject: [PATCH 3/4] Edited readme.md --- src/readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/readme.md b/src/readme.md index f429e0a..82f5e88 100644 --- a/src/readme.md +++ b/src/readme.md @@ -6,8 +6,8 @@ Want to contribute? Well your most welcome here is an Set-up instruction to help ### 1. Clone the repository: -```git clone https://github.com/Artlfmj/course-manager.git - +``` + git clone https://github.com/Artlfmj/course-manager.git cd course-manager ``` From 738a2b141be4b2652632d3e76664331dd27b7415 Mon Sep 17 00:00:00 2001 From: Dharansh Neema Date: Tue, 3 Oct 2023 11:05:51 +0530 Subject: [PATCH 4/4] Deleted readme file as requested. --- src/readme.md | 33 --------------------------------- 1 file changed, 33 deletions(-) delete mode 100644 src/readme.md diff --git a/src/readme.md b/src/readme.md deleted file mode 100644 index 82f5e88..0000000 --- a/src/readme.md +++ /dev/null @@ -1,33 +0,0 @@ -# Welcome to Course manager - -Want to contribute? Well your most welcome here is an Set-up instruction to help you out. - -## Setup Instructions - -### 1. Clone the repository: - -``` - git clone https://github.com/Artlfmj/course-manager.git - cd course-manager -``` - -### 2. Install dependencies - -`npm install` - -### 3. Set-up .env - -`touch .env` -or make file named as .env and assign this varaibles in that - -``` -MONGODB_URL=mongodb://localhost:27017/ -SECRET_KEY= -``` - -### 4. Start the application - -`npm run` - -or -`node app.js`