This repository was archived by the owner on Jan 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
366 lines (316 loc) · 11.6 KB
/
app.js
File metadata and controls
366 lines (316 loc) · 11.6 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
#!/usr/bin/env node
console.log('#############################');
console.log('Mr. Green Gaming website');
console.log('#############################');
class App {
static initLog() {
const bunyan = require('bunyan');
global.log = bunyan.createLogger({
name: 'mrgreen-website',
streams: [
{
level: this.isDevelopment ? 'trace' : 'info',
stream: process.stdout
},
/*{
type: 'rotating-file',
path: 'logs/trace.log',
level: 'trace',
period: '1d',
count: 5
},*/
{
type: 'rotating-file',
path: 'logs/info.log',
level: 'info',
period: '1d',
count: 5
},
{
type: 'rotating-file',
path: 'logs/error.log',
level: 'warn',
period: '1d',
count: 5
},
{
type: 'rotating-file',
path: 'logs/fatal.log',
level: 'fatal',
period: '1d',
count: 5
}
],
src: false
//src: this.isDevelopment
});
}
static initConfig() {
const _ = require('lodash');
const module = './config/env.json';
delete require.cache[require.resolve(module)];
const env = require(module);
if (typeof(env[this.env]) !== 'object') {
log.warn('No custom environment config set!');
global.Config = env['base'];
} else
global.Config = _.defaultsDeep(_.clone(env[this.env]), env['base']);
if (!Config.configReloadTimeSeconds) {
log.warn('No config reload time set. Reloading is disabled.');
return;
}
setTimeout(() => {
log.debug('Reloading server configuration');
this.initConfig();
}, Config.configReloadTimeSeconds * 1000);
}
static initDatabases() {
return new Promise(async (resolve, reject) => {
const Database = require('./base/database');
let dbConfig = Config.databases.base;
global.db = new Database(dbConfig.socket, dbConfig.host, dbConfig.port, dbConfig.user, dbConfig.password, dbConfig.databaseName, dbConfig.connectionLimit);
dbConfig = Config.databases.forums;
global.forumsDb = new Database(dbConfig.socket, dbConfig.host, dbConfig.port, dbConfig.user, dbConfig.password, dbConfig.databaseName, dbConfig.connectionLimit);
try {
await db.connect();
await forumsDb.connect();
} catch (error) {
reject(error);
return;
}
resolve();
});
}
static initExpress() {
const Express = require('express');
const express = this.express = Express();
express.enable('strict routing');
express.enable('case sensitive routing');
express.disable('x-powered-by');
express.set('trust proxy', Config.http.trustProxy);
this.server = require('http').createServer(express);
//Body Parser
const bodyParser = require('body-parser');
express.use(bodyParser.json());
express.use(bodyParser.urlencoded({
extended: false
}));
//Fixes body being an array when coming from MTASA. Needs further investigation.
express.use('/', (req, res, next) => {
if (req.body instanceof Array && req.body.length === 1)
req.body = req.body[0];
next();
});
//Sessions
const session = require('express-session');
const mySqlStore = require('express-mysql-session')(session);
const sessionStore = new mySqlStore({
createDatabaseTable: true,
charset: 'utf8mb4_general_ci',
schema: {
tableName: 'sessions',
columnNames: {
session_id: 'sessionId',
expires: 'expires',
data: 'data'
}
}
}, db.getPool());
express.use(session({
secret: Config.http.cookieSecret,
secure: Config.http.cookieSecure,
resave: false,
store: sessionStore,
saveUninitialized: false,
name: 'mrgreen'
}));
//Marko render engine
require('marko/node-require').install();
const markoExpress = require('marko/express'); //enable res.marko
express.use(markoExpress());
express.locals.layout = '/views/layouts/defaultLayout.marko';
//Set Marko globals
express.locals.site = {
title: Config.site.title,
googleAnalyticsTrackingId: Config.site.googleAnalyticsTrackingId,
//description: '',
publicUrl: Config.site.publicUrl
};
express.locals.author = {
name: Config.site.author.name,
emailAddress: Config.site.author.emailAddress
};
}
static listenExpress() {
return new Promise((resolve, reject) => {
this.server.listen(Config.host.port, Config.host.address);
this.server.on('error', (error) => {
if (error.syscall !== 'listen')
throw error;
switch (error.code) {
case 'EACCES':
reject(new Error(`Host requires elevated privileges`));
break;
case 'EADDRINUSE':
reject(new Error(`Host is already in use`));
break;
default:
throw error;
}
});
this.server.on('listening', () => {
const addr = this.server.address();
const bind = typeof(addr.port) === 'string' ? `pipe ${addr.port}` : `port ${addr.port}`;
log.info(`Listening on ${addr.address} ${bind} (${addr.family})`);
resolve();
});
});
}
static initRoutes() {
const express = require('express');
const path = require('path');
this.express.use('/', express.static(path.join(__dirname, 'public'), {
etag: !App.isDevelopment
}));
//Get user when logged in
this.express.use('/', async (req, res, next) => {
const userId = req.session.userId;
if (typeof(userId) === 'number' && !req.user) {
try {
req.user = await Users.get(userId);
} catch(error) {
log.warn(error);
}
}
next();
});
this.express.use('/', require('./routes/static'));
//Strict routing redirects
this.express.get(['/games', '/account', '/greencoins', '/api'], (req, res) => {
const query = req.url.slice(req.path.length);
res.redirect(301, req.path + '/' + query);
});
this.express.use('/account/', require('./routes/account'));
this.express.use('/games/', require('./routes/games'));
this.express.use('/greencoins/', require('./routes/greencoins'));
this.express.use('/api/', require('./routes/api'));
//Remove trailing slash if not found
this.express.use((req, res, next) => {
const pathLength = req.path.length;
if (pathLength > 1 && req.path.lastIndexOf('/') === (pathLength - 1)) {
const query = req.url.slice(pathLength);
res.redirect(301, req.path.slice(0, -1) + query);
} else
next();
});
//Error Handler is our last stop
this.express.use((req, res, next) => {
const error = new Error('Not Found');
error.originalUrl = req.originalUrl;
error.path = req.path;
error.status = 404;
next(error);
});
//Deal with errors
this.express.use((error, req, res, next) => {
log.warn(`Express: ${JSON.stringify(error)}`);
if (!error.status)
error.status = 500;
switch (error.status) {
case 403:
error.statusMessage = 'No permission';
break;
case 404:
error.statusMessage = 'Not found';
break;
case 500:
error.statusMessage = 'An internal server error occurred';
break;
default:
error.statusMessage = 'A server error occurred';
break;
}
if (!error.message)
error.message = 'An unknown problem occurred. Please try again later.';
res.status(error.status);
const layout = require('./views/error.marko');
res.marko(layout, {
error,
isDevelopment: this.isDevelopment,
page: {
title: error.message,
description: error.statusMessage,
path: this.getExpressPath(req.baseUrl, req.path)
}
});
});
}
/**
* Helper function
* ToDo: Move to utility class
* @param {string} baseUrl
* @param {string} path
* @returns {string}
*/
static getExpressPath(baseUrl, path) {
return baseUrl.replace(/\/$/, '') + path.replace(/\/$/, '');
}
/**
* Initialize modules
* @return {Promise<void>}
*/
static initModules() {
return new Promise(async (resolve, reject) => {
this.modules = {};
const ApiApps = global.ApiApps = require('./base/apiApps');
const Games = global.Games = require('./base/games');
try {
await ApiApps.load();
await Games.load();
} catch (error) {
reject(error);
return;
}
global.Users = require('./base/users');
global.Utils = require('./utils/utils');
global.CommunityNews = require('./base/communityNews');
resolve();
});
}
static initPaths() {
const path = require('path');
this.paths = {
data: path.join(__dirname, 'data')
};
}
/**
* Init application
* @async
* @return {void}
*/
static async init() {
this.env = process.env.NODE_ENV;
this.isDevelopment = process.env.NODE_ENV === 'development';
this.initLog();
this.initConfig();
log.info(`Current environment: ${this.env} (debug: %s}`, this.isDevelopment);
this.initPaths();
//Display detailed info about Unhandled Promise rejections and Uncaught Exceptions
process.on('unhandledRejection', (reason, p) => log.fatal('Unhandled Rejection at:', p, 'reason:', reason));
process.on('uncaughtException', error => log.fatal('Uncaught Exception:', error));
try {
await this.initDatabases();
this.initExpress();
this.initRoutes();
await this.initModules();
await this.listenExpress();
} catch (error) {
log.error(error);
process.exit(1);
return;
}
log.info('Application is initialized and ready for use');
}
}
global.App = App;
App.init();