This repository has been archived by the owner on Jun 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
316 lines (252 loc) · 7.87 KB
/
router.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
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
/*
Copyright 2017 Emil Hemdal (https://emil.hemdal.se/) and
Datateknologsektionen Chalmers Studentkår (https://www.dtek.se/)
This file is part of tv.dtek.se.
tv.dtek.se is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
tv.dtek.se is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with tv.dtek.se. If not, see <http://www.gnu.org/licenses/>.
*/
const config = require('./config.json');
const updateJSON = require('./updateJSON.js');
const process = require('process');
const http = require('http');
const fs = require('fs');
const express = require('express');
let mysql = require('mysql');
// Probably overkill using connectionpooling here!
let pool = mysql.createPool(config.mysql);
const bodyParser = require('body-parser');
const multiparty = require('multiparty');
const moment = require('moment');
const crypto = require('crypto');
const pug = require('pug');
const admin = pug.compileFile('./views/admin.pug');
const addNew = pug.compileFile('./views/addNew.pug');
const unauthed = pug.compileFile('./views/unauthed.pug');
const router = express.Router();
router.use(bodyParser.urlencoded({extended: false, })); // Yes, let that comma be there. JSHint is setup to complain otherwise.
router.use((req, res, next) => {
if(process.env.NODE_ENV && process.env.NODE_ENV === 'development') {
req.tv = {
data: {
user: {
cid: 'testing',
fullName: 'Testing Testsson',
},
},
};
return next();
}
if(!req.headers.cookie) {
res.redirect(config.redirectToAuth + '/admin');
return res.end();
}
validateUser(req.headers.cookie, (err, userData) => {
if(err) {
if(err === 'unauthed') {
res.type('html');
return res.end(unauthed());
}
console.error(err);
res.status(503);
return res.end('An error occured!');
}
req.tv = {};
req.tv.data = userData;
next();
});
});
router.get('//addNew', (req, res) => { // Yes, double slash...
res.type('html');
let addNewData = {
user: req.tv.data.user,
error: req.query.error ? req.query.error : null,
};
res.end(addNew(addNewData));
});
function advertActiveState(req, res, active) {
let poolQueryParameters = [
active,
req.params.id,
];
pool.query('UPDATE advert SET active = ? WHERE id = ?', poolQueryParameters, (err) => {
if(err) {
console.error(err);
res.status(503);
return res.end("An error occured!");
}
res.redirect('/admin');
res.end();
updateJSON();
}
);
}
router.get('//disable/:id', (req, res) => { // Yes, double slash...
advertActiveState(req, res, 0);
});
router.get('//enable/:id', (req, res) => { // Yes, double slash...
advertActiveState(req, res, 1);
});
router.post('//addNew', (req, res) => { // Yes, double slash...
let form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
if(err) {
console.error(err);
res.status(503);
return res.end('An error occured!');
}
let data = {
name: null,
committee: null,
startDate: null,
startTime: null,
endDate: null,
endTime: null,
};
for(let prop in fields) {
if(fields.hasOwnProperty(prop)) {
if(fields[prop][0].length === 0) {
res.redirect('/admin/addNew?error=somethingIsMissing1');
return res.end();
}
}
}
for(let prop in data) {
if(data.hasOwnProperty(prop)) {
if(typeof fields[prop] !== 'object') {
res.redirect('/admin/addNew?error=somethingIsMissing2');
return res.end();
}
data[prop] = fields[prop][0];
if(typeof data[prop] !== 'string' || data[prop].length === 0) {
res.redirect('/admin/addNew?error=somethingIsMissing3');
return res.end();
}
}
}
let mEndDate = moment(data.endDate + ' ' + data.endTime, 'YYYY-MM-DD HH:mm');
let mStartDate = moment(data.startDate + ' ' + data.startTime, 'YYYY-MM-DD HH:mm');
if(!mStartDate.isValid() ||
!mEndDate.isValid() ||
mEndDate.isBefore(mStartDate)) {
res.redirect('/admin/addNew?error=checkYourDates');
return res.end();
}
if(files.file.length !== 1) {
res.redirect('/admin/addNew?error=noFileUploaded');
return res.end();
}
let hash = crypto.createHash('sha256');
let fd = fs.createReadStream(files.file[0].path);
let ofn = files.file[0].originalFilename;
hash.setEncoding('hex');
// console.log(mEndDate.unix());
fd.on('end', () => {
hash.end();
let hashString = hash.read();
let fdr = fs.createReadStream(files.file[0].path);
let newFileName = hashString + ofn.substring(ofn.lastIndexOf('.'));
let fdw = fs.createWriteStream('serve/img/' + newFileName);
fdr.pipe(fdw);
fdw.on('finish', () => { // Order of definitions regarding ".on" may matter
let poolQueryParameters = [
mStartDate.unix(),
mEndDate.unix(),
data.name,
data.committee,
ofn,
newFileName,
req.tv.data.user.cid,
data.tempPriority === 'on' ? 1 : 0,
];
pool.query('INSERT INTO ' +
'advert(active, startDate, endDate, name, committee, originalFilename, currentFilename, author, tempPriority) '+
'VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?);',
poolQueryParameters,
(err) => {
if(err) {
console.error(err);
res.status(503);
return res.end("An error occured!");
}
res.redirect('/admin');
res.end();
updateJSON();
}
);
});
});
fd.pipe(hash);
});
});
router.get('//', (req, res) => { // Yes, double slash!
pool.query('SELECT * FROM advert ORDER BY endDate DESC;', (error, results) => {
if(error) {
console.error(error);
res.status(503);
return res.end('An error occured!');
}
res.type('html');
let pugParameters = {
user: req.tv.data.user,
adverts: results,
now: Math.round(Date.now() / 1000),
};
res.end(admin(pugParameters));
});
});
function validateUser(cookieData, callback) {
validateCookie(cookieData, (err, data) => {
if(err) {
return callback(err);
}
let poolQueryParameters = [
data.user.cid,
];
pool.query('SELECT cid FROM admins WHERE cid = ?;', poolQueryParameters, (error, results) => {
if(error) {
return callback(error);
}
if(results.length !== 1) {
return callback('unauthed');
}
callback(null, data);
});
});
}
function validateCookie(cookieData, callback) {
let validateCookieGetParams = config.externalAuthServerConfig;
validateCookieGetParams.headers = {
cookie: cookieData,
};
http.get(validateCookieGetParams, (res) => {
if (res.statusCode !== 200) {
return callback('error1');
} else if (!/^application\/json/.test(res.headers['content-type'])) {
return callback('error2');
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
let parsedData = JSON.parse(rawData);
callback(null, parsedData);
} catch (e) {
console.error(e.message);
callback('error3');
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
callback('error4');
});
}
module.exports = router;