-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
487 lines (436 loc) · 12.8 KB
/
server.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
/*********************************************************************************
* WEB322 – Assignment 06
* I declare that this assignment is my own work in accordance with Seneca Academic Policy. No part
* of this assignment has been copied manually or electronically from any other source
* (including 3rd party web sites) or distributed to other students.
*
* Name: Lorenz Alvin Tubo Student ID: 1090934224 Date: 07/29/2023
*
* Cyclic Web App URL: https://easy-teal-elk-gear.cyclic.app/about
*
* GitHub Repository URL: https://github.com/YuhanPizza/web322-app
*
********************************************************************************/
require('dotenv').config();
//client sessions
const clientSessions = require('client-sessions');
//auth-service
const authData = require("./auth-service");
//strip-js
const stripJs = require("strip-js");
//handlebars
const exphbs = require("express-handlebars");
//streamifier
const streamifier = require("streamifier");
//cloudinary
const cloudinary = require("cloudinary").v2;
//multer
const multer = require("multer");
//require blog-service
const blogService = require("./blog-service");
//express library
const express = require("express");
const app = express();
//static files
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
const path = require("path");
//port
const HTTP_PORT = process.env.PORT || 8080;
const onHttpStart = () => {
console.log(`Port Listening :${HTTP_PORT}`);
};
//strip-Js custom Helper
exphbs.create({}).handlebars.registerHelper("safeHTML", function (context) {
return stripJs(context);
});
//handle-bars config
app.engine(".hbs", exphbs.engine({ extname: ".hbs", helpers:{formatDate: function(dateObj){
let year = dateObj.getFullYear();
let month = (dateObj.getMonth() + 1).toString();
let day = dateObj.getDate().toString();
return `${year}-${month.padStart(2, '0')}-${day.padStart(2,'0')}`;
}
} }));
app.set("view engine", ".hbs");
//cloudinary config
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET,
secure: true,
});
//upload variable w/o disk storage
const upload = multer(); // no {storage: storage }
//custom middleware
app.use(
clientSessions({
cookieName: "session", // this is the object name that will be added to 'req'
secret: "long_un_guessable_string", // this should be a long un-guessable string.
duration: 5 * 60 * 1000, // duration of the session in milliseconds (5 minutes)
activeDuration: 1000 * 60 * 5, // Session will be extended by 5 minutes on each request
})
);
app.use(function (req, res, next) {
res.locals.session = req.session;
next();
});
function ensureLogin(req, res, next) {
if (req.session && req.session.user) {
next();
} else {
res.redirect("/login");
}
}
// Middleware function
app.use(function (req, res, next) {
let route = req.path.substring(1);
app.locals.activeRoute =
"/" +
(isNaN(route.split("/")[1])
? route.replace(/\/(?!.*)/, "")
: route.replace(/\/(.*)/, ""));
app.locals.viewingCategory = req.query.category;
next();
});
// Custom handle-bars helper
exphbs.create({}).handlebars.registerHelper("navLink", function (url, options) {
return (
"<li" +
(url == app.locals.activeRoute ? ' class="active" ' : "") +
'><a href="' +
url +
'">' +
options.fn(this) +
"</a></li>"
);
});
//login stuff
// GET route to render the login view
app.get("/login", function (req, res) {
res.render("login");
});
// GET route to render the register view
app.get("/register", function (req, res) {
res.render("register");
});
// POST route to handle user registration
app.post("/register", function (req, res) {
authData
.registerUser(req.body)
.then(() => {
res.render("register", { successMessage: "User created" });
})
.catch((err) => {
res.render("register", { errorMessage: err, userName: req.body.userName });
});
});
// POST route to handle user login
app.post("/login", function (req, res) {
req.body.userAgent = req.get("User-Agent");
authData
.checkUser(req.body)
.then((user) => {
req.session.user = {
userName: user.userName,
email: user.email,
loginHistory: user.loginHistory,
};
res.redirect("/posts");
})
.catch((err) => {
res.render("login", { errorMessage: err, userName: req.body.userName });
});
});
// GET route to handle user logout
app.get("/logout", function (req, res) {
req.session.reset();
res.redirect("/");
});
// GET route to render the userHistory view
app.get("/userHistory", ensureLogin, function (req, res) {
res.render("userHistory");
});
//post route
app.post("/posts/add",ensureLogin, upload.single("featureImage"), (req, res) => {
if (req.file) {
let streamUpload = (req) => {
return new Promise((resolve, reject) => {
let stream = cloudinary.uploader.upload_stream((error, result) => {
if (result) {
resolve(result);
} else {
reject(error);
}
});
streamifier.createReadStream(req.file.buffer).pipe(stream);
});
};
async function upload(req) {
let result = await streamUpload(req);
console.log(result);
return result;
}
upload(req)
.then((uploaded) => {
processPost(uploaded.url,req,res);
})
.catch((error) => {
console.error("Image Upload Failed: ", error);
res.status(500).send("Image upload failed.");
});
} else {
processPost("",req,res);
}
function processPost(imageUrl ,req ,res ) {
req.body.featureImage = imageUrl;
const newPost = {
body: req.body.body,
title:req.body.title,
category:req.body.category,
featureImage: req.body.featureImage,
published:req.body.published,
// Add other properties from req.body as needed
};
blogService
.addPost(newPost)
.then(() => {
res.redirect("/posts");
})
.catch((error) => {
console.error(error);
res.status(500).send("Error creating new post.");
});
}
});
//initalize
blogService
.initialize()
.then(authData.initialize)
.then(() => {
//Routes and server setup
app.listen(HTTP_PORT, onHttpStart);
})
.catch((error) => {
console.error("Initialization error:",error);
});
//about
app.get("/about", (req, res) => {
res.render("about");
});
app.get("/", (req, res) => {
res.redirect("/blog");
});
//blog
app.get("/blog", async (req, res) => {
// Declare an object to store properties for the view
let viewData = {};
try {
// declare empty array to hold "post" objects
let posts = [];
// if there's a "category" query, filter the returned posts by category
if (req.query.category) {
// Obtain the published "posts" by category
posts = await blogService.getPublishedPostsByCategory(req.query.category);
} else {
// Obtain the published "posts"
posts = await blogService.getPublishedPosts();
}
// sort the published posts by postDate
posts.sort((a, b) => new Date(b.postDate) - new Date(a.postDate));
// get the latest post from the front of the list (element 0)
let post = posts[0];
// store the "posts" and "post" data in the viewData object (to be passed to the view)
viewData.posts = posts;
viewData.post = post;
} catch (err) {
viewData.message = "no results";
}
try {
// Obtain the full list of "categories"
let categories = await blogService.getCategories();
// store the "categories" data in the viewData object (to be passed to the view)
viewData.categories = categories;
} catch (err) {
viewData.categoriesMessage = "no results";
}
// render the "blog" view with all of the data (viewData)
res.render("blog", { data: viewData });
});
//post
app.get("/posts",ensureLogin, (req, res) => {
const { category, minDate } = req.query;
if (category) {
blogService
.getPostsByCategory(category)
.then((posts) => {
if (posts.length > 0) {
res.render("posts", { posts: posts });
} else {
res.render("posts", { message: "no results" });
}
})
.catch((error) => {
res.render("posts", { message: "no results" });
});
} else if (minDate) {
blogService
.getPostsByMinDate(minDate)
.then((posts) => {
if (posts.length > 0) {
res.render("posts", { posts: posts });
} else {
res.render("posts", { message: "no results" });
}
})
.catch((error) => {
res.render("posts", { message: "no results" });
});
} else {
blogService
.getAllPosts()
.then((posts) => {
if (posts.length > 0) {
res.render("posts", { posts: posts });
} else {
res.render("posts", { message: "no results" });
}
})
.catch((error) => {
res.render("posts", { message: "no results" });
});
}
});
//post add
app.get("/posts/add",ensureLogin, (req, res) => {
blogService.getCategories().then((categories)=>{
res.render("addPost",{categories});
}).catch(()=>{
res.render("addPost",{categories:[]});
});
});
//categories add
app.get("/categories/add",ensureLogin, (req, res) => {
res.render("addCategory");
});
//post by Id
app.get("/post/:value",ensureLogin, (req, res) => {
const postId = req.params.value;
blogService
.getPostById(postId)
.then((post) => {
if (post) {
res.json(post);
} else {
res.status(404).json({ message: "Post not found." });
}
})
.catch((error) => {
res.status(500).json({ message: error });
});
});
//post delete id
app.get("/posts/delete/:id",ensureLogin, (req, res) => {
const postId = req.params.id;
blogService
.deletePostById(postId)
.then(() => {
res.redirect("/posts");
})
.catch((error) => {
console.error(error);
res.status(500).send("Unable to remove post / Post not found.");
});
});
//categories
app.get("/categories",ensureLogin, (req, res) => {
blogService
.getCategories()
.then((categories) => {
if (categories.length > 0) {
res.render("categories", { categories });
} else {
res.render("categories", { message: "no results" });
}
})
.catch((error) => {
res.render("categories", { message: "no results" });
});
});
//categories add post
app.post("/categories/add",ensureLogin, (req, res) => {
const newCategory = {
category: req.body.category,
};
blogService
.addCategory(newCategory)
.then(() => {
res.redirect("/categories");
})
.catch((error) => {
console.error(error);
res.status(500).send("Error creating new category.");
});
});
//categories delete id
app.get("/categories/delete/:id", ensureLogin, (req, res) => {
const categoryId = req.params.id;
blogService
.deleteCategoryById(categoryId)
.then(() => {
res.redirect("/categories");
})
.catch((error) => {
console.error(error);
res.status(500).send("Unable to remove category / Category not found.");
});
});
app.get("/blog/:id", async (req, res) => {
// Declare an object to store properties for the view
let viewData = {};
try {
// declare empty array to hold "post" objects
let posts = [];
// if there's a "category" query, filter the returned posts by category
if (req.query.category) {
// Obtain the published "posts" by category
posts = await blogService.getPublishedPostsByCategory(req.query.category);
} else {
// Obtain the published "posts"
posts = await blogService.getPublishedPosts();
}
// sort the published posts by postDate
posts.sort((a, b) => new Date(b.postDate) - new Date(a.postDate));
// store the "posts" and "post" data in the viewData object (to be passed to the view)
viewData.posts = posts;
} catch (err) {
viewData.message = "no results";
}
try {
// Obtain the post by "id"
viewData.post = await blogService.getPostById(req.params.id);
} catch (err) {
viewData.message = "no results";
}
try {
// Obtain the full list of "categories"
let categories = await blogService.getCategories();
// store the "categories" data in the viewData object (to be passed to the view)
viewData.categories = categories;
} catch (err) {
viewData.categoriesMessage = "no results";
}
// render the "blog" view with all of the data (viewData)
res.render("blog", { data: viewData });
});
//me just stuff
app.get("/me", (req, res) => {
res.redirect("https://github.com/YuhanPizza");
});
//404
//This use() will not allow req to go beyond it
//so we place it at the end of the file, after other routes.
//This function will catch all other requests that dont match.
app.use((req, res) => {
res.status(404).render('404');
});