Skip to content

Commit 3fdc0bc

Browse files
tanmayc07sahilambrerutu363
authored
Release 1.0 (#66)
* Test commit for sahildev * test commit for rutudev * Initial test commit for tanmaydev * Test commit * 💩 add authentication * 🗃️ Add scripts for /create and /list of blogs * 🗃️ Add scripts for /update and /delete of blogs * ➕ Add body-parser dependency * added landing login reg pages * 💄 Add create view * 🚧 Add create and landing view and backend code * 💫 Add logo * Merge rutudev * 🎨 Structure blog routes * 🚚 Restructure auth routes #4 * 🚚 Restructure auth routes #4 * 🚚 Restructure auth routes #4 * 👽 Add auth middleware for every blog crud operation #6 * 🗃️ Resolve deprecation warning * ✅ correct auth middleware * 💄 Change in Register and login page #5 * 🗃️ Generalize database name #10 * 🐛 Login bug resolve * 💄 Add tui editor in create view #3 * 🔧 password validate * 💩 Add script for create blog * 🚧 validations * ✨ Update create blog script * 🚧 validations * 🍻 Done validations #15 #12 * ✨ Render Blog on seperate route * ✨ Implement back button #18 * 📱 Login view and validations * 🔥 Remove a temporary file * 🐛 Fix UI bugs #18 #21 * 🐛 Fix footer in log and reg #21 * commit * 💄 Connect landing to auth pages * 💄 Error message styling in auth pages #28 * ✨ Add partial views for blog cards #2 * 🐛 Fix route and changed file name #30 * ✨ Add explore page * Changes Logout #32 * ⚡ redirects * 💩 Connect user and blog * Connect user and blog schemas * Iss33 (#36) * 📝 Add cover image and badges #33 * 📝 Add steps to run locally #33 * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * ♻️ Remove typo * 🐛 Fix login and redirect page bug * ⚡ Secret in .env * ♻️ Remove comments and extra code #37 * 🗃️ Add author field in blogSchema * 💄 Add author name on card #42 * ♻️ Redirect to explore after login * ✨ Explore page patch * ✨ Add functionality to create button * ✅ myblogs #45 * 🔨 removes myblog test #45 * ✨ Frontend my blogs #50 * 💄 update ui for frontend myblogs #50 * ✨ Add edit and delete functionality to blogs * 👽 Integrate mailchimp * ⚡ adds 404 page * ✨ Add navbar dropdown and avatar #55 * ➕ Add migrate-mongo dependency * 📝 Update documentation * 🐛 Patch * ♻️ Refactor API to get latest blogs first * 🔒 Add DB_URI in env Co-authored-by: sahilambre <[email protected]> Co-authored-by: Rutu <[email protected]> Co-authored-by: Rutu <[email protected]> Co-authored-by: Sahil Ambre <[email protected]>
1 parent 952e3da commit 3fdc0bc

File tree

80 files changed

+9159
-39
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

80 files changed

+9159
-39
lines changed

.env.sample

+2-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
PORT="Your PORT value"
1+
PORT="Your PORT value"
2+
JWT = "Your JWT secret"

README.md

+51-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,52 @@
1-
# A Blogging website built with Nodejs
1+
<p align="center">
2+
<img alt="cover-image" src="./public/img/coverImage.svg">
3+
</p>
4+
<p align="center">
5+
<img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed/tanmayc07/Blog-App?color=Blue">
26

3-
[![Generic badge](https://img.shields.io/badge/Status-In_Progress-green.svg)](https://shields.io/)
4-
[![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://github.com/Naereen/StrapDown.js/blob/master/LICENSE)
7+
<img alt="Github status" src="https://img.shields.io/badge/status-In Progress-brightgreen">
8+
9+
<img alt="Github status" src="https://img.shields.io/badge/Nodejs->=12.0.0-brightgreen">
10+
11+
<img alt="Github status" src="https://img.shields.io/badge/license-MIT-brightgreen">
12+
</p>
13+
<p>
14+
<h1 align="center">Think it. Write it</h1>
15+
<p align="center">A Blogging website built with Nodejs 🖋️</p>
16+
</p>
17+
18+
19+
20+
### **How to run code locally**
21+
22+
1. Clone the repository
23+
24+
2. Download all the **packages** and it's **dependencies**. Open the terminal and type
25+
26+
```bash
27+
npm install
28+
```
29+
30+
3. Create `.env` file and insert proper **key values** (refer `.env.sample`).
31+
32+
4. Install migrate-mongo globally
33+
34+
```bash
35+
npm install -g migrate-mongo
36+
```
37+
5. Migrate up
38+
39+
```bash
40+
migrate-mongo up
41+
```
42+
43+
6. To **start** the development server run
44+
45+
```bash
46+
npm run startDev
47+
```
48+
49+
50+
<!-- [![Generic badge](https://img.shields.io/badge/Status-In_Progress-green.svg)](https://shields.io/) -->
51+
52+
<!-- [![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://github.com/Naereen/StrapDown.js/blob/master/LICENSE) -->

app.js

+35-4
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,48 @@
11
require("dotenv").config();
2+
const routes = require("express").Router();
3+
const mongoose = require("mongoose");
24
const express = require("express");
3-
const routes = require("./routes");
4-
5+
const cors = require("cors");
6+
const bodyParser = require("body-parser");
7+
const blogRoutes = require("./routes/blogs/blogRoutes");
8+
const authRoutes = require("./routes/auths/authRoutes");
9+
const cookieParser = require("cookie-parser");
510
const PORT = process.env.PORT;
11+
const { requireAuth } = require("./middleware/authMiddleware");
12+
const Index = require("./routes/Index");
613
const app = express();
14+
const checkUser = require("./middleware/authMiddleware");
15+
16+
17+
app.use(express.static(__dirname + "./public"));
18+
app.use(express.json());
19+
app.post("/register",routes);
20+
app.use(authRoutes);
21+
app.set("view engine", "ejs");
22+
app.set("views", "./views");
723

24+
app.use(cookieParser());
25+
app.use(cors());
826
app.use(express.static(__dirname + "/public"));
9-
app.use("/create", routes);
10-
app.use("/", routes);
27+
app.use(bodyParser.urlencoded({ extended: true }));
28+
app.use(bodyParser.json());
1129

30+
app.use("/auth", authRoutes);
31+
app.use("/blogs", blogRoutes);
32+
app.use("/",Index);
33+
1234
app.set("views", "./views");
1335
app.set("view engine", "ejs");
1436

37+
//app.get("/auth/login", checkUser, (req, res) => {
38+
// res.render("register");
39+
//});
40+
41+
app.use((req, res, next) => {
42+
res.status(404).render("404page");
43+
});
44+
45+
1546
app.listen(PORT, () => {
1647
console.log(`Server started at port ${PORT}`);
1748
});

config/database.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
const mongoose = require("mongoose");
2-
mongoose.connect("mongodb://localhost:27017/blog", { useNewUrlParser: true });
2+
mongoose.connect(process.env.DB_URI, {
3+
useNewUrlParser: true,
4+
useUnifiedTopology: true,
5+
useFindAndModify: false,
6+
useCreateIndex: true,
7+
});
8+
9+
mongoose.set("returnOriginal", false);
310

411
const conn = mongoose.connection;
512

613
conn.on("connected", function () {
7-
console.log("Database is connected is successfully!");
14+
console.log("Database is connected successfully!");
815
});
916

1017
conn.on("disconnected", function () {

controllers/authControllers.js

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
var User = require("../models/user/User");
2+
const conn = require("../config/database");
3+
const bcrypt = require("bcryptjs");
4+
const jwt = require("jsonwebtoken");
5+
const checkUser = require("../middleware/authMiddleware");
6+
7+
const secret = process.env.JWT;
8+
9+
const handleErrors = (err) => {
10+
console.log(err.message);
11+
let errors = { email: "", password: "" };
12+
13+
// incorrect email
14+
if (err.message === "Incorrect Email") {
15+
errors.email = "That email is not registered";
16+
}
17+
18+
// incorrect password
19+
if (err.message === "Incorrect Password") {
20+
errors.password = "That password is incorrect";
21+
}
22+
if (
23+
err.message === "user validation failed: password: Minimum 6 characters"
24+
) {
25+
errors.password = "Minimum 6 characters required";
26+
}
27+
if (err.code === 11000) {
28+
errors.email = "That email is already taken";
29+
}
30+
31+
return errors;
32+
};
33+
34+
35+
const redirect = (req, res) => {
36+
res.redirect("/auth/login");
37+
};
38+
39+
40+
module.exports.register_get = (req, res) => {
41+
res.render("register");
42+
};
43+
44+
module.exports.login_get = (req, res) => {
45+
res.render("login");
46+
};
47+
48+
const maxAge = 3 * 24 * 60 * 60;
49+
50+
51+
const createToken = (id)=>{
52+
return jwt.sign({ id },secret,{
53+
expiresIn: maxAge
54+
});
55+
};
56+
57+
module.exports.register_post = async (req, res) => {
58+
const {
59+
firstname,
60+
lastname,
61+
email,
62+
username,
63+
password,
64+
gender,
65+
DOB,
66+
} = req.body;
67+
try {
68+
const user = await User.createUser({
69+
firstname,
70+
lastname,
71+
email,
72+
username,
73+
password,
74+
gender,
75+
DOB,
76+
});
77+
78+
res.status(200).json({});
79+
} catch (err) {
80+
const errors = handleErrors(err);
81+
82+
res.status(400).json({ errors });
83+
}
84+
};
85+
module.exports.login_post = async (req, res) => {
86+
const email = req.body.email;
87+
const password = req.body.password;
88+
89+
try {
90+
const user = await User.login(email, password);
91+
const token = createToken(user._id);
92+
res.cookie("jwt", token, { httpOnly: true, maxAge: maxAge * 1000 });
93+
res.status(200).json({ user: user._id });
94+
} catch (err) {
95+
const errors = handleErrors(err);
96+
res.status(400).json({ errors });
97+
}
98+
99+
};
100+
101+
module.exports.logout_get = (req, res) => {
102+
res.cookie('jwt', '', { maxAge: 1 });
103+
res.redirect('/');
104+
}
105+

controllers/blogcrud.controllers.js

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
const model = require("../config/database");
2+
const blogModel = require("../models/blogapi/crud");
3+
const userModel = require("../models/user/User");
4+
5+
module.exports = {
6+
createForm: function (req, res) {
7+
let user = {
8+
id: req.userid
9+
}
10+
res.render("create", {user:user});
11+
},
12+
createData: function (req, res) {
13+
const inputData = req.body;
14+
const userid = req.userid;
15+
userModel.getOneUser(userid, function(username){
16+
inputData.author = username
17+
blogModel.createBlog(req, inputData, function (data) {
18+
userModel.updateBlog(req, data, function (data) {
19+
res.json(data);
20+
});
21+
});
22+
})
23+
},
24+
listMine: function (req, res) {
25+
const inputData = req.body;
26+
const userid = req.userid;
27+
userModel.getOneUser(userid, function(author){
28+
inputData.author = author
29+
blogModel.listMine(author,function (data) {
30+
res.render("myBlogs", { data });
31+
});
32+
})
33+
},
34+
listAll: function (req, res) {
35+
blogModel.listAll(function (data) {
36+
res.render("explore", { data });
37+
});
38+
},
39+
listData: function (req, res) {
40+
const id = req.params.id
41+
blogModel.listBlog(id, function (data) {
42+
res.render("blog", { data });
43+
});
44+
},
45+
getUpdate: function(req, res){
46+
const id = req.params.id
47+
blogModel.listBlog(id, function(data){
48+
res.render("update", { data: JSON.stringify(data), blogid:req.params.id })
49+
})
50+
},
51+
updateData: function (req, res) {
52+
var inputData = req.body;
53+
var blogID = req.params.id;
54+
blogModel.updateBlog(inputData, blogID, function (data) {
55+
res.json(data);
56+
});
57+
},
58+
deleteData: function (req, res) {
59+
var blogID = req.params.id;
60+
blogModel.deleteBlog(blogID, function (data) {
61+
res.send(`Record deleted!`);
62+
});
63+
},
64+
};

controllers/index.controllers.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module.exports.Index = function (req, res) {
2-
res.render("home", { title: "Tanmay" });
2+
res.render("landing");
33
};

middleware/authMiddleware.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
const jwt = require('jsonwebtoken');
2+
const secret = process.env.JWT;
3+
const requireAuth = (req, res, next) => {
4+
const token = req.cookies.jwt;
5+
6+
// check json web token exists & is verified
7+
if (token) {
8+
jwt.verify(token,secret, (err, decodedToken) => {
9+
if (err) {
10+
console.log(err.message);
11+
res.redirect('/auth/login');
12+
} else {
13+
req.userid = decodedToken.id
14+
next();
15+
}
16+
});
17+
} else {
18+
res.redirect('/auth/login');
19+
}
20+
};
21+
22+
23+
module.exports = { requireAuth };

middleware/redirectMiddleware.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const jwt = require('jsonwebtoken');
2+
const secret = process.env.JWT;
3+
const checkUser = (req, res, next) => {
4+
const token = req.cookies.jwt;
5+
6+
// check json web token exists & is verified
7+
if (token) {
8+
jwt.verify(token,secret, (err, decodedToken) => {
9+
if (err) {
10+
console.log(err.message);
11+
} else {
12+
res.redirect('/blogs/explore');
13+
}
14+
});
15+
} else {
16+
next();
17+
}
18+
};
19+
20+
21+
22+
module.exports = { checkUser };

migrate-mongo-config.js

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// In this file you can configure migrate-mongo
2+
3+
const config = {
4+
mongodb: {
5+
// TODO Change (or review) the url to your MongoDB:
6+
url: "mongodb://localhost:27017/blog",
7+
8+
// TODO Change this to your database name:
9+
databaseName: "blog",
10+
11+
options: {
12+
useNewUrlParser: true, // removes a deprecation warning when connecting
13+
useUnifiedTopology: true, // removes a deprecating warning when connecting
14+
// connectTimeoutMS: 3600000, // increase connection timeout to 1 hour
15+
// socketTimeoutMS: 3600000, // increase socket timeout to 1 hour
16+
}
17+
},
18+
19+
// The migrations dir, can be an relative or absolute path. Only edit this when really necessary.
20+
migrationsDir: "migrations",
21+
22+
// The mongodb collection where the applied changes are stored. Only edit this when really necessary.
23+
changelogCollectionName: "changelog",
24+
25+
// The file extension to create migrations and search for in migration dir
26+
migrationFileExtension: ".js"
27+
};
28+
29+
// Return the config as a promise
30+
module.exports = config;

0 commit comments

Comments
 (0)