/
webServer.js
203 lines (181 loc) · 6.81 KB
/
webServer.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*
* INDEX FOR WEBSERVER
* contains all setup and routing for web requests
*/
//Dependencies
const config = require('./../config.js');
const http = require('http');
const https = require('https');
const StringDecoder = require('string_decoder').StringDecoder;
const fs = require('fs');
const path = require('path');
const url = require('url');
const handlers = require('./handlers');
const log = require('./../lib/log.js');
//Create the container
var server = {};
//Instanciate the http server
server.httpServer = http.createServer(function (req, res) {
server.getDataObject(req, function(data){
res.writeHead(301, {Location: `https://${data.headers.host}/${data.path}`});
res.end();
});
});
//https stuff
if(config['use-external-certs']){
server.httpsConfig = {
'key': fs.readFileSync(path.join(config['cert-path'], 'privkey.pem')),
'cert': fs.readFileSync(path.join(config['cert-path'], 'fullchain.pem'))
};
}else{
server.httpsConfig = {
'key': fs.readFileSync(path.join(__dirname, './certs/localhost.key')),
'cert': fs.readFileSync(path.join(__dirname, './certs/localhost.crt'))
};
}
//Instanciate the https server
server.httpsServer = https.createServer(server.httpsConfig, function (req, res) {
//Form the data object
server.getDataObject(req, function(data){
//Log the request
log.write(0, 'Web Request received', {data: data, sourceIP: req.connection.remoteAddress});
if(!config['use-external-certs']){
//FOR TESTING ONLY
var origHost = data.headers.host;
data.headers.host = 'thetxt.club'
data.headers.host = 'paxterya.com'
}
if(data.headers.hasOwnProperty('landingtesting')) data.headers.host = 'thetxt.club';
//Insert the correct path for different hosts
if(!data.path.startsWith('assets')){
if (data.headers.host.indexOf('thetxt.club') > -1) data.path = '/landing/' + data.path;
if (data.headers.host.indexOf('paxterya.com') > -1) data.path = '/paxterya/' + data.path;
}
if(!config['use-external-certs']){
//necessary for testing purposes
data.headers.host = origHost;
console.log(data.method, data.path)
if(data.method == 'post') console.log(data.payload);
}
//Check the path and choose a handler
var chosenHandler = handlers.assets;
for(key in router){
chosenHandler = data.path.startsWith(key) ? router[key] : chosenHandler;
}
//Send the request to the chosenHandler
try {
chosenHandler(data, function (statusCode, payload, contentType) {
server.processHandlerResponse(res, data.method, data.path, statusCode, payload, contentType);
});
} catch (e) {
console.log(e);
server.processHandlerResponse(res, data.method, data.path, 500, 'Internal server error :(\n(Please notify TxT#0001 on Discord if you see this!)', 'html');
}
});
});
const router = {
'/landing': handlers.landing,
'/paxterya': handlers.paxterya,
'/paxterya/api/application': handlers.paxapi.application,
'/paxterya/api/contact': handlers.paxapi.contact,
'/paxterya/login': handlers.paxLogin,
'/paxterya/staff': handlers.paxStaff
};
//Take a request and return a nice data object w/o payload
server.getDataObject = function (req, callback) {
var parsedUrl = url.parse(req.url, true);
//Try to get payload, if there is some
var decoder = new StringDecoder('utf-8');
var buffer = '';
req.on('data', function (data) {
buffer += decoder.write(data);
});
req.on('end', function () {
buffer += decoder.end();
try {
var jsonObject = JSON.parse(buffer);
} catch (e) {
var jsonObject = {};
}
var data = {
'path': parsedUrl.pathname.replace(/^\/+|\/+$/g, ''),
'queryStringObject': JSON.parse(JSON.stringify(parsedUrl.query)),
'method': req.method.toLowerCase(),
'headers': req.headers,
'payload': jsonObject
};
callback(data);
});
};
//Take the response from the handler and process it
server.processHandlerResponse = function (res, method, path, statusCode, payload, contentType) {
//Check responses from handler or use defaults
statusCode = typeof (statusCode) == 'number' ? statusCode : 200;
contentType = typeof (contentType) == 'string' ? contentType : 'html';
//Log 404 and 500 errors
if (statusCode == 404) log.write(0, 'Answered web request with 404', { path: path, payload: payload });
if (statusCode == 500) log.write(2, 'Answered web request with 500', { path: path, payload: payload });
//Build the response parts that are content specific
var payloadStr = '';
if(statusCode == 301 || statusCode == 302){
res.writeHead(statusCode, payload);
}else{
if (contentType == 'html') {
res.setHeader('Content-Type', 'text/html');
payloadStr = typeof (payload) == 'string' ? payload : '';
}
if (contentType == 'json') {
res.setHeader('Content-Type', 'application/json');
payloadStr = typeof (payload) == 'object' ? JSON.stringify(payload) : payload;
}
if (contentType == 'favicon') {
res.setHeader('Content-Type', 'image/x-icon');
payloadStr = typeof (payload) !== 'undefined' ? payload : '';
}
if (contentType == 'css') {
res.setHeader('Content-Type', 'text/css');
payloadStr = typeof (payload) !== 'undefined' ? payload : '';
}
if (contentType == 'png') {
res.setHeader('Content-Type', 'image/png');
payloadStr = typeof (payload) !== 'undefined' ? payload : '';
}
if (contentType == 'jpg') {
res.setHeader('Content-Type', 'image/jpeg');
payloadStr = typeof (payload) !== 'undefined' ? payload : '';
}
if (contentType == 'font') {
res.setHeader('Content-Type', 'application/octet-stream');
payloadStr = typeof (payload) !== 'undefined' ? payload : '';
}
if (contentType == 'svg') {
res.setHeader('Content-Type', 'image/svg+xml');
payloadStr = typeof (payload) !== 'undefined' ? payload : '';
}
if (contentType == 'js') {
res.setHeader('Content-Type', 'application/javascript');
payloadStr = typeof (payload) !== 'undefined' ? payload : '';
}
if (contentType == 'plain') {
res.setHeader('Content-Type', 'text/plain');
payloadStr = typeof (payload) !== 'undefined' ? payload : '';
}
res.writeHead(statusCode);
}
//Finish the response with the rest which is common
res.end(payloadStr);
};
//Init
server.init = function () {
//Start http server
server.httpServer.listen(config["http-port"], function () {
console.log('HTTP server online on port ' + config["http-port"]);
log.write(1, 'HTTP server is online', { 'port': config["http-port"] });
});
server.httpsServer.listen(config["https-port"], function () {
console.log('HTTPS server online on port ' + config["https-port"]);
log.write(1, 'HTTPS server is online', { 'port': config["https-port"] });
});
};
//Export the container
module.exports = server;