-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
245 lines (216 loc) · 7.55 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectID;
const methodOverride = require('method-override');
const assert = require('assert');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const passport = require("passport");
const LocalStrategy = require("passport-local");
const session = require('express-session');
const flash = require('express-flash');
const {check, validationResult} = require('express-validator/check');
//view engine for ejs
app.set('view engine', 'ejs');
//using req.body
app.use(express.urlencoded({extended: true}));
app.use(express.json());
//for delete and edit routes
app.use(methodOverride('_method'));
//setting folders
app.use(express.static('public'));
app.use(express.static('partials'));
app.use(express.static('images'));
app.use(express.static('assets'));
// using express-session for session cookies
app.use(session({
secret: 'ahnyujin',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
res.locals.error = req.flash('error');
res.locals.success = req.flash('success');
next();
})
// Connection URL
const mongourl = process.env.DATABASE_URL
// Database Name
var db;
// Use connect method to connect to the server
MongoClient.connect(mongourl, {useNewUrlParser: true}, function(err, client) {
if(err) {
assert.equal(null, err);
} else {
console.log('Connected successfully to the MongoDB server');
db = client.db('theartblog');
}
});
// using the local strategy with passport
passport.use(new LocalStrategy({usernameField: 'username', passwordField: 'password'}, (username, password, done) => {
db.collection('users').findOne({user: username}, (err, user) => {
if(err) {
return done(err);
} if (!user) {
return done(null, false, {message: 'User not found'});
} if (username === user.user && (bcrypt.compareSync(password, user.password) === false)) {
return done(null, false, {message: 'Incorrect password'});
} if (username === user.user && (bcrypt.compareSync(password, user.password) === true)) {
return done(null, user);
}
});
}));
passport.serializeUser(function (user, done) {
return done(null, user.id);
});
passport.deserializeUser(function (id, done) {
db.collection('users').findOne({id: id}, (err, user) => {
return done(null, user);
});
});
//INDEX ROUTE
app.get('/', (req, res) => {
db.collection('posts').find().sort({"_id": -1}).toArray((err, allPosts) => {
if(err) {
assert.equal(null, err);
} else {
res.render('index', {allPosts: allPosts, layout: 'index', user: req.user});
}
});
});
//SIGNUP ROUTE
app.get('/signup', (req, res) => {
res.render('signup', {layout: 'signup', user: req.user});
});
app.post('/signup', [
check('username').trim().escape(),
check('email').trim().escape(),
check('password').trim().escape()
], (req, res) => {
bcrypt.hash(req.body.password, saltRounds, (err, hash) => {
if(err) {
assert.equal(err, null);
} else {
var upsert = {upsert: true};
var setForm = {$set:{user: req.body.username, email: req.body.email, password: hash, date: new Date}};
db.collection('users').createIndex({user: 1}, {unique: true});
db.collection('users').createIndex({email: 1}, {unique: true});
db.collection('users').updateOne({user: req.body.username, email: req.body.email, password: hash, id: ObjectId().toString()}, setForm, upsert, (err, userCreated) => {
if(err) {
req.flash('error', 'User with this username or email is already exist');
res.redirect('/signup');
} else {
passport.authenticate('local')(req, res, () => {
req.flash('success', 'Welcome ' + req.user.user + '!');
res.redirect('/');
});
console.log('User created');
}
});
}
});
});
//LOGIN ROUTE
app.get('/login', (req, res) => {
res.render('login', {layout: 'login', user: req.user, message: req.flash('error')});
});
app.post('/login', passport.authenticate('local', {failureRedirect: '/login', failureFlash : true}), (req, res) => {
req.flash('success', 'Welcome back ' + req.user.user + '!');
res.redirect('/');
});
//logout route
app.get('/logout', (req, res) => {
req.logout();
req.flash('success', 'Goodbye. See you next time!');
res.redirect('/');
});
function isLoggedIn(req, res, next) {
if(req.isAuthenticated()){
return next();
};
res.redirect('/login');
};
function isSameUser(req, res, next){
var objectId = require('mongodb').ObjectID(req.params.id);
db.collection('posts').findOne({_id: objectId}, (err, foundPost) => {
if(req.user.user === foundPost.user){
return next();
} else {
res.redirect('back');
}
});
}
//add new post route
app.get('/add', isLoggedIn, (req, res) => {
res.render('add', {layout: 'add', user: req.user, message: req.flash('error')});
});
app.post('/add', isLoggedIn, [
check('image').trim(),
check('title').trim().unescape(),
check('content').trim().unescape()
], (req, res) => {
db.collection('posts').insertOne({user: req.user.user, image: req.body.image, title: req.body.title, content: req.body.content, date: new Date}, (err, createdPost) => {
if(err) {
assert.equal(err, null);
} else {
res.redirect('/');
}
});
});
//show post route
app.get('/:id([0-9a-f]{24})', (req, res) => {
var objectId = require('mongodb').ObjectID(req.params.id);
db.collection('posts').findOne({_id: objectId}, (err, foundPost) => {
if(err) {
assert.equal(err, null);
} else {
res.render('post', {foundPost: foundPost, layout: 'post', user: req.user});
}
});
});
//edit post route
app.put('/:id', isLoggedIn, isSameUser, [
check('image').trim(),
check('title').trim().unescape(),
check('content').trim().unescape()
], (req, res) => {
var objectId = require('mongodb').ObjectID(req.params.id);
var setUpdate = {$set:{title: req.body.title, image: req.body.image, content: req.body.content, edited: new Date}};
db.collection('posts').updateOne({_id: objectId}, setUpdate, (err, updatedPost) => {
if(err) {
assert.equal(err, null);
} else {
res.redirect('/' + req.params.id);
}
});
});
//delete a post route
app.delete('/:id', isLoggedIn, isSameUser, (req, res) => {
var objectId = require('mongodb').ObjectID(req.params.id);
db.collection('posts').deleteOne({_id: objectId}, (err) => {
if(err) {
assert.equal(err, null);
} else {
res.redirect('/');
}
});
});
//edit post route
app.get('/:id/edit', isLoggedIn, isSameUser, (req, res) => {
var objectId = require('mongodb').ObjectID(req.params.id);
db.collection('posts').findOne({_id: objectId}, (err, foundPost) => {
if(err) {
assert.equal(err, null);
} else {
res.render('edit', {foundPost: foundPost, layout: 'edit', user: req.user});
}
});
});
//starting a server
app.listen(process.env.PORT, process.env.IP, function() {
console.log('Blog server has been started');
});