Skip to content

Commit c0551ae

Browse files
author
DEVfancybear
committed
luu tru
0 parents  commit c0551ae

22 files changed

+3672
-0
lines changed

.env

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
PORT=5000
2+
MONGODB_URL=mongodb://localhost/simple-blog
3+
SECRET=mysecret

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

config/passport.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const passport = require('passport')
2+
const localStrategy = require('passport-local').Strategy
3+
const User = require('../models/User')
4+
5+
module.exports = function (app) {
6+
app.use(passport.initialize())
7+
app.use(passport.session())
8+
9+
passport.serializeUser((user, done) => { done(null, user.id) })
10+
passport.deserializeUser((id, done) => {
11+
User.findById(id, (err, user) => {
12+
done(err, user)
13+
})
14+
})
15+
16+
passport.use(new localStrategy(function (username, password, done) {
17+
User.findOne({ username }, (err, user) => {
18+
if (err) return done(err)
19+
if (!user) return done(null, false, { message: 'User not found'})
20+
21+
user.comparePassword(password, (err, isMatch) => {
22+
if (err) return done(null, { message: 'Something went wrong'})
23+
if (!isMatch) return done(null, false,{ message: 'Invalid password'})
24+
return done(null, user)
25+
})
26+
})
27+
}))
28+
}

index.js

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// modules
2+
const express = require('express')
3+
const dotenv = require('dotenv')
4+
const mongoose = require('mongoose')
5+
const bodyParser = require('body-parser')
6+
const flash = require('connect-flash')
7+
const session = require('express-session')
8+
9+
// routes
10+
const indexRoutes = require('./routes/index')
11+
const postRoutes = require('./routes/post')
12+
const commentRoutes = require('./routes/comment')
13+
// setup the environment
14+
dotenv.config()
15+
16+
// connect database
17+
mongoose.connect(process.env.MONGODB_URL, { useNewUrlParser: true })
18+
.then(() => console.log('Mongodb connected'))
19+
20+
// create app
21+
const app = express()
22+
23+
// configuration ejs
24+
app.set('view engine', 'ejs')
25+
26+
// setup public folder
27+
app.use(express.static('public'))
28+
// middlewares
29+
app.use(bodyParser.json())
30+
app.use(bodyParser.urlencoded({ extended: false }))
31+
app.use(session({
32+
secret: process.env.SECRET,
33+
resave: false,
34+
saveUninitialized: false
35+
}))
36+
app.use(flash())
37+
38+
// setup passport
39+
require('./config/passport')(app)
40+
41+
// custom middeware
42+
app.use((req, res, next) => {
43+
res.locals.currentUser = req.user;
44+
res.locals.error = req.flash('error')
45+
res.locals.success = req.flash('success')
46+
next()
47+
})
48+
49+
50+
// setup routes
51+
app.use('/', indexRoutes)
52+
app.use('/post', postRoutes)
53+
app.use('/post/:id/comments', commentRoutes)
54+
55+
const PORT = process.env.PORT || 5000
56+
57+
// run server
58+
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`))

middleware/index.js

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
const Post = require('../models/Post')
2+
const Comment = require('../models/Comment')
3+
4+
exports.isLoggedIn = (req, res, next) => {
5+
if (req.isAuthenticated()) {
6+
next()
7+
} else {
8+
req.flash('error', 'You must be logged')
9+
res.redirect('/login')
10+
}
11+
}
12+
13+
// check ownership
14+
exports.isOwnerPost = async (req, res, next) => {
15+
if (req.isAuthenticated()) {
16+
try {
17+
// find post by id
18+
const post = await Post.findById(req.params.id)
19+
20+
if (!post) {
21+
// if not found the post
22+
req.flash('error', 'Post not found')
23+
return res.redirect('back')
24+
} else {
25+
// check ownership
26+
if (post.userId.equals(req.user._id)) {
27+
// same ids
28+
next()
29+
} else {
30+
// not same ids
31+
req.flash('error', "You don't have permission")
32+
return res.redirect('back')
33+
}
34+
}
35+
} catch (err) {
36+
req.flash('error', 'Something went wrong')
37+
return res.redirect('back')
38+
}
39+
} else {
40+
req.flash('error', 'You must be logged in')
41+
res.redirect('back')
42+
}
43+
}
44+
45+
exports.checkOwnershipComment = async (req, res, next) => {
46+
if (req.isAuthenticated()) {
47+
try {
48+
// find post and comment
49+
const post = await Post.findById(req.params.id)
50+
const comment = await Comment.findById(req.params.commentId)
51+
// not found comment or post
52+
if (!comment || !post) {
53+
req.flash('error', 'Something went wrong')
54+
return res.redirect('back')
55+
}
56+
// check ownership of comment
57+
if (comment.author.id.equals(req.user._id)) {
58+
next()
59+
} else {
60+
// dont have permisson
61+
req.flash('error', "You don't have permission")
62+
return res.redirect('back')
63+
}
64+
} catch (err) {
65+
console.log(err)
66+
return res.redirect('back')
67+
}
68+
} else {
69+
req.flash('error', 'You must be logged in')
70+
return res.redirect('back')
71+
}
72+
}

models/Comment.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const mongoose = require('mongoose')
2+
const Schema = mongoose.Schema
3+
4+
5+
const commentSchema = new Schema({
6+
text: {
7+
type: String,
8+
required: true
9+
},
10+
author: {
11+
id: {
12+
type: Schema.Types.ObjectId,
13+
ref: 'User'
14+
},
15+
username: String
16+
},
17+
createdAt: {
18+
type: Date,
19+
default: Date.now
20+
}
21+
})
22+
23+
24+
module.exports = mongoose.model('Comment', commentSchema)

models/Post.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const mongoose = require('mongoose')
2+
const Schema = mongoose.Schema
3+
4+
const postSchema = new Schema({
5+
title: {
6+
type: String,
7+
required: true
8+
},
9+
image: {
10+
type: String,
11+
required: true
12+
},
13+
body: {
14+
type: String,
15+
required: true
16+
},
17+
createdAt: {
18+
type: Date,
19+
default: Date.now
20+
},
21+
userId: {
22+
type: Schema.Types.ObjectId,
23+
ref: 'User'
24+
},
25+
comments: [
26+
{
27+
type: Schema.Types.ObjectId,
28+
ref: 'Comment'
29+
}
30+
]
31+
})
32+
33+
module.exports = mongoose.model('Post', postSchema)

models/User.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
const mongoose = require('mongoose')
2+
const bcrypt = require('bcryptjs')
3+
const Schema = mongoose.Schema
4+
5+
const userSChema = new Schema({
6+
username: {
7+
type: String,
8+
required: true,
9+
unique: true
10+
},
11+
password: {
12+
type: String,
13+
require: true
14+
}
15+
})
16+
17+
userSChema.pre('save', function (next) {
18+
var user = this
19+
20+
if (!user.isModified('password')) {
21+
return next()
22+
}
23+
24+
bcrypt.genSalt(10, (err, salt) => {
25+
if (err) return next(err)
26+
27+
bcrypt.hash(user.password, salt, function(err, hash) {
28+
if (err) return next(err)
29+
user.password = hash
30+
next()
31+
})
32+
})
33+
})
34+
35+
userSChema.methods.comparePassword = function (clientPassword, cb) {
36+
bcrypt.compare(clientPassword, this.password, (err, isMatch) => {
37+
if (err) return cb(err)
38+
cb(null, isMatch)
39+
})
40+
}
41+
module.exports = mongoose.model('User', userSChema)

0 commit comments

Comments
 (0)