-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
391 lines (326 loc) · 9.12 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
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
var http = require('http');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var spawn = require('child_process').spawn;
const jwt = require('jsonwebtoken');
const TOKEN_SECRET = require('crypto').randomBytes(64).toString('hex');
const dotenv = require('dotenv');
const crypto = require("crypto");
var bcrypt = require('bcryptjs');
const fs = require('fs');
dotenv.config();
const USER_NAME = process.env.USER_NAME;
const USER_ID = process.env.USER_ID;
const USER_PASSWORD = process.env.USER_PASSWORD;
var token_random_time = crypto.randomInt(0, 100000000);
var token_salt_ramdon = bcrypt.genSaltSync(10);
var seasons = [];
function readSeasons(req, res){
try {
const file = fs.readFileSync('seasons.json');
seasons = JSON.parse(file.toString());
res.json(seasons);
} catch (error) {
console.log("failed to read seasons");
console.error(error);
res.statusCode=500;
res.json({status: "failed"});
}
}
function writeSeasons(req, res){
try {
fs.writeFileSync('seasons.json', JSON.stringify(seasons));
res.json({status: "success"});
} catch (error) {
console.log("failed to save seasons");
console.error(error);
res.statusCode=500;
res.json({status: "failed"});
}
}
var app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', ['*']);
res.append('Access-Control-Allow-Methods', 'OPTIONS,GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//app.use(express.static(path.join(__dirname, 'public')));
var publicDir = path.join(__dirname, 'public');
function generateAccessToken(username) {
return jwt.sign(username, TOKEN_SECRET, { expiresIn: '1800s' }); //30 mins
}
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
let token = authHeader && authHeader.split(' ')[1];
if(token){
token = authHeader.split(' ')[1].replace(/[\""]/g, '');
}
token_random_time = crypto.randomInt(0, 100000000);
token_salt_ramdon = bcrypt.genSaltSync(10);
if (token == null){
res.setHeader("token_salt", token_salt_ramdon);
res.setHeader("token_rand", token_random_time);
res.statusCode=403;
return res.sendFile(path.join(publicDir, 'login.html'));
}
jwt.verify(token, TOKEN_SECRET, (err, user) => {
if (err){
console.log(err);
res.statusCode=403;
res.setHeader("token_salt", token_salt_ramdon);
res.setHeader("token_rand", token_random_time);
return res.sendFile(path.join(publicDir, 'login.html'));
}
req.user = user;
next();
});
}
app.get('/', function (req, res) {
console.log("sending index");
res.sendFile(path.join(publicDir, 'index1.html'));
});
app.post('/login', (req, res) =>{
let token = "error";
if(req.body.username && req.body.hash){
let hash = bcrypt.hashSync(USER_ID+USER_PASSWORD+token_random_time.toString(),token_salt_ramdon);
if(req.body.username === USER_NAME && req.body.hash === hash){
token = generateAccessToken({username: req.body.username});
}
}
res.json(token);
});
app.get('/stylesheets/:sheet_name', function (req, res, next) {
console.log("sending style sheet ", req.params.sheet_name);
var options = {
root: path.join(__dirname, "public"+"/stylesheets")
};
res.sendFile(req.params.sheet_name, options, function (err) {
if (err) {
//res.send("hello");
req.error = err;
next();
}
});
});
app.get('/javascripts/:js_name', function (req, res, next) {
console.log("sending javascript", req.params.js_name);
var options = {
root: path.join(__dirname, "public"+"/javascripts")
};
res.sendFile(req.params.js_name, options, function (err) {
if (err) {
//res.send("hello");
req.error = err;
next();
}
});
});
app.get('/images/:image_name', function (req, res, next) {
console.log("sending image", req.params.image_name);
var options = {
root: path.join(__dirname, "public"+"/images")
};
res.sendFile(req.params.js_name, options, function (err) {
if (err) {
req.error = err;
next();
}
});
});
app.get('/devices/:type', authenticateToken, function (req, res, next) {
console.log("sending info page for ", req.params.type);
var options = {
root: path.join(__dirname, "public"+"/devices")
};
res.sendFile(req.params.type+".html", options, function (err) {
if (err) {
//res.send("hello");
req.error = err;
next();
}
});
});
app.get('/info/:type', authenticateToken, function (req, res, next) {
console.log("sending info type", req.params.type);
let arguements = null;
switch (req.params.type) {
case "d":
console.log("getting disk info");
arguements = "-d";
break;
case "c":
console.log("getting temperature info");
arguements = "-c";
break;
case "t":
console.log("getting top info");
arguements = "-t";
break;
case "a":
console.log("getting all info");
arguements = "-a";
break
}
if(arguements!== null){
var prc = spawn('./info_script.sh', [arguements]);
let output = "";
//noinspection JSUnresolvedFunction
prc.stdout.setEncoding('utf8');
prc.stdout.on('data', function (data) {
var str = data.toString()
var lines = str.split(/(\r?\n)/g).join("");
output+=lines;
})
prc.on('close', function (code) {
//console.log(output);
return res.json({result:output});
});
}else{
return res.json({result:"failed to get"});
}
});
app.get('/system/:command', authenticateToken, function (req, res, next) {
console.log("sending systemc command", req.params.command);
let arguements = null;
let p = null;
const p_actions = './sys_actions';
switch (req.params.command) {
case "v_status":
console.log("getting vpn info");
p = "mullvad";
arguements = "status";
break;
case "v_disconnect":
console.log("disconnecting vpn");
p = "mullvad";
arguements = "disconnect";
break;
case "v_connect":
console.log("connecting vpn");
p = "mullvad";
arguements = "connect";
break;
case "ip":
console.log("getting ip info");
p = "ip";
arguements = "a";
break
case "ip_public":
console.log("getting ip public info");
p = "curl";
arguements = "https://ifconfig.me";
break
case "shut":
console.log("shutting down");
p = p_actions;
arguements = "shut";
break
case "smb_status":
console.log("getting smb status");
p = p_actions;
arguements = "smb_status";
break
case "smb":
console.log("restarting smb");
p = p_actions;
arguements = "smb_restart";
break
case "nfs_status":
console.log("getting nfs status");
p = p_actions;
arguements = "nfs_status";
break
case "nfs":
console.log("restarting nfs");
p = p_actions;
arguements = "nfs_restart";
break
default:
return res.json({result: "invalid command"});
}
if(arguements!== null){
var prc = spawn(p, [arguements]);
let output = "";
//noinspection JSUnresolvedFunction
prc.stdout.setEncoding('utf8');
prc.stdout.on('data', function (data) {
var str = data.toString()
var lines = str.split(/(\r?\n)/g).join("");
output+=lines;
})
prc.on('close', function (code) {
//console.log(output);
return res.json({result:output});
});
}else{
return res.json({result:"failed to get"});
}
});
app.get('/seasons', function(req, res, next) {
readSeasons(req, res);
});
app.post('/seasons', function(req, res, next) {
seasons = req.body;
writeSeasons(req, res);
});
app.options('/seasons', function(req, res, next) {
res.send();
})
app.use(function(req, res) {
if(req.error){
console.log("error encountered");
}
console.log("not found1 ", req.url);
res.statusCode = 404;
return res.send("not found");
});
var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('Listening on ' + bind);
}