Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored app.js and created config file #39

Merged
merged 4 commits into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 67 additions & 83 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@
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");

Expand All @@ -27,67 +32,30 @@
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"));

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,
})
Dismissed Show dismissed Hide dismissed
);
app.use(flash());
// Initialize Passport and session middleware
require("./config/passportConfig");
app.use(passport.initialize());
app.use(passport.session());
//changes
Expand All @@ -98,7 +66,10 @@
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
}
});

Expand All @@ -124,12 +95,12 @@
})(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");
}
});
});
Expand All @@ -141,8 +112,11 @@

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) => {
Expand Down Expand Up @@ -177,7 +151,7 @@
username: username,
email: email,
password: hashedPassword,
fullName
fullName,
// Additional user profile fields can be added here
});

Expand All @@ -192,44 +166,54 @@
}
});

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();
Expand Down
17 changes: 17 additions & 0 deletions src/config/dbconfig.js
Original file line number Diff line number Diff line change
@@ -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;
41 changes: 41 additions & 0 deletions src/config/passportConfig.js
Original file line number Diff line number Diff line change
@@ -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);
});
});