-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
504 lines (416 loc) · 12.9 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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/*********************************************************************************
* 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: Henrique Toshio Sagara Student ID: 170954218 Date: 2023-04-07
*
* Online (Cyclic) Link: https://taupe-lemur-cuff.cyclic.app/
*
********************************************************************************/
var express = require("express");
var app = express();
const path = require("path");
const multer = require("multer");
const exphbs = require("express-handlebars");
const clientSessions = require('client-sessions');
const cloudinary = require('cloudinary').v2;
const streamifier = require('streamifier');
var HTTP_PORT = process.env.PORT || 8080;
//Express built-in "bodyParser" - to access form data in http body
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(clientSessions({
cookieName: "session", // Name of the session cookie
secret: "secret_key", // Secret key for the session cookie
duration: 30 * 60 * 1000, // Session duration in milliseconds
activeDuration: 5 * 60 * 1000, // Session active duration in milliseconds
}));
// Import the data-service module
const dataService = require("./data-service");
const dataServiceAuth = require('./data-service-auth');
const { MulterError } = require("multer");
const { addImage } = require("./data-service");
//Set the cloudinary config
cloudinary.config({
cloud_name: 'dy49xpi4m',
api_key: '238756957843678',
api_secret: '11uWQqTWM8viZalijqfl7cRzpKE',
secure: true
});
//"upload" variable without any disk storage
const upload = multer();
//built-in "express.urlencoded" middleware
app.use(express.urlencoded({ extended: true }));
app.use(function(req, res, next) {
res.locals.session = req.session;
next();
});
// call this function after the http server starts listening for requests
function onHttpStart() {
console.log("\n****Express http server listening on: " + HTTP_PORT + "****\n\n\n\n");
}
function ensureLogin(req, res, next) {
if (!req.session.user) {
res.redirect('/login');
} else {
next();
}
}
//use the new "express-handlebars" module
app.engine('.hbs', exphbs.engine({extname: 'hbs'}));
app.set('view engine', '.hbs');
app.engine('.hbs', exphbs.engine({
extname: '.hbs',
helpers:{
navLink: function(url, options){
return '<li' +
((url == app.locals.activeRoute) ? ' class="active" ' : '') +
'><a href="' + url + '">' + options.fn(this) + '</a></li>';
},
equal: function (lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlebars Helper equal needs 2 parameters");
if (lvalue != rvalue) {
return options.inverse(this);
} else {
return options.fn(this);
}
}
}
}));
// setup a 'route' to listen on the default url path (http://localhost)
app.get('/', (req, res) => {
res.render('home');
});
// setup another route to listen on /about
app.get('/about', (req, res) => {
res.render('about');
});
//***************************************STUDENT****************************************** */
// Add route for students/add
app.get('/students/add', ensureLogin, (req, res) => {
dataService.getPrograms()
.then((data) => {
res.render('addStudent', { programs: data });
})
.catch((err) => {
// Render the students view with an error message
res.render("addStudent", { message: err.message });
});
});
app.get('/students', ensureLogin, (req, res) => {
const status = req.query.status;
const program = req.query.program;
const credential = req.query.credential;
if (status) {
dataService.getStudentsByStatus(status)
.then((students) => {
res.render('students', { students });
})
.catch((err) => {
console.log(err);
res.status(500).send("Error retrieving students");
});
} else if (program) {
dataService.getStudentsByProgramCode(program)
.then((students) => {
res.render('students', { students });
})
.catch((err) => {
console.log(err);
res.status(500).send("Error retrieving students");
});
} else if (credential) {
dataService.getStudentsByExpectedCredential(credential)
.then((students) => {
res.render('students', { students });
})
.catch((err) => {
console.log(err);
res.status(500).send("Error retrieving students");
});
} else {
dataService.getAllStudents()
.then((students) => {
res.render('students', { students });
})
.catch((err) => {
console.log(err);
res.status(500).send("Error retrieving students");
});
}
});
app.get("/students/delete/:studentID", ensureLogin, (req, res)=>
{
const studentID = req.params.studentID
dataService.deleteStudentById(studentID)
.then(() =>
{
console.log("Student deleted");
res.redirect("/students");
})
.catch((err) =>
{
console.log(err)
res.status(500).send("Fail to Remove Student");
});
})
app.post("/student/update", ensureLogin, (req, res) =>
{
console.log(req.body.studentID);
dataService.updateStudent(req.body)
.then(() =>
{
res.redirect("/students");
}).catch((error) =>
{
console.error(error);
res.send(error);
});
});
app.post("/students/add", ensureLogin, function(req, res) {
dataService.addStudent(req.body)
.then(() => {
console.log("Student added");
res.redirect('/students');
})
.catch((err) => {
res.status(500).send("Unable to add student");
});
});
app.get("/student/:studentID", ensureLogin, (req, res) => {
// initialize an empty object to store the values
let viewData = {};
dataService.getStudentById(req.params.studentID).then((data) => {
if (data) {
viewData.student = data; //store student data in the "viewData" object as "student"
} else {
viewData.student = null; // set student to null if none were returned
}
}).catch(() => {
viewData.student = null; // set student to null if there was an error
}).then(dataService.getPrograms)
.then((data) => {
viewData.programs = data; // store program data in the "viewData" object as "programs"
// loop through viewData.programs and once we have found the programCode that matches
// the student's "program" value, add a "selected" property to the matching
// viewData.programs object
for (let i = 0; i < viewData.programs.length; i++) {
if (viewData.programs[i].programCode == viewData.student.program) {
viewData.programs[i].selected = true;
}
}
}).catch(() => {
viewData.programs = []; // set programs to empty if there was an error
}).then(() => {
if (viewData.student == null) { // if no student - return an error
res.status(404).send("Student Not Found");
} else {
res.render("student", { viewData: viewData }); // render the "student" view
}
}).catch((err)=>{
res.status(500).send("Unable to Show Students");
});
});
//***************************************PROGRAMS****************************************** */
app.get("/programs/add", ensureLogin, (req, res) => {
res.render('addProgram');
})
app.get("/programs", ensureLogin, (req, res) => {
dataService.getPrograms()
.then((data) => {
// console.log("get program", programs)
if (data.length > 0) {
res.render("programs", { programs: data });
} else {
res.render("programs", { message: "No results found." });
}
})
.catch((error) => {
console.error(error);
res.render("programs", { message: "An error occurred." });
});
});
app.get('/program/:programCode', ensureLogin, (req, res) => {
const programCode = req.params.programCode;
dataService.getProgramByCode(programCode)
.then((data) => {
if (data) {
res.render('program', { program: data});
} else {
res.status(404).send("Program Not Found");
}
})
.catch(() => {
res.status(404).send("Program Not Found");
});
});
app.get("/programs/delete/:programCode", ensureLogin, (req, res) =>
{
dataService.deleteProgramByCode(req.params.programCode)
.then(() =>
{
console.log("Program deleted");
res.redirect("/programs");
})
.catch((err) =>
{
console.log(err + '\n\n')
res.status(500).send("Fail to Remove Program");
});
});
app.post("/program/update", ensureLogin, (req, res) => {
dataService.updateProgram(req.body)
.then(() => {
res.redirect("/programs")
})
.catch((error) => {
console.error(error);
res.send(error);
});
});
app.post('/programs/add', ensureLogin, function(req, res) {
dataService.addProgram(req.body)
.then(() => {
console.log("Program added");
res.redirect('/programs');
})
.catch((err) => {
res.status(500).send('unable to add program');
});
})
//***************************************IMAGES******************************************** */
// Add route for images/add
app.get('/images/add', ensureLogin, (req, res) => {
res.render('addImage');
});
app.get("/images", ensureLogin, function(req,res){
dataService.getImages().then(function(data) {
if (data.length > 0) {
res.render("images",{images: data});
} else {
res.render("images",{ message: "no results" });
}
}).catch(function(err){
res.send('Error' + err);
});
});
app.post("/images/add", ensureLogin, upload.single("imageFile"), function (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) =>
{
processForm(uploaded);
});
}
else
{
processForm("");
}
function processForm(uploaded)
{
let imgData = {};
imgData.imageId = uploaded.public_id;
imgData.imageUrl = uploaded.url;
imgData.version = uploaded.version;
imgData.width = uploaded.width;
imgData.height = uploaded.height;
imgData.format = uploaded.format;
imgData.resourceType = uploaded.resource_type;
imgData.uploadedAt = uploaded.created_at;
imgData.originalFileName = req.file.originalname;
imgData.mimeType = req.file.mimetype;
console.log("imgData: ", imgData);
dataService.addImage(imgData).then((data) =>
{
console.log("Image added successfully: ", data);
res.redirect("/images");
}).catch((err) =>
{
console.log("Error adding image: " + err);
res.status(500).send("Error adding image: " + err);
});
}
});
//***************************************USER AUTH******************************************** */
app.get('/login', (req, res) => {
res.render('login', {});
});
app.post('/login', (req, res) => {
req.body.userAgent = req.get('User-Agent');
dataServiceAuth.checkUser(req.body)
.then((user) => {
req.session.user = {
userName: user.userName,
email: user.email,
loginHistory: user.loginHistory,
};
res.redirect('/students');
})
.catch((err) => {
res.render('login', { errorMessage: err, userName: req.body.userName });
});
});
app.get('/register', (req, res) => {
res.render('register', {});
});
app.post('/register', (req, res) => {
dataServiceAuth.registerUser(req.body)
.then(() => {
res.render('register', { successMessage: 'User created' });
})
.catch((err) => {
res.render('register', { errorMessage: err, userName: req.body.userName });
});
});
app.get('/logout', (req, res) => {
req.session.reset();
res.redirect('/');
});
app.get('/userHistory', ensureLogin, (req, res) => {
res.render('userHistory', {});
});
app.use(function(req, res, next){
let route = req.baseUrl + req.path;
app.locals.activeRoute = (route == "/") ? "/" : route.replace(/\/$/, "");
next();
});
app.use((req, res) =>
{
res.status(404).send("<h2>404</h2><p>Page Not Found</p>");
});
// setup http server to listen on HTTP_PORT
dataService.initialize()
.then(() => {
return dataServiceAuth.initialize();
})
.then(() => {
app.listen(HTTP_PORT, onHttpStart );
})
.catch((err) => {
console.log(`unable to start server: ${err}`);
});