-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
499 lines (464 loc) · 16 KB
/
index.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
// TO DO:
// change the query in /profile to upsertProfile
// querystring search in /profile/edit if err
// add password double check
const express = require("express");
const helmet = require("helmet");
const app = express();
// to export the app to the supertest:
exports.app = app;
const hb = require("express-handlebars");
// to get querystrings in urls:
const url = require("url");
const querystring = require("querystring");
// const { SESSION_SECRET: sessionSecret } = require("./secrets");
// const cookieParser = require('cookie-parser');
// cookie-parser is gone now! we now use cookie session..
// creates two cookies: second one is an encrypred copy of the first, that makes it temper-proof:
const cookieSession = require("cookie-session");
const csurf = require("csurf");
let secrets;
if (process.env.NODE_ENV === "production") {
secrets = process.env;
} else {
secrets = require("./secrets");
}
const {
addUser,
getUser,
getSigID,
getSigs,
addSig,
getSig,
addProfile,
getSigners,
getSignersInCity,
getProfile,
updateUser3,
updateUser4,
upsertProfile,
deleteSig
} = require("./db");
const {
requireLoggedInUser,
requireLoggedOutUser,
requireSignature,
requireNoSignature
} = require("./middleware");
// for log in:
const { hash, compare } = require("./bcrypt");
// this configures express to use express-handlebars:
app.engine("handlebars", hb());
app.set("view engine", "handlebars");
app.use(helmet());
// let's you link to the styles.css in public folder:
app.use(express.static("./public"));
// middleware function, that grabs user input, parses it and makes it available to req.body:
app.use(
express.urlencoded({
extended: false
})
);
app.use(
cookieSession({
secret: secrets.SESSION_SECRET,
maxAge: 1000 * 60 * 60 * 24 * 14
})
);
app.use(csurf());
app.use(function(req, res, next) {
res.set("x-frame-options", "DENY");
res.locals.csrfToken = req.csrfToken();
next();
});
// app.use((req, res, next) => {
// if (!req.session.userId && req.url != '/login' && req.url != '/register') {
// res.redirect('/register');
// } else {
// next();
// }
// });
app.get("/", (req, res) => {
console.log("*************** / GET ***********");
res.redirect("/petition");
});
// ------------------- adding log in:-------------------------
app.get("/register", requireLoggedOutUser, (req, res) => {
console.log("*************** /register GET ***********");
res.render("register", {
layout: "main",
loginBtn: true
});
});
app.post("/register", requireLoggedOutUser, (req, res) => {
console.log("*************** /register POST ***********");
// console.log(`your name is: ${req.body.first} ${req.body.last}`);
hash(req.body.password)
.then(password => {
addUser(
req.body.first,
req.body.last,
req.body.email,
password
).then(result => {
// console.log('result which includes the RETURNING data: ', result);
// GET ACTUAL ID HERE:
let id = result.rows[0].id;
// console.log(id);
req.session.userId = id;
req.session.first = req.body.first;
req.session.last = req.body.last;
res.redirect("/profile");
});
})
.catch(err => {
console.log("err in /register POST: ", err);
res.render("register", {
loginBtn: true,
err
});
});
});
app.get("/profile", requireLoggedInUser, (req, res) => {
console.log("*************** /profile GET ***********");
res.render("profile", {
layout: "main"
});
});
app.post("/profile", requireLoggedInUser, (req, res) => {
console.log("*************** /profile POST ***********");
let url = req.body.homepage;
if (!(url.startsWith("http://") || url.startsWith("https://"))) {
console.log("url of homepage is not safe!");
url = "";
}
// insert user's age, city, url into new user_profiles table:
let age = req.body.age;
if (age === '') {
age = null;
}
addProfile(age, req.body.city, url, req.session.userId)
.then(() => {
res.redirect("/petition");
})
.catch(err => {
console.log("err in /profile POST: ", err);
res.render("profile", {
err
});
});
});
app.get("/login", requireLoggedOutUser, (req, res) => {
console.log("*************** /login GET ***********");
res.render("login", {
layout: "main",
loginBtn: true
});
});
app.post("/login", requireLoggedOutUser, (req, res) => {
console.log("*************** /login POST ***********");
// console.log(`your name is: ${req.body.first} ${req.body.last}`);
let typedPW = req.body.password;
// ****CHANGE getUser to querie: JOIN users and signatures to get info about logged in user (password, signature)
getUser(req.body.email)
.then(result => {
let userId = result[0].id;
let userPW = result[0].password;
let first = result[0].first;
let last = result[0].last;
// console.log("userId in users table: ", userId);
// console.log("userPW safed in user table: ", userPW);
compare(typedPW, userPW).then(result => {
console.log("passwords do match: ", result);
if (result) {
// if password correct:
req.session.userId = userId;
req.session.first = first;
req.session.last = last;
// get users signature id and put in session if exists:
// console.log("userId: ", userId);
getSigID(userId)
.then(signatureId => {
// only happening when signatureId does exist
// console.log(
// "signatureId in signatures table: ",
// signatureId[0].id
// );
req.session.signatureId = signatureId[0].id;
res.redirect("/thanks");
})
.catch(err => {
// happening when signatureId does NOT exist (or there is another error)
console.log("err in getSigID", err);
res.redirect("/petition");
});
} else {
// if password wrong:
let loginErr = "wrong password or email!";
console.log(loginErr);
res.render("login", {
loginBtn: true,
loginErr
});
}
});
})
.catch(err => {
console.log("err in /login: ", err);
res.render("login", {
loginBtn: true,
err
});
});
});
app.get("/petition", requireLoggedInUser, requireNoSignature, (req, res) => {
console.log("*************** /petition GET ***********");
let first = req.session.first;
let last = req.session.last;
// console.log('this is the cookie session in petition route: ', req.session);
// if user is logged in:
res.render("petition", {
layout: "main",
editBtn: true,
first,
last
});
});
// app.get("/petition", requireNoSignature, (req, res) => {
// console.log("*************** /petition GET ***********");
// // console.log('this is the cookie session in petition route: ', req.session);
// // if user is logged in:
// if (req.session.userId) {
// let first = req.session.first;
// let last = req.session.last;
// // if user already has a signatureId in their cookies, send them to /thanks
// if (req.session.signatureId) {
// console.log("redirect to /thanks from /petition happening");
// res.redirect("/thanks");
// } else {
// res.render("petition", {
// layout: "main",
// first,
// last
// });
// }
// } else {
// // if user is not logged in:
// res.redirect("/register");
// }
// });
app.post("/petition", requireNoSignature, (req, res) => {
console.log("*************** /petition POST ***********");
// console.log(`your name is: ${req.body.first} ${req.body.last}`);
let timeStamp = new Date();
let first = req.session.first;
let last = req.session.last;
addSig(req.body.sig, timeStamp, req.session.userId)
.then(result => {
// console.log('timeStamp: ', timeStamp);
// console.log('result which includes the RETURNING data: ', result);
// GET ACTUAL ID HERE:
let id = result.rows[0].id;
// console.log(id);
req.session.signatureId = id;
res.redirect("/thanks");
})
.catch(err => {
console.log("err in /petition POST: ", err);
res.render("petition", {
err,
editBtn: true,
first,
last
});
});
});
app.get("/thanks", requireLoggedInUser, requireSignature, (req, res) => {
console.log("*************** /thanks Route ***********");
// console.log('req.session.signatureId: ', req.session.signatureId);
let signatureId = req.session.signatureId;
getSigs()
.then(signers => {
console.log("*************** /thanks Route ***********");
// console.log("signers.length: ", signers.length);
let numberOfSigners = signers.length;
req.session.numberOfSigners = numberOfSigners;
getSig(signatureId)
.then(result => {
let sigUrl = result[0].signature;
// console.log('sigUrl: ', sigUrl);
res.render("thanks", {
layout: "main",
editBtn: true,
signersBtn: true,
sigUrl,
numberOfSigners
});
})
.catch(err => {
console.log("err in getSig: ", err);
});
})
.catch(err => {
console.log("err in getSigs in /thanks: ", err);
});
});
app.get("/signers", requireLoggedInUser, requireSignature, (req, res) => {
console.log("*************** /signers GET ***********");
getSigners()
.then(signers => {
// console.log(signers);
res.render("signers", {
layout: "main",
editBtn: true,
signers
});
})
.catch(err => {
console.log("err in getSigs in /signers: ", err);
});
});
app.get("/signers/:city", requireLoggedInUser, requireSignature, (req, res) => {
console.log("*************** /signers/city GET ***********");
let city = req.params.city;
// console.log("city before: ", city);
// city = city.charAt(0).toUpperCase() + city.slice(1);
// console.log("city after: ", city);
let numberOfSigners = req.session.numberOfSigners;
getSignersInCity(city)
.then(signers => {
// console.log(signers);
res.render("signers_city", {
layout: "main",
editBtn: true,
signersBtn: true,
numberOfSigners,
signers,
city
});
})
.catch(err => {
console.log("err in getSignersInCity in /signers/city: ", err);
});
});
// --------------- Part 5: ------------------------------
app.get("/profile/edit", requireLoggedInUser, (req, res) => {
console.log("*************** /profile/edit Route***********");
let userId = req.session.userId;
let numberOfSigners = req.session.numberOfSigners;
let signatureId = req.session.signatureId;
getProfile(userId)
.then(profile => {
// console.log("profile: ", profile);
profile = profile[0];
// console.log("profile.first: ", profile.first);
res.render("profile_edit", {
layout: "main",
signersBtn: true,
numberOfSigners,
profile,
signatureId
});
})
.catch(err => {
console.log("err in getProfile in /profile/edit: ", err);
res.render("profile_edit", {
err
});
});
});
app.post("/profile/edit", requireLoggedInUser, (req, res) => {
console.log("*************** /profile/edit POST***********");
let userId = req.session.userId;
// console.log('new Name: ', req.body.first);
let signatureId = req.session.signatureId;
let url = req.body.homepage;
let age = req.body.age;
if (age === '') {
age = null;
}
if (!(url.startsWith("http://") || url.startsWith("https://"))) {
console.log("url of homepage is not safe!");
url = "";
}
if (req.body.password) {
console.log("password has been changed!");
hash(req.body.password).then(password => {
// console.log('hashedPW: ', password);
Promise.all([
updateUser4(
req.body.first,
req.body.last,
req.body.email,
password,
userId
),
upsertProfile(age, req.body.city, url, userId)
])
.then(() => {
let changes = "changes made successfully!";
console.log(changes);
res.render("profile_edit", {
changes,
signatureId
});
})
.catch(err => {
console.log(
"err in updateUser4 or upsertProfile in /profile/edit: ",
err
);
res.render("profile_edit", {
err,
signatureId
});
});
});
} else {
console.log("password stays the same");
Promise.all([
updateUser3(req.body.first, req.body.last, req.body.email, userId),
upsertProfile(req.body.age, req.body.city, url, userId)
])
.then(() => {
let changes = "changes made successfully!";
console.log(changes);
res.render("profile_edit", {
changes
});
})
.catch(err => {
console.log(
"err in updateUser3 or upsertProfile in /profile/edit: ",
err
);
res.render("profile_edit", {
err
});
});
}
});
app.post("/sig/delete", requireLoggedInUser, requireSignature, (req, res) => {
console.log("*************** /sig/delete POST***********");
deleteSig(req.session.signatureId)
.then(() => {
delete req.session.signatureId;
res.redirect("/petition");
})
.catch(err => {
console.log("err in deleteSig: ", err);
});
});
app.get("/logout", requireLoggedInUser, (req, res) => {
console.log("*************** /logout ***********");
req.session = null;
res.redirect("/login");
});
// to make supertest possible:
// console.log(require.main == module);
// only if someona calls "node ."" or "node index.js", will not run, when just called within a test module:
if (require.main == module) {
app.listen(process.env.PORT || 8080, () =>
console.log("port 8080 listening!")
);
}