-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
545 lines (451 loc) · 14 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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const _ = require("lodash");
const mongoose= require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const findOrCreate = require("mongoose-findorcreate");
const InternalOAuthError = require('passport-oauth').InternalOAuthError;
const homeStartingContent = "Lacus vel facilisis volutpat est velit egestas dui id ornare. Semper auctor neque vitae tempus quam. Sit amet cursus sit amet dictum sit amet justo. Viverra tellus in hac habitasse. Imperdiet proin fermentum leo vel orci porta. Donec ultrices tincidunt arcu non sodales neque sodales ut. Mattis molestie a iaculis at erat pellentesque adipiscing. Magnis dis parturient montes nascetur ridiculus mus mauris vitae ultricies. Adipiscing elit ut aliquam purus sit amet luctus venenatis lectus. Ultrices vitae auctor eu augue ut lectus arcu bibendum at. Odio euismod lacinia at quis risus sed vulputate odio ut. Cursus mattis molestie a iaculis at erat pellentesque adipiscing.";
const aboutContent = "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Non diam phasellus vestibulum lorem sed. Platea dictumst quisque sagittis purus sit. Egestas sed sed risus pretium quam vulputate dignissim suspendisse. Mauris in aliquam sem fringilla. Semper risus in hendrerit gravida rutrum quisque non tellus orci. Amet massa vitae tortor condimentum lacinia quis vel eros. Enim ut tellus elementum sagittis vitae. Mauris ultrices eros in cursus turpis massa tincidunt dui.";
const contactContent = "Scelerisque eleifend donec pretium vulputate sapien. Rhoncus urna neque viverra justo nec ultrices. Arcu dui vivamus arcu felis bibendum. Consectetur adipiscing elit duis tristique. Risus viverra adipiscing at in tellus integer feugiat. Sapien nec sagittis aliquam malesuada bibendum arcu vitae. Consequat interdum varius sit amet mattis. Iaculis nunc sed augue lacus. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. Pulvinar elementum integer enim neque. Ultrices gravida dictum fusce ut placerat orci nulla. Mauris in aliquam sem fringilla ut morbi tincidunt. Tortor posuere ac ut consequat semper viverra nam libero.";
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
//-------------------- DATA BASE parts-------------------------
mongoose.connect("mongodb://0.0.0.0:27017/blogdb");
const userInfo= new mongoose.Schema({
mail:String,
username:String,
password:String
})
const Blog= new mongoose.Schema({
Username:String,
date:String,
title: String,
content: String
})
const comment= new mongoose.Schema({
newId:String,
username:String,
comment:String
})
userInfo.plugin(passportLocalMongoose);
userInfo.plugin(findOrCreate);
const userInfoDB= mongoose.model("UserInfo",userInfo);
const BlogDB=mongoose.model("Blog",Blog);
const commentDB=mongoose.model("comment",comment);
passport.use(userInfoDB.createStrategy());
// this will complicate the password and also derived the orginal password
passport.serializeUser(function(user,done){
done(null,user.id);
});
passport.deserializeUser(function(id, done) {
userInfoDB.findById(id)
.then(function(user) {
done(null, user);
})
.catch(function(err) {
done(err, null);
});
});
//-------------------- DATA BASE parts ends here-------------------------
// -------------------- get function()-------------------
app.get("/", function(req, res){
if(req.isAuthenticated()){
res.redirect("/home");
}else{
BlogDB.find({})
.then((posts,err)=>{
if (err) {
console.error(err);
res.render("404");
}else{
// console.log(posts);
// res.render('home', {
// startingContent: homeStartingContent,
// posts: posts
// });
res.render("drashboard",{posts: posts});
}
})
}
});
app.get("/home",function(req,res){
if (req.isAuthenticated())
{ BlogDB.find({})
.then((posts,err)=>{
if (err) {
console.error(err);
res.render("404");
}else{
// console.log(posts);
userInfoDB.findOne({_id:req.session.passport.user})
.then(function(user){
res.render('home', {
yourAccount:user.username,
startingContent: homeStartingContent,
posts: posts
});
// res.render("drashboard",{posts: posts});
});
}
})}else{
res.render("login");
}
});
app.get("/about", function(req, res){
res.render("about", {aboutContent: aboutContent});
});
app.get("/contact", function(req, res){
res.render("contact", {contactContent: contactContent});
});
app.get("/login",function(req,res){
res.render("login");
});
app.get("/signup",function(req,res){
res.render("signup");
});
app.get("/compose", function(req, res){
// passing the current user to get the writer of the blog
if (req.isAuthenticated()){
// console.log(req.session.passport.user);
userInfoDB.findOne({_id:req.session.passport.user})
.then(function(user){
// console.log(user.username);
res.render("compose",{currentUser:user.username});
});
}else{
res.render("login");
}
});
app.get("/logout",function(req,res){
req.logout((err) => {
if (err) {
console.error(err);
}
// Redirect after logout
res.redirect("/");
});
});
app.get("/user/:yourAccount",function(req,res){
//req.params.yourAccount = user name store in userinfo
// console.log(req.session.passport);
if(req.isAuthenticated()){
// console.log(req.params.yourAccount);
userInfoDB.findOne({_id : req.session.passport.user})
.then((user)=>{
if(req.params.yourAccount){
BlogDB.find({ Username: req.params.yourAccount})
.exec()
.then(posts => {
if (!posts) {
res.render("account",{
posts:posts
});
}
// console.log("post[0]: ",posts[0].Username);
else if(req.params.yourAccount===user.username){
res.render("account", {
posts:posts
});
}else{
res.render("404");
}
})
.catch(err => {
const post=[];
res.render("account",{
posts:post
});
});
}else{
res.send("error");
}
})
}else{
res.render("login");
}
});
app.get("/404",(req,res)=>{
res.render("404");
});
app.get("/submissionError",(req,res)=>{
res.render("submission_error");
});
app.get("/account/:postName",function(req,res){
const requestedTitle = _.lowerCase(req.params.postName);
// console.log(requestedTitle);
// console.log(BlogDB.findOne({ title: requestedTitle }));
BlogDB.findOne({ title: requestedTitle })
.exec()
.then(post => {
if (!post) {
res.render("404");
}
res.render("manageBlog", {
title: post.title,
content: post.content
});
})
.catch(err => {
console.error(err);
res.status(500).send('Internal Server Error');
});
});
app.get("/posts/:postName", function(req, res){
const requestedTitle = _.lowerCase(req.params.postName);
// console.log(BlogDB.findOne({ title: requestedTitle }));
if(req.isAuthenticated()){
BlogDB.findOne({ title: requestedTitle })
.exec()
.then(post => {
// console.log(post);
if (!post) {
res.render("404");
}
else{
// console.log(post.id);
commentDB.find({newId:post.id})
.then((comments)=>{
userInfoDB.findOne({_id:req.session.passport.user})
.then(function(User){
res.render("post", {
user:User.username,
ID:post.id,
title: post.title,
content: post.content,
allComment: comments
});
});
});
}
})
.catch(err => {
console.error(err);
res.status(500).send('Internal Server Error');
});
}
else{
BlogDB.findOne({ title: requestedTitle })
.exec()
.then(post => {
if (!post) {
res.render("404");
}
res.render("seeBlog", {
writer:post.Username,
title: post.title,
content: post.content
});
})
.catch(err => {
console.error(err);
res.status(500).send('Internal Server Error');
});
}
});
app.get("/edit", function (req, res) {
const editContent = req.query.title;
BlogDB.findOne({ title: editContent })
.then((post) => {
if (!post) {
res.render("404");
} else {
res.render("edit", {
title: post.title,
content: post.content,
});
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Internal Server Error');
});
});
app.get("/delete", function(req, res){
const deleteContent = req.query.title;
// console.log(deleteContent);
BlogDB.findOneAndDelete({title:deleteContent})
.then(success=>{
if (success) {
console.log("successfully deleted");
res.redirect("/home");
}
else{
// console.error(err);
res.status(500).send('Internal Server Error');
return;
}
})
});
app.get("/:random",(req,res)=>{
res.render("404");
})
//--------------------------post funciton()----------------
// app.post("/compose", function(req, res){
// const blog= new BlogDB({
// Username: req.body.username,
// title:_.lowerCase(req.body.postTitle),
// content: req.body.postBody
// })
// blog.save()
// .then(()=>{
// console.log("your data base is updated");
// })
// res.redirect("/");
// });
app.post("/compose", function(req, res){
const title = _.lowerCase(req.body.postTitle);
// Check if a blog with the same title already exists
BlogDB.findOne({ title: title })
.then(existingBlog => {
if (existingBlog) {
console.log("A blog with this title already exists.");
return res.render("exists"); // Or you can redirect to an error page
}
// If no existing blog, save the new one
const blog = new BlogDB({
Username: req.body.username,
title: title,
content: req.body.postBody
});
return blog.save()
.then(() => {
console.log("Your database is updated.");
res.redirect("/");
});
})
.catch(error => {
console.error(error);
res.status(500).send("Internal Server Error");
});
});
app.post("/update", function (req, res) {
const updatedTitle = req.body.postTitle;
const updatedContent = req.body.postBody;
// Assuming you have a way to identify the specific post you want to update (e.g., using an ID)
const postId = req.query.content;
BlogDB.findOneAndUpdate(
{ content: postId },
{ $set: { title: updatedTitle, content: updatedContent } },
{ new: true }
)
.then((updatedPost) => {
if (!updatedPost) {
res.render("404");
} else {
console.log("Post updated successfully");
// Redirect to a different page or route after successful update
res.redirect("/");
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Internal Server Error');
});
});
app.post("/login", (req, res) => {
const email = req.body.email;
const password = req.body.password;
if (!email || !password) {
res.render("submission_error");
}
userInfoDB.findOne({ mail: email, password: password })
.then(function(user) {
if (user) {
req.logIn(user, (err) => {
if (err) {
console.error(err);
res.render("404");
} else {
res.redirect("/home");
}
});
} else {
res.render("invalid");
}
})
.catch(function(error) {
console.error(error);
res.send("Error checking database.");
});
});
app.post("/register",(req,res)=>{
const email = req.body.email;
const username = req.body.username;
const password = req.body.password
// Check if any field is empty
if (!email || !username || !password) {
res.render("submission_error");
}
// Check if email or username already exists
userInfoDB.findOne({ $or: [ { mail: email }, { username: username } ] })
.then(function(user){
if(user) {
if(user.mail === email) {
res.send("This email is already registered.");
} else {
res.send("This username is already taken.");
}
} else {
// If email and username are unique, create a new user
const newUser = new userInfoDB({
mail: email,
username: username,
password: password
});
newUser.save()
.then(function(success){
res.redirect("/home");
})
.catch(function(error){
res.render("404");
});
}
})
.catch(function(error){
res.send("Error checking database: " + error);
});
});
app.post("/publish",function(req,res){
const username= req.body.username;
const comment= req.body.comment;
const blogRelatedId=req.query.ID;
// console.log(username);
// console.log(comment);
// console.log(blogRelatedId);
// res.send("we are working on it");
if(!comment){
res.render("submission_error");
}else{
const comment_data= new commentDB({
newId:blogRelatedId,
username:username,
comment:comment
});
comment_data.save()
.then(()=>{
console.log("new comment added");
})
// BlogDB.findOne({_id:blogRelatedId})
// .then((blog)=>{
// res.redirect(`/posts/{blog.title}`);
// })
res.redirect("/home")
}
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});