-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
448 lines (386 loc) · 14.9 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
require('dotenv').config()
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const lodash = require('lodash');
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
const findOrCreate = require('mongoose-findorcreate');
const aboutContent = "Daily journal is blogging site where you can post your blogs publicly for the world to see. What makes it different from most other blogging sites though, is that apart from posting public blogs you can use it as a personal diary as well. Yes you read it right! All you need to do is select your posts to be private while creating them and voila! You have a personal journal entry! Hope you have a good time on Daily Journal.";
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(express.static("public"));
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
const mongoAtlasPassword = process.env.MONGOATLASAPPPASSWORD;
mongoose.connect('mongodb+srv://admin-naman:' + mongoAtlasPassword + '@cluster0.cxzx0.mongodb.net/blogDB', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false })
mongoose.set('useCreateIndex', true);
const postSchema = new mongoose.Schema({
title: String,
post: String,
public: Boolean,
account: String,
email: String,
authorId: String,
timestamp: String,
likes: Number
// liked: Boolean,
// likes: Number,
// comments: [String],
// numberOfComments: Number
});
const Post = mongoose.model('Post', postSchema);
const usersSchema = new mongoose.Schema({
accountName: String,
email: String,
password: String,
googleId: String,
// googleId: String,
// facebookId: String,
posts: [postSchema],
likedPosts: [String]
});
usersSchema.plugin(passportLocalMongoose);
usersSchema.plugin(findOrCreate);
const User = mongoose.model('User', usersSchema);
passport.use(User.createStrategy());
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "https://shielded-wave-63105.herokuapp.com/auth/google/callback",
// userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({ googleId: profile.id, accountName: profile.displayName, username: profile.emails[0]['value'] }, function (err, user) {
return cb(err, user);
});
}
));
//
// passport.use(new FacebookStrategy({
// clientID: process.env.FB_APP_ID,
// clientSecret: process.env.FB_APP_SECRET,
// callbackURL: "http://localhost:3000/auth/facebook/"
// },
// function(accessToken, refreshToken, profile, cb) {
// console.log(profile);
// User.findOrCreate({ facebookId: profile.id }, function (err, user) {
// return cb(err, user);
// });
// }
// ));
app.get('/', (req, res) => {
Post.find({public: true}, (err, posts) => {
posts.sort ( (a, b) => {
return new Date(b.timestamp) - new Date(a.timestamp);
});
if(req.isAuthenticated()) {
User.findById(req.user.id, (err, foundUser) => {
if(err) {
console.log(err);
res.send("There was an error. Please try again.");
} else {
res.render('home', {postsArray: posts, authenticated: req.isAuthenticated(), userLikedPosts: foundUser.likedPosts});
}
});
} else {
res.render('home', {postsArray: posts, authenticated: req.isAuthenticated(), userLikedPosts: null});
}
})
});
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] })
);
app.get('/auth/google/callback', passport.authenticate('google', {failureRedirect: '/login'}), (req, res) => {
res.redirect('/');
});
//
// app.get('/auth/facebook',
// passport.authenticate('facebook'));
//
// app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), (req, res) => {
// // Successful authentication, redirect home.
// res.redirect('/');
// });
app.get('/login', (req, res) => {
res.render('login', {authenticated: req.isAuthenticated()});
});
app.get('/register', (req, res) => {
res.render('register', {authenticated: req.isAuthenticated()});
});
app.get('/about', (req, res) => {
res.render('about', {aboutContent: aboutContent, authenticated: req.isAuthenticated()});
});
app.get('/contact', (req, res) => {
res.render('contact', {authenticated: req.isAuthenticated()});
});
app.get('/profile', (req, res) => {
if(req.isAuthenticated()) {
User.findById(req.user.id, (err, foundUser)=> {
if(err) {
console.log(err);
res.send('Please log in to see your profile.');
} else {
if (foundUser) {
console.log(foundUser.posts.length);
res.render('profile', { postsArray: foundUser.posts, userName: foundUser.accountName, authenticated: req.isAuthenticated(), visitor: false });
}
else{
res.send("Please log in to see your profile.");
}
}
});
} else {
res.send("Please log in to see your profile.");
}
});
app.get('/profile/:profileId', (req, res) => {
const profileId = req.params.profileId;
console.log(profileId);
User.findById(profileId, (err, foundUser) => {
if (err) {
console.log(err);
res.send('User not found');
} else {
if(req.isAuthenticated()) {
User.findById(req.user.id, (err, foundMyself) => {
if(err) {
console.log(err);
res.send("Please login to see this profile");
} else {
if(foundMyself) {
if (JSON.stringify(foundMyself._id) === JSON.stringify(foundUser._id)) {
res.render('profile', { postsArray: foundUser.posts, userName: foundUser.accountName, authenticated: req.isAuthenticated(), visitor: false });
} else {
res.render('profile', { postsArray: foundUser.posts, userName: foundUser.accountName, authenticated: req.isAuthenticated(), visitor: true });
}
} else {
res.send("Please login to see this profile");
}
}
});
} else {
res.render('profile', { postsArray: foundUser.posts, userName: foundUser.accountName, authenticated: req.isAuthenticated(), visitor: true });
}
}
});
});
app.get('/compose', (req, res) => {
if(req.isAuthenticated()){
res.render('compose', {authenticated: req.isAuthenticated()});
} else {
res.send("Please login to write a post.");
}
});
app.get('/posts/:postId', (req, res) => {
const requestedPostId = req.params.postId;
Post.findById( requestedPostId, (err, foundPost) => {
if(err) {
console.log(err);
res.send("There was an error retrieving the post.");
} else {
if(foundPost) {
if (req.isAuthenticated()) {
User.findById(req.user.id, (err, foundMyself) => {
if(err) {
console.log(err);
res.send("Please login to see this post");
} else {
if(foundMyself) {
console.log(foundPost.post);
if (JSON.stringify(foundMyself._id) === JSON.stringify(foundPost.authorId)) {
res.render('post', {id: foundPost._id, title: foundPost.title, author: foundPost.account, content: foundPost.post, visitor: false, authenticated: req.isAuthenticated()});
} else {
res.render('post', {id: foundPost._id, title: foundPost.title, author: foundPost.account, content: foundPost.post, visitor: true, authenticated: req.isAuthenticated()});
}
} else {
res.send("Please login to see this post");
}
}
});
} else {
res.render('post', {id: foundPost._id, title: foundPost.title, author: foundPost.account, content: foundPost.post, visitor: true, authenticated: req.isAuthenticated()});
}
}
}
});
});
app.post('/like', (req, res) => {
const liked = req.body.liked;
const postId = req.body.postId;
if(req.isAuthenticated()) {
User.findById(req.user.id, (err, foundUser) => {
if(err) {
console.log(err);
res.send("There was an error. Please try again.");
} else {
if(liked==='true'){
foundUser.likedPosts.push(postId);
foundUser.save();
Post.findById(postId, (err, foundPost) => {
if(err) {
console.log(err);
res.send("There was an error");
} else {
foundPost.likes++;
console.log(foundPost.likes)
foundPost.save();
console.log(foundPost.likes)
}
});
res.redirect('/');
} else {
foundUser.likedPosts.splice(foundUser.likedPosts.indexOf(postId), 1);
foundUser.save();
Post.findById(postId, (err, foundPost) => {
if(err) {
console.log(err);
res.send("There was an error");
} else {
foundPost.likes--;
console.log(foundPost.likes)
foundPost.save();
console.log(foundPost.likes)
}
});
res.redirect('/');
}
}
});
}
});
app.post('/delete', (req, res) => {
const postId = req.body.postId;
Post.findById(postId, (err, foundPost) => {
if(err) {
console.log(err);
res.send('Post not found.');
} else {
if(foundPost) {
const userId = foundPost.authorId;
User.findById(userId, (err, foundUser) => {
if(err) {
console.log(err);
res.send("There was an error. Please try again.");
} else {
if (foundUser) {
for(let i = 0; i < foundUser.posts.length; i++) {
if (JSON.stringify(foundUser.posts[i]['_id']) === JSON.stringify(postId)) {
console.log(foundUser.posts.length);
foundUser.posts.splice(i,1);
foundUser.save();
console.log(foundUser.posts.length);
break;
}
}
} else {
res.send("User not found");
}
}
});
Post.findByIdAndDelete(postId, (err, deletedPost) => {
if(err) {
console.log(err);
res.send("There was an error. Please try again.");
} else {
if(deletedPost) {
console.log(deletedPost);
res.redirect('/profile');
}
}
});
} else {
res.send("Post not found");
}
}
});
});
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
app.post('/register', (req, res) => {
User.register({username: req.body.username, accountName: req.body.accountName}, req.body.password, (err, user) => {
if(err) {
console.log(err);
res.redirect('/register');
} else {
passport.authenticate('local')(req, res,() => {
res.redirect('/')
});
}
});
})
app.post('/login', (req, res) => {
const user = new User({
username: req.body.username,
password: req.body.password
});
req.login(user, (err) => {
if(err) {
console.log(err);
res.send("Incorrect email or password");
} else {
passport.authenticate('local')(req, res, ()=> {
res.redirect('/');
});
}
});
})
app.post('/compose', (req, res) => {
User.findById(req.user.id, (err, foundUser)=> {
if(err) {
console.log(err);
res.send('Please log in to post.');
} else {
const today = new Date();
const dateTime = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate() + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
const post = new Post ({
title: req.body.title,
post: req.body.post,
public: req.body.public,
account: foundUser.accountName,
email: foundUser.username,
authorId: req.user.id,
timestamp: dateTime,
likes: 0
});
// if(post.public) {
// post.save();
// }
post.save();
foundUser.posts.push(post);
foundUser.save(() => {
res.redirect('/');
console.log(foundUser.posts);
});
}
})
})
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, function() {
console.log("Server has started Successfully");
});