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

Added Comments to Code #763

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# do not upload the package modules - our file would be too heavy
node_modules

# do not upload secret keys, risk of exposure
.env

# settings for when opening app in vscode
.vscode
2 changes: 2 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<!-- Allows people to use the code, and doesn't hold the developer liable for any issues -->

MIT License

Copyright (c) 2024 100devs
Expand Down
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
# Install

<!-- install packages and dependencies since .gitignore contains node_modules because we don't want to upload such heavy info-->
`npm install`

---

# Things to add

<!-- create and .env file and add the following -->
- Create a `.env` file in config folder and add the following as `key = value`
<!-- tell the server to listen at PORT 2121 -->
- PORT = 2121 (can be any port example: 3000)
<!-- connect to the mongoDB database -->
- DB_STRING = `your database URI`
<!-- connect to the cloudinary for media -->
- CLOUD_NAME = `your cloudinary cloud name`
- API_KEY = `your cloudinary api key`
- API_SECRET = `your cloudinary api secret`

---

# Run

<!--runs what ever is in package.json start AKA starts the server -->
`npm start`


<!-- Procfile is for Heroku hosting -->
1 change: 1 addition & 0 deletions config/database.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const mongoose = require("mongoose");

// configuration to connect to database using mongoose
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.DB_STRING, {
Expand Down
1 change: 1 addition & 0 deletions config/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const LocalStrategy = require("passport-local").Strategy;
const mongoose = require("mongoose");
const User = require("../models/User");

// Use passport with local strategy to authenticate users and the User model to talk to the database
module.exports = function (passport) {
passport.use(
new LocalStrategy({ usernameField: "email" }, (email, password, done) => {
Expand Down
8 changes: 8 additions & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const passport = require("passport");
const validator = require("validator");
const User = require("../models/User");

//If they are already logged in, take them to their profile when they try to click login in, if render the login page and give title value of Login
exports.getLogin = (req, res) => {
if (req.user) {
return res.redirect("/profile");
Expand All @@ -11,6 +12,7 @@ exports.getLogin = (req, res) => {
});
};

// Validators and display error message if not successful login. Checks to see if login info matches a user, if it does successfully login redirects to /profile
exports.postLogin = (req, res, next) => {
const validationErrors = [];
if (!validator.isEmail(req.body.email))
Expand Down Expand Up @@ -44,6 +46,7 @@ exports.postLogin = (req, res, next) => {
})(req, res, next);
};

// Destroys the session and the client is redirected to the home route
exports.logout = (req, res) => {
req.logout(() => {
console.log('User has logged out.')
Expand All @@ -56,6 +59,8 @@ exports.logout = (req, res) => {
});
};

// If user is already logged in, redirects to /profile page if user tries to signup
// If not signedup/logged in, renders a signup page
exports.getSignup = (req, res) => {
if (req.user) {
return res.redirect("/profile");
Expand All @@ -65,6 +70,9 @@ exports.getSignup = (req, res) => {
});
};

// Validations and errors
// Adds to the Users Collection using User Model and info from the req.body
// Checks to see if user doesn't already exist, if user already exists will redirect to /signup, if not adds a new document and redirects to /profile
exports.postSignup = (req, res, next) => {
const validationErrors = [];
if (!validator.isEmail(req.body.email))
Expand Down
1 change: 1 addition & 0 deletions controllers/home.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// on / route render index.ejs
module.exports = {
getIndex: (req, res) => {
res.render("index.ejs");
Expand Down
10 changes: 10 additions & 0 deletions controllers/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const cloudinary = require("../middleware/cloudinary");
const Post = require("../models/Post");

module.exports = {
// finds the Posts that matches the userId given by passport and renders profile.ejs with the posts info and the user info
//Only shows posts for that specific user id
getProfile: async (req, res) => {
try {
const posts = await Post.find({ user: req.user.id });
Expand All @@ -10,6 +12,8 @@ module.exports = {
console.log(err);
}
},
//get all the posts from the Posts collection and render in feed.ejs as posts
// Shows all posts by everyone
getFeed: async (req, res) => {
try {
const posts = await Post.find().sort({ createdAt: "desc" }).lean();
Expand All @@ -18,6 +22,7 @@ module.exports = {
console.log(err);
}
},
// Render a post.ejs with posts matching the post id requested
getPost: async (req, res) => {
try {
const post = await Post.findById(req.params.id);
Expand All @@ -26,11 +31,14 @@ module.exports = {
console.log(err);
}
},

//
createPost: async (req, res) => {
try {
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path);

//Create a new post using Post model with cloudinary ID and redirect to profile
await Post.create({
title: req.body.title,
image: result.secure_url,
Expand All @@ -45,6 +53,7 @@ module.exports = {
console.log(err);
}
},
//Find the post that matches the post id and increase the likes value by 1 then redirect to the post page
likePost: async (req, res) => {
try {
await Post.findOneAndUpdate(
Expand All @@ -68,6 +77,7 @@ module.exports = {
// Delete post from db
await Post.remove({ _id: req.params.id });
console.log("Deleted Post");
// redirect to user profile
res.redirect("/profile");
} catch (err) {
res.redirect("/profile");
Expand Down
5 changes: 5 additions & 0 deletions middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// If user is authenticated, do the next task which is go to the controller and do task
// If not go back to home screen
module.exports = {
ensureAuth: function (req, res, next) {
if (req.isAuthenticated()) {
Expand All @@ -6,6 +8,9 @@ module.exports = {
res.redirect("/");
}
},

// If user is authenticated, do the next task which is go to the controller and do task
// If not, the guest can go back to the dashboard
ensureGuest: function (req, res, next) {
if (!req.isAuthenticated()) {
return next();
Expand Down
2 changes: 2 additions & 0 deletions middleware/cloudinary.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const cloudinary = require("cloudinary").v2;

require("dotenv").config({ path: "./config/.env" });

// Cloduinary middle ware to configure to codinary
//does not need to be in config because we are using it as middleware
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
Expand Down
2 changes: 2 additions & 0 deletions middleware/multer.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// Use muelter for file upload from client
const multer = require("multer");
const path = require("path");

module.exports = multer({
storage: multer.diskStorage({}),
fileFilter: (req, file, cb) => {
let ext = path.extname(file.originalname);
// if file is not jpg or jpeg or png, run error
if (ext !== ".jpg" && ext !== ".jpeg" && ext !== ".png") {
cb(new Error("File type is not supported"), false);
return;
Expand Down
2 changes: 1 addition & 1 deletion models/Post.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const mongoose = require("mongoose");

// Post schema to talk to data base and includes coludinary id and image link and reference to User model for who created it.
const PostSchema = new mongoose.Schema({
title: {
type: String,
Expand Down
4 changes: 3 additions & 1 deletion models/User.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const bcrypt = require("bcrypt");
const mongoose = require("mongoose");

// Setting up Schema for Model
const UserSchema = new mongoose.Schema({
userName: { type: String, unique: true },
email: { type: String, unique: true },
Expand Down Expand Up @@ -28,7 +29,7 @@ UserSchema.pre("save", function save(next) {
});
});

// Helper method for validating user's password.
// Helper method for validating user's password for comparison

UserSchema.methods.comparePassword = function comparePassword(
candidatePassword,
Expand All @@ -39,4 +40,5 @@ UserSchema.methods.comparePassword = function comparePassword(
});
};

// Exporting out model to be used in controllers
module.exports = mongoose.model("User", UserSchema);
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 23 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,31 +1,53 @@
// List of packages used for the app, versions, dependencies,

{
"name": "binary-upload-boom",
"name": "binary-upload",
"version": "1.0.0",
"description": "100Devs Social Network",
// main file to start the server
"main": "server.js",
"scripts": {
//npm start = nodemon server.js
"start": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT",
// can separate into dev dependencies that only runs when developing and not in production ex: nodemon
"dependencies": {
// hash our passwords
"bcrypt": "^5.0.1",
// cdn for media
"cloudinary": "^1.25.1",
// used for storage of the session
"connect-mongo": "^3.2.0",
//creates .env file to store sensitve keys
"dotenv": "^8.2.0",
// Views templating language
"ejs": "^3.1.6",
//framework that prevents having to use basic node (lots of needing to know specifics of each request)
"express": "^4.17.1",
// show flash messages during login/signup
"express-flash": "^0.0.2",
// creates cookies on our browser so we can save the sessions into data bases
"express-session": "^1.17.1",
// allows form requests to be PUT and DELETE req
"method-override": "^3.0.0",
// connects to the db
"mongodb": "^3.6.5",
// Object data modeling library that abstracts lots of things from mongo client
"mongoose": "^5.12.3",
// morgan is the dev logger
"morgan": "^1.10.0",
// allows client to upload files
"multer": "^1.4.5-lts.1",
// allows the server to refresh without starting and stoping the server
"nodemon": "^2.0.7",
// needed for authentication
"passport": "^0.6.0",
// package is needed for local authentication
"passport-local": "^1.0.0",
// used for POST req for signup/login
"validator": "^13.6.0"
}
}
10 changes: 10 additions & 0 deletions routes/main.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
// Use express package
const express = require("express");
// Use express Router method to be able to direct to routers
const router = express.Router();
//Pathway to auth controller
const authController = require("../controllers/auth");
//Pathway to home Controller
const homeController = require("../controllers/home");
//Pathway to posts Controller
const postsController = require("../controllers/posts");
//Require the middleware for ensureAuth that will check to see if a user is logged in
const { ensureAuth, ensureGuest } = require("../middleware/auth");

//Main Routes - simplified for now
router.get("/", homeController.getIndex);
//ensureAuth makes sure a user is loggid in before the action in the controller
router.get("/profile", ensureAuth, postsController.getProfile);
router.get("/feed", ensureAuth, postsController.getFeed);

// simple routers
router.get("/login", authController.getLogin);
router.post("/login", authController.postLogin);
router.get("/logout", authController.logout);
router.get("/signup", authController.getSignup);
router.post("/signup", authController.postSignup);

//export the router info to the server.js file
module.exports = router;
9 changes: 9 additions & 0 deletions routes/posts.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
// Use express package
const express = require("express");
// Use express Router method to be able to direct to routers
const router = express.Router();
//Use multer to upload media from the client
const upload = require("../middleware/multer");
//Pathway to posts Controller
const postsController = require("../controllers/posts");
//Require the middleware for ensureAuth that will check to see if a user is logged in
const { ensureAuth, ensureGuest } = require("../middleware/auth");

//Post Routes - simplified for now
// with posts/:id (of post) make sure they are logged in and get the POST
router.get("/:id", ensureAuth, postsController.getPost);

//on posts/createPost upload a file using muelter and go to the postsController and run createPost
router.post("/createPost", upload.single("file"), postsController.createPost);

// simple routers
router.put("/likePost/:id", postsController.likePost);

router.delete("/deletePost/:id", postsController.deletePost);

//export the router info to the server.js file
module.exports = router;
Loading