This repository was archived by the owner on Jan 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1085 lines (974 loc) · 27.9 KB
/
server.js
File metadata and controls
1085 lines (974 loc) · 27.9 KB
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const dotenv = require("dotenv").config();
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const fetch = require("node-fetch");
const FormData = require("form-data");
//For News page
const NewsAPI = require("newsapi");
const newsapi = new NewsAPI(process.env.NEWSAPI_KEY);
//For Search page
const igdb = require("igdb-api-node").default;
const client = igdb(process.env.IGDB_KEY);
const pgp = require("pg-promise")();
const bcrypt = require("bcrypt");
const passport = require("passport");
const cookieParser = require("cookie-parser");
const expressSession = require("express-session");
const LocalStrategy = require("passport-local").Strategy;
const getUser = req => {
const user = req.user
? {
username: req.user.gamer_name,
userId: req.user.id
}
: { username: null, userId: null };
return {
data: JSON.stringify(user)
};
};
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/static", express.static("static"));
app.use(cookieParser());
app.use(
require("express-session")({
secret: "some random text #^*%!!", // used to generate session ids
resave: false,
saveUninitialized: false
})
);
// Database connection
const db = pgp({
host: "localhost",
port: 5432,
database: process.env.DATABASE,
user: process.env.USERNAME,
password: process.env.PASSWORD
});
//Fetches Top TWITCH Data streams - Twitch channel/user names & photos etc
app.get("/twitchStreams", (req, res) => {
var headers = {
"Client-ID": process.env.TWITCH_KEY
};
fetch(`https://api.twitch.tv/helix/streams?first=5&language=en`, {
method: "GET",
headers
})
.then(
response => (response.ok ? response.json() : Promise.reject(response))
)
.then(result => {
return result.data.map(twitchUser => {
return fetch(
`https://api.twitch.tv/helix/users?id=${twitchUser.user_id}`,
{
method: "GET",
headers
}
);
});
})
.then(result => {
return Promise.all(result);
// console.log("twitcher info", result.data);
})
.then(results => {
return results.map(result => result.json());
})
.then(result => {
return Promise.all(result);
// console.log("twitcher info", result.data);
})
.then(results => {
// console.log("twitcher info", results);
res.json(results);
})
.catch(error => {
console.log(error);
});
});
// Login starts
const SALT_ROUNDS = 12;
/* helper function to get user by username */
function getUserByUsername(username) {
return db
.one(`SELECT * FROM gamer WHERE gamer_name = $1`, [username])
.catch(error => console.log(error.message));
}
function getUserById(id) {
return db
.one(`SELECT * FROM gamer WHERE id = $1`, [id])
.catch(error => console.log(error.message));
}
function getUserAvatarById(id) {
return db
.one(`SELECT avatar FROM gamer_profile WHERE gamer_id = $1`, [id])
.catch(error => console.log(error.message));
}
///////////////// Forum - start //////////////////
app.get("/api/forum", function(req, res) {
db.any(`SELECT * FROM forum ORDER BY title ASC`)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.get("/api/forum/:id", function(req, res) {
db.one(`SELECT * FROM forum WHERE id = $1`, [req.params.id])
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.get("/api/forum/search/:name", function(req, res) {
db.any(`SELECT * FROM forum WHERE title ILIKE \'%$1#%\'`, [req.params.name])
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.get("/api/post/:id", function(req, res) {
db.any(
`SELECT * FROM post WHERE parent_id is null AND forum_id = $1 ORDER BY created DESC`,
[req.params.id]
)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.get("/api/post/:id/search/:name", function(req, res) {
db.any(
`SELECT * FROM post WHERE parent_id is null AND forum_id = $1
AND (title ILIKE \'%$2#%\' OR body ILIKE \'%$2#%\') ORDER BY created DESC`,
[req.params.id, req.params.name]
)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
// Get gamer's posts
app.get("/api/userposts/:id", function(req, res) {
db.manyOrNone(
`SELECT * FROM post WHERE gamer_id = $1 ORDER BY created DESC`,
[req.params.id]
)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
// Get posts that are parent (thread)
app.get("/api/parentpost/:id", function(req, res) {
db.one(`SELECT * FROM post WHERE id = $1`, [req.params.id])
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
// Get posts that are replies of a parent post
app.get("/api/postsbyparent/:parentid", function(req, res) {
db.manyOrNone(`SELECT * FROM post WHERE parent_id = $1`, [
req.params.parentid
])
.then(data => res.json(data))
.catch(error => console.log("/api/postsbyparent/:parentid", error.message));
});
// Get user's avatar
app.get("/api/getgameravatar/:gamer_id", function(req, res) {
db.oneOrNone(`SELECT avatar FROM gamer_profile WHERE gamer_id = $1`, [
req.params.gamer_id
])
.then(data => res.json(data))
.catch(error => console.log("/api/getgameravatar", error.message));
});
app.get("/api/reply/:id", function(req, res) {
db.any(`SELECT * FROM post WHERE parent_id = $1 ORDER BY created ASC`, [
req.params.id
])
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.get("/api/reply/:id/search/:name", function(req, res) {
db.any(
`SELECT * FROM post WHERE
(title ILIKE \'%$2#%\' OR body ILIKE \'%$2#%\') AND parent_id = $1 `,
[req.params.id, req.params.name]
)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.post("/api/reply", function(req, res) {
const { title, body, parent_id, forum_id, gamer_id, gamer_name } = req.body;
db.one(
`INSERT INTO post(title, body, parent_id, forum_id, gamer_id, gamer_name)
VALUES($1, $2, $3, $4, $5, $6) RETURNING id`,
[title, body, parent_id, forum_id, gamer_id, gamer_name]
)
.then(data => {
db.any(`SELECT * FROM post WHERE parent_id = $1`, [parent_id])
.then(data => {
db.none(
`UPDATE gamer_profile SET totalposts = totalposts+1 where gamer_id = $1`,
[gamer_id]
);
res.json(data);
})
.catch(error => console.log(error.message));
// res.json(Object.assign({}, {id: data.id}, req.body));
})
.catch(error => {
res.json({
error: error.message
});
});
});
app.post("/api/post", function(req, res) {
const { title, body, forum_id, gamer_id, gamer_name } = req.body;
db.one(
`INSERT INTO post(title, body, forum_id, gamer_id, gamer_name)
VALUES($1, $2, $3, $4, $5) RETURNING id`,
[title, body, forum_id, gamer_id, gamer_name]
)
.then(data => {
db.any(
`SELECT * FROM post WHERE parent_id is NULL AND forum_id= $1 ORDER BY created DESC`,
[forum_id]
)
.then(data => {
db.none(
`UPDATE gamer_profile SET totalposts = totalposts+1 where gamer_id = $1`,
[gamer_id]
);
res.json(data);
})
.catch(error => console.log(error.message));
// res.json(Object.assign({}, {id: data.id}, req.body));
})
.catch(error => {
res.json({
error: error.message
});
});
});
app.post("/api/post-edit", function(req, res) {
const { newTitle, newBody, post_id, forum_id } = req.body;
db.one(
`UPDATE post SET title = $1, body = $2 WHERE id = $3
RETURNING id;`,
[newTitle, newBody, post_id]
)
.then(data => {
db.any(
`SELECT * FROM post WHERE parent_id is NOT NULL AND forum_id= $1 ORDER BY created DESC`,
[forum_id]
)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
})
.catch(error => console.log(error.message));
});
app.post("/api/postreport/:id", function(req, res) {
const { selectId } = req.body;
const review = "review";
db.one(`UPDATE post SET admin_status = $1 WHERE id = $2;`, [review, selectId])
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.get("/api/reviewposts", function(req, res) {
db.any(
"SELECT body, post.id, post.title, gamer.gamer_name, forum.title AS forum_title FROM post, gamer, forum WHERE admin_status = 'review' AND post.gamer_id = gamer.id AND post.forum_id = forum.id;"
)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.post("/api/review-delete/:id", function(req, res) {
const { id } = req.body;
const deletedPost = "this post was deleted by a moderator";
const deletedStatus = "delete";
db.one(`UPDATE post SET body = $1, admin_status = $2 WHERE id = $3;`, [
deletedPost,
deletedStatus,
id
])
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.post("/api/review-clear/:id", function(req, res) {
const { id } = req.body;
const clearedStatus = "clear";
db.one(`UPDATE post SET admin_status = $1 WHERE id = $2;`, [
clearedStatus,
id
])
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.post("/api/review-block/:id", function(req, res) {
const { id } = req.body;
const resetPassword = "admin";
const blocked = "blocked";
db.one(`UPDATE gamer SET password_hash = $1, status = $2 WHERE id = $3;`, [
resetPassword,
blocked,
id
])
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.get("/api/deletedposts", function(req, res) {
db.any(
"SELECT body, post.id, post.title, gamer.gamer_name, forum.title AS forum_title FROM post, gamer, forum WHERE admin_status = 'delete' AND post.gamer_id = gamer.id AND post.forum_id = forum.id;"
)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.post("/api/newforum", function(req, res) {
const { title, gameId, category, mp, gamerId, gamerName} = req.body;
db.one(`INSERT INTO forum (title, game_Id, category) VALUES ($1, $2, $3) RETURNING id`, [
title,
gameId,
category
])
.then(data => {
if(mp){
db.none(`INSERT INTO post (id, title, forum_id, gamer_id, body, gamer_name)
VALUES (0, 'Looking for a group', $1, $2, 'reply to this post to raid with a group', $3 )`,
[data.id,
gamerId,
gamerName]
)}
})
.catch(error => console.log(error.message));
});
///////////////// Forum - end //////////////////
///////////////// Account Updates - Starts /////////////////
// Avatar Update
app.post("/api/account/avatar", function(req, res) {
const { gamer_id, avatar } = req.body;
if (avatar) {
db.one(
`UPDATE gamer_profile SET avatar = $2
WHERE gamer_id = $1`,
[gamer_id, avatar]
)
.then(data => {
return { status: "success" };
})
.catch(error => {
res.json({
error: error.message
});
});
}
});
// Fortnite name Update
app.post("/api/account/fortnitename", function(req, res) {
console.log("req.body", req.body);
const { gamer_id, fortniteName } = req.body;
if (fortniteName) {
db.one(
`UPDATE gamer_profile SET fortniteName = $2
WHERE gamer_id = $1`,
[gamer_id, fortniteName]
)
.then(data => {
return { status: "success" };
})
.catch(error => {
res.json({
error: error.message
});
});
}
});
// Email Update
app.post("/api/account/emailupdate", function(req, res) {
console.log("req.body", req.body);
const { gamer_id, email } = req.body;
if (email) {
db.one(
`UPDATE gamer SET email = $2
WHERE id = $1`,
[gamer_id, email]
)
.then(data => {
return { status: "success" };
})
.catch(error => {
res.json({
error: error.message
});
});
}
});
// Description Update
app.post("/api/account/description", function(req, res) {
const { gamer_id, desc } = req.body;
if (desc) {
db.one(
`UPDATE gamer_profile SET description = $2
WHERE gamer_id = $1`,
[gamer_id, desc]
)
.then(data => {
return { status: "success" };
})
.catch(error => {
res.json({
error: error.message
});
});
}
});
///////////////// Account Updates - Ends //////////////////
///////////////// profile - start //////////////////
app.get("/api/gamer/:id", function(req, res) {
db.one(
`SELECT gamer_profile.*, gamer.gamer_name, gamer.email FROM gamer_profile
INNER JOIN gamer ON gamer.id=$1 WHERE gamer_profile.gamer_id =$1;`,
[req.params.id]
)
.then(profile => {
db.any(
`SELECT * FROM game, gamer_favorites WHERE gamer_favorites.gamer_id = $1
AND game.id = gamer_favorites.game_id`,
[req.params.id]
)
.then(favs => {
res.json({ profile: profile, favs: favs });
})
.catch(error => console.log(error.message));
})
.catch(error => console.log(error.message));
});
app.post("/api/newfavourite/", function(req, res) {
//check if game exists in game table
db.one(`SELECT * FROM game WHERE igdb_id = $1`, [req.body.igdb])
.then(data1 => {
console.log(data1.id);
// game exists in game table => check if it exists in gamer_favorites
db.one(
`SELECT * FROM gamer_favorites WHERE game_id = $1
AND gamer_id = $2`,
[data1.id, req.body.gamerId]
)
.then(data2 => {
//game already exists in gamer_favorites. Returning
res.json({ msg: "game is already there" });
})
.catch(error => {
// game doesnt exists in gamer_favorites. Adding
db.one(
`INSERT INTO gamer_favorites(game_id, gamer_id)
VALUES($1, $2) RETURNING id`,
[data1.id, req.body.gamerId]
)
.then(data3 => {
res.json({ msg: "added fav" });
})
.catch(error => {
res.json({
error: error.message
});
});
});
})
.catch(error => {
//game doesnt exsits in game table, Adding to game table
console.log("doesnt exist");
db.one(
`INSERT INTO game(title, igdb_id,cover)
VALUES($1, $2,$3) RETURNING id`,
[req.body.title, req.body.igdb, req.body.cover]
)
.then(data4 => {
db.one(
`INSERT INTO gamer_favorites(game_id, gamer_id)
VALUES($1, $2) RETURNING id`,
[data4.id, req.body.gamerId]
)
.then(data5 => {
res.json({ msg: "added game and fav" });
})
.catch(error => console.log(error.message));
// res.json(Object.assign({}, {id: data.id}, req.body));
})
.catch(error => {
res.json({
error: error.message
});
});
});
});
// gets all GAME favourites per user
app.get("/api/favourites/:id", function(req, res) {
db.any(
`SELECT * FROM game, gamer_favorites WHERE gamer_favorites.gamer_id = $1
AND game.id = gamer_favorites.game_id`,
[req.params.id]
)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
// gets all TWITCH favourites per user
app.get("/api/twitchfavourites/:id", function(req, res) {
db.any(`SELECT * FROM twitch_favorites WHERE gamer_id = $1 `, [
req.params.id
])
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
// adds TWITCH favourite to database
app.post("/api/addtwitchfavourite", function(req, res) {
var headers = {
"Client-ID": process.env.TWITCH_KEY
};
fetch(`https://api.twitch.tv/helix/users?login=${req.body.twitchName}`, {
method: "GET",
headers
})
.then(
response => (response.ok ? response.json() : Promise.reject(response))
)
.then(result => {
const twitch_image = result.data[0]["profile_image_url"];
return twitch_image;
})
.then(twitch_image => {
//Original insert below
db.one(
`INSERT INTO twitch_favorites(twitch_name, gamer_id,twitch_image)
VALUES($1, $2, $3) RETURNING id`,
[req.body.twitchName, req.body.gamerId, twitch_image]
)
.then(data => {
res.json({ msg: "added" });
})
.catch(error => {
res.json({
error: error.message
});
});
});
});
app.get("/api/gamer/post/:id", function(req, res) {
db.any(
`SELECT * FROM post WHERE parent_id is null AND gamer_id = $1 ORDER BY created DESC`,
[req.params.id]
)
.then(posts => {
db.any(
`SELECT * FROM post WHERE parent_id IS NOT NULL AND gamer_id = $1 ORDER BY created DESC`,
[req.params.id]
)
.then(replies => {
res.json({ posts: posts, replies: replies });
})
.catch(error => console.log(error.message));
// res.json(data);
})
.catch(error => console.log(error.message));
});
app.get("/api/profile/:username", function(req, res) {
db.one(`SELECT * FROM gamer_profile WHERE gamer_name = $1`, [
req.params.username
])
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.get("/api/allgames/", function(req, res) {
db.any(`SELECT * FROM game`)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
///////////////// profile - end //////////////////
///////////////// homepage - start //////////////////
app.get("/api/featured/", function(req, res) {
db.one(
`SELECT gamer_name, gamer_id,avatar FROM gamer_profile ORDER BY RANDOM() LIMIT 1`
)
.then(gamer => {
db.one(`SELECT title, igdb_id FROM game ORDER BY RANDOM() LIMIT 1`)
.then(game => {
db.one(`SELECT title, id FROM forum ORDER BY RANDOM() LIMIT 1`)
.then(forum => {
res.json({ gamer, game, forum });
})
.catch(error => console.log(error.message));
})
.catch(error => console.log(error.message));
})
.catch(error => console.log(error.message));
});
app.get("/api/voteresults", function(req, res) {
db.any(`SELECT title, COUNT(title) FROM poll GROUP BY title`)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
app.post("/api/vote", function(req, res) {
const { title, value, gamer_id, gamer_name } = req.body;
db.one(
`INSERT INTO poll(value, title, gamer_id, gamer_name)
VALUES($1, $2, $3, $4) RETURNING id`,
[value, title, gamer_id, gamer_name]
)
.then(data => {
res.json({ msg: "thank you for voting" });
})
.catch(error => {
res.json({ msg: "you already voted" });
});
});
app.get("/api/top5forums", function(req, res) {
db.any(
`SELECT post.forum_id, COUNT(post.forum_id), forum.title FROM post, forum
WHERE post.forum_id = forum.id GROUP BY post.forum_id, forum.title ORDER BY count DESC LIMIT 5`
)
.then(data => {
res.json(data);
})
.catch(error => console.log(error.message));
});
///////////////// homepage - end //////////////////
function compare(plainTextPassword, hashedPassword) {
return bcrypt.compare(plainTextPassword, hashedPassword).then(matches => {
// matches will be true if plain text password is the same as hashedPassword once it has been hashed.
return matches;
});
}
// serialise user into session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// deserialise user from session
passport.deserializeUser(function(id, done) {
getUserById(id).then(user => {
done(null, user);
});
});
// configure passport to use local strategy
// that is use locally stored credentials
passport.use(
new LocalStrategy(function(username, password, done) {
let _user;
getUserByUsername(username)
.then(user => {
if (!user) return done(null, false);
_user = user;
return compare(password, user.password_hash);
})
.then(passwordMatches => {
if (!passwordMatches) return done(null, false);
return done(null, _user);
})
.catch(error => done(error, false));
})
);
// initialise passport and session
app.use(passport.initialize());
app.use(passport.session());
// middleware function to check user is logged in
function isLoggedIn(req, res, next) {
if (req.user && req.user.id) {
next();
} else {
res.redirect("/login");
}
}
// route to log out users
app.get("/logout", function(req, res) {
req.logout();
res.redirect("/");
});
// Login ends
// only accessible to logged in users
app.get("/dashboard", isLoggedIn, function(req, res) {
getUserAvatarById(req.user.id).then(avatar => {
if (req.user.id) {
res.render("index", {
data: JSON.stringify({
username: req.user.gamer_name,
userId: req.user.id,
avatar: avatar ? avatar.avatar : ""
})
});
} else {
res.render("index", getUser(req));
}
});
});
app.get("/dashboard/account", isLoggedIn, function(req, res) {
getUserAvatarById(req.user.id)
.then(avatar => {
if (req.user.id) {
res.render("index", {
data: JSON.stringify({
username: req.user.gamer_name,
userId: req.user.id,
avatar: avatar ? avatar.avatar : ""
})
});
} else {
res.render("index", getUser(req));
}
})
.catch(error => console.log(error.message));
});
app.set("view engine", "hbs");
// app.get("/", function (req, res) {
// res.render("index", {});
// });
app.get("/", function(req, res) {
res.render("index", getUser(req));
});
app.get("/homepage", function(req, res) {
if (req.user) {
res.render("index", {
data: JSON.stringify({
username: req.user.gamer_name,
userId: req.user.id
})
});
} else {
res.render("index", getUser(req));
}
});
app.get("/login", function(req, res) {
res.render("login", getUser(req));
});
// route to accept logins
app.post("/login", passport.authenticate("local", { session: true }), function(
req,
res
) {
res.status(200).end();
});
// register page
app.get("/signup", function(req, res) {
res.render("signup", getUser(req));
});
app.post("/signup", (req, res) => {
const { signupUsername, signupPassword, signupEmail } = req.body;
pass = signupPassword;
bcrypt
.genSalt(SALT_ROUNDS)
.then(salt => {
return bcrypt.hash(signupPassword, salt);
})
.then(hashedPassword => {
db.one(
`
INSERT INTO gamer (gamer_name, password_hash, email)
VALUES ($1, $2, $3) RETURNING id;
`,
[signupUsername, hashedPassword, signupEmail]
)
.then(data => {
db.one(
`
INSERT INTO gamer_profile (gamer_name, gamer_id)
VALUES ($1, $2) RETURNING id;
`,
[signupUsername, data.id]
)
.then(data2 => {
res.status(200).end();
})
.catch(error =>
console.log("Gamer_profile error: ", error.message)
);
})
.catch(error => console.log("Gamer error: ", error.message));
});
});
//Main GAMES search for specific title
app.get("/games/:title", (req, res) => {
const gameTitle = req.params.title;
client
.games(
{
filters: {
"name-in": gameTitle
},
order: "popularity:desc"
},
["*"]
)
.then(response => {
res.json(response);
})
.catch(error => {
console.log("You have 2 lives remaining ", error);
});
});
//This search is executed when a favourite is clicked on due to the search limitations of the API not finding the game by exact title
app.get("/gameid/:id", (req, res) => {
const gameTitle = req.params.id;
client
.games({
ids: [gameTitle],
order: "release_dates.date:asc",
fields: "*", // Return all fields
limit: 5, // Currently limited to 5 results
offset: 15 // Index offset for results
})
.then(response => {
res.json(response);
})
.catch(error => {
console.log("You have 2 lives remaining ", error);
});
});
//Load themes and genres once on component did mount to speed up search
app.get("/themes/", (req, res) => {
const themeId = req.params.title;
client
.themes({
fields: "id,name",
limit: 50 // Limit to 50 results
})
.then(response => {
res.json(response);
})
.catch(error => {
console.log("You have 2 lives remaining ", error);
});
});
app.get("/genres/", (req, res) => {
const genreId = req.params.genreId;
client
.genres({
fields: "id,name", // Return all fields
limit: 50 // Limit to 50 results
})
.then(response => {
// response.body contains the parsed JSON response to this query
res.json(response);
})
.catch(error => {
console.log("You have 2 lives remaining ", error);
});
});
//Main general NEWS search for latest Gaming/tech articles
app.get("/newsApi/:pageNum", (req, res) => {
const page = req.params.pageNum;
newsapi.v2
.everything({
sources: "ign",
language: "en",
sortBy: "publishedAt",
pageSize: 10,
page
})
.then(response => {
res.json(response);
})
.catch(error => {
console.log("You have 2 lives remaining ", error);
});