-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
109 lines (87 loc) · 2.31 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
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 8081;
const bodyParser = require("body-parser");
const api_routes = require("./api/routers/routes");
const mongoose = require('mongoose');
const signale = require('signale');
const config = require("./config/config");
const expressValidator = require('express-validator');
const session = require('express-session');
// initializing express
const app = express();
//configure database
mongoose.connect(config.mongodb.dbURI,config.mongodb.setting)
.then(() => {
signale.success('*****Database Connection Successfull******');
}).catch(err => {
signale.fatal(new Error(err));
signale.warn('Could not connect to Database. Exiting now...');
process.exit();
})
let db = mongoose.connection;
//configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.json({
type: ['application/json', 'text/plain']
}));
app.use(express.static(path.join(__dirname, 'public')));
app.set("view engine", "ejs");
// initialize express-session to allow us track the logged-in user across sessions.
app.use(session({
secret: config.session.secretString,
resave: true,
saveUninitialized: false
}))
// //sessionChecker middlewares
let sessionChecker = (req, res, next) => {
if (!req.session.user) {
res.redirect('/login')
} else {
next()
}
}
//check if already logged in.
let loggedIn = (req, res, next) => {
if (req.session.user) {
return res.redirect(`/user/game`);
}
return next()
}
// routes
app.use("/user", api_routes);
app.get("/login",loggedIn,(req,res) => {
res.render("Login");
});
app.get('/register',loggedIn,(req,res) => {
res.render('Register');
})
app.get("/",(req,res) => {
let loggedIn = false;
if(req.session.user){
loggedIn = true;
}
res.render("Home",{loggedIn});
})
app.get("/rules",(req,res) => {
let loggedIn = false;
if(req.session.user){
loggedIn = true;
}
res.render("Rules",{loggedIn});
})
app.get('/logout', sessionChecker, (req, res) => {
req.session.destroy(err => {
if (err) {
return next(err)
}
return res.redirect('/')
})
})
app.get("*",(req,res) => {
res.render("NotFound");
})
app.listen(PORT, () => {
signale.success(`Server is running on ${PORT}`);
});