-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
108 lines (83 loc) · 2.41 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
// External Modules
const express = require('express');
const methodOverride = require("method-override");
const path = require('path');
const session = require('express-session')
const MongoStore = require('connect-mongo')(session)
// Interal Modules
const controllers = require('./controllers')
const db = require('./models')
// Instanced Modules
const app = express();
require('dotenv')
//add role to company in company Schema
// Configuration
const PORT = process.env.PORT || 4000;
// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride("_method"));
app.use(express.static('public'));
app.use('/jquery', express.static(__dirname + '/node_modules/jquery/dist/'));
// creates the session id on server side
app.use(session({
resave: false,
saveUninitialized:false,
secret: process.env.SECRET,
store: new MongoStore({
url: process.env.MONGODB_URI
}),
cookie:{
maxAge:1000 * 60 * 60 * 24 * 7 * 2
}
}))
// validates if user logs in
const authRequired = function(req, res , next){
//console.log(req.session.currentUser.id)
if(!req.session.currentUser){
return res.redirect('/login')
}
next();
};
// middleware to add user to all ejs views
app.use(function (req, res, next) {
res.locals.user = req.session.currentUser; // adds the user to all ejs views
res.locals.isAdmin = false;
next();
});
const checkRole = async (req, res, next) => {
try {
if (req.session.currentUser){
if (req.session.currentUser.role == 'admin') {
res.locals.isAdmin = true;
}
}
next();
} catch (error) {
console.log(error);
res.send({ message: "Internal server error" });
}
};
// ROUTES
// View Route
app.get('/', checkRole, async (req, res) => {
try {
const foundCompanies = await db.Company.find({});
const context = {
companies: foundCompanies,
};
res.render('home.ejs', context);
} catch (error) {
console.log(error);
res.send({ message: "Internal server error" });
}
});
// Auth Routes
app.use('/', controllers.auth)
// Company Route
app.use('/company', checkRole, controllers.company);
// User Route
app.use('/user', controllers.user);
// Booking Route
app.use('/booking', checkRole, controllers.booking);
// Server Listener
app.listen(PORT, () => console.log(`App is running on port ${PORT}`))