Skip to content

Commit

Permalink
Merge branch 'main' into update
Browse files Browse the repository at this point in the history
  • Loading branch information
lilmow authored Oct 4, 2023
2 parents e2738f8 + 04838bc commit 1ab54ef
Show file tree
Hide file tree
Showing 10 changed files with 715 additions and 256 deletions.
282 changes: 282 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"mongodb": "^6.1.0",
"mongoose": "^7.5.3",
"morgan": "^1.10.0",
"nodemon": "^3.0.1",
"passport": "^0.6.0",
"passport-local": "^1.0.0",
"passport-local-mongoose": "^8.0.0"
Expand All @@ -23,6 +24,7 @@
"main": "src/app.js",
"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
Expand Down
49 changes: 49 additions & 0 deletions setup.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Project Setup

This guide will help you set up the project on your local machine.

## Step 1: Install Dependencies

First, you need to install the project dependencies. Run the following command in your terminal:

```bash
npm install
```

## Step 2: Set Up Environment Variables

There is an example.env.txt file in the project root. Create a new file named .env in the same location and copy the contents of example.env.txt into it.

In the .env file, you will find a placeholder for MONGODB_URL credential. Replace it with your actual credentials.

If you’re running MongoDB locally, your database link will look something like this:

```bash
mongodb://localhost:27017/mydatabase
```

If you’re using a cloud database service like MongoDB Atlas, your database link will be provided by the service.which will look something like this:

- replace the password with actual password

```bash
mongodb+srv://databasename:<password>@something.banc821.mongodb.net/
```

## Step 3: Start the Server

To start the server, run the following command:

```bash
npm run dev
```

Now, your server should be up and running!

## Step 4: Access the Server

You can access the server by typing http://localhost:<port_number> in your browser, where <port_number> is the port number on which your server is running. the default port is 3000:

```bash
http://localhost:3000
```
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 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");

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

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
Expand All @@ -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
}
});

Expand All @@ -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");
}
});
});
Expand All @@ -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) => {
Expand Down Expand Up @@ -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
});

Expand All @@ -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();
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);
});
});
Loading

0 comments on commit 1ab54ef

Please sign in to comment.