-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
181 lines (153 loc) · 4.18 KB
/
app.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
'use strict';
// Import required modules
const bodyParser = require('body-parser');
const express = require('express');
const { engine } = require('express-handlebars');
const fs = require('fs');
const morgan = require('morgan');
const path = require('path');
const session = require('express-session');
const serveFavicon = require('serve-favicon');
const serveStatic = require('serve-static');
// Import user defined modules
const DatabaseConnectionPool = require('./lib/DatabaseConnectionPool');
const hbsHelpers = require('./lib/handlebarsHelpers.js');
const importJSON = require('./lib/importJSON');
/**
* loadRoutes() Loads all of the routes from /routers into a map
*
* @return {Array<Array<String, Object>>} Map of all of the routes
*/
function loadRoutes() {
return fs.readdirSync(path.join(__dirname, 'routes'))
.filter(file => file.endsWith('.js'))
.map(file => {
const route = require(path.join(
__dirname,
'routes',
file
));
return {
...route,
filename: file
};
})
.sort((a, b) => {
if (a.priority > b.priority || b.priority == null)
return 1;
if (a.priority < b.priority || a.priority == null)
return -1;
return 0;
});
}
async function main() {
// Import config files
const serverOptions = importJSON('server');
const sessionOptions = importJSON('session');
const dbp = await new DatabaseConnectionPool();
// Set up express-session to store in mysql database
const mysqlStore = require('express-mysql-session')(session);
const sessionStore = new mysqlStore({}, dbp.pool);
// Initialise express app
const app = express();
// Set up global database pool
app.use((req, res, next) => {
req.db = dbp;
next();
});
// Set up templating language and path
app.engine(
'hbs',
engine({
extname: '.hbs',
helpers: hbsHelpers,
runtimeOptions: {
allowProtoPropertiesByDefault: true,
allowProtoMethodsByDefault: true
}
})
);
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));
// Set up parsers to allow reading of POST form data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan('tiny'));
// Set up routes for static files
app.use(serveFavicon(path.join(__dirname,
'public/assets/favicon.ico')));
app.use('/', serveStatic(path.join(__dirname, 'public')));
// Set up session middleware
app.use(session({
secret: sessionOptions.sessionSecret,
saveUninitialized: false,
resave: false,
store: sessionStore,
cookie: {
maxAge: sessionOptions.sessionLifetime,
sameSite: true
}
}));
// Generic handlebars context
app.use((req, res, next) => {
req.hbsContext = {
name: req.session?.fullName,
userType: req.session?.userType,
title: 'Stratos'
};
next();
});
/*
* Authentication middleware that redirects unauthenticated users
* back to the login page if they request a page they don't have access
* to
*/
app.use((req, res, next) => {
const allowed = [
'/login',
'/register',
'/password-reset',
'/change-password',
'/contact',
'/'
];
// Extract the first component of the path from the request
const path = `/${req.path.split('/')?.[1] ?? ''}`;
if (!allowed.includes(path) && !req.session.authenticated)
return res.redirect(`/login?redirect_to=${req.path}`);
else if (req.path !== '/admin/parent-login' &&
!allowed.includes(path) &&
req.session.userType === 'parent'
)
return res.redirect('/admin/parent-login');
next();
});
app.get('*', (req, res, next) => {
req.app.locals.layout = 'main';
next();
});
app.get('/admin/*', (req, res, next) => {
req.app.locals.layout = 'admin';
next();
});
for (const route of loadRoutes())
app.use(route.root, route.router);
/*
* If the request gets to the bottom of the route stack, it doesn't
* have a defined route and therefore a HTTP status code 404 is sent
* and an error page shown
*/
app.use((req, res) => {
res.status(404).render('error', {
...req.hbsContext,
title: 'Stratos - Error',
code: 404,
msg: 'Page Not Found'
});
});
// Start the server
app.listen(serverOptions.port, () => {
console.log(`Server listening on :${serverOptions.port}`);
});
}
main().catch(console.error);