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); + }); +});