-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
645 lines (579 loc) · 17.1 KB
/
server.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// =======================
// get the packages we need ============
// =======================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var fileUpload = require('express-fileupload');
var fs = require('fs');
var nodemailer = require('nodemailer');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('./config'); // get our config file
var User = require('./app/models/user'); // get our mongoose models
var Script = require('./app/models/script');
// =======================
// configuration =========
// =======================
var port = process.env.PORT || 8080; // used to create, sign, and verify tokens
mongoose.Promise = global.Promise;
mongoose.connect(config.database); // connect to database
app.set('superSecret', config.secret); // secret variable
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('public'));
// use morgan to log requests to the console
app.use(morgan('dev'));
// use express-fileupload to upload file
app.use(fileUpload());
// ######### API ROUTES #########
// get an instance of the router for api routes
var apiRoutes = express.Router();
// ######### PUBLIC API #########
/*
* /livesim
*
* path: the script's path that needs to be read [string]
* data: the script's text
*
*/
app.post('/agentsim/livesim', function(req, res, next){
fs.readFile('./header.html', function(err, data){
if(err)
throw(err);
req.script = data;
next();
});
},function(req, res, next){
if(req.body.path){
fs.readFile("upload/" + req.body.path, function(err, data){
if(err)
throw(err);
var html = req.script.toString().replace("<script></script>", "<script>" + data + "</script>");
res.write(html);
res.end();
});
}
else
next();
},function(req, res, next){
if(req.body.data){
var html = req.script.toString().replace("<script></script>", "<script>" + req.body.data + "</script>");
res.write(html);
res.end();
}
}
);
// apply the routes to our application with the prefix /api
app.use('/api', apiRoutes);
// route to show a random message (GET http://localhost:8080/api/)
apiRoutes.get('/', function(req, res) {
res.json({ message: 'Welcome to the AgentSimJS Portal API!' });
});
/*
* /authenticate
* name: name of the user [string]
* password: password of the user [string]
*/
apiRoutes.post('/authenticate', function(req, res) {
// find the user
console.log(req.body.name);
User.findOne({
"name": req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({
success: false,
message: 'Authentication failed. User not found.'
});
}
else if(user.blocked){
res.json({
success: false,
message: 'You have to verify your account first.'
});
}
else if (user) {
// check if password matches
if (user.password != req.body.password) {
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
});
}
else {
// if user is found and password is right
// create a token
var token = jwt.sign(user, app.get('superSecret'), {
expiresIn: 1440 // expires in 24 hours
});
// return the information including token as JSON
res.json({
success: true,
message: 'Enjoy your token!',
token: token
});
}
}
});
});
/*
* /register
*
* name: name of the user [string]
* password: password of the user [string]
* email: email of the user [string]
*/
apiRoutes.post('/register', function(req, res, next){
console.log(req.body.name +" "+req.body.password+" "+req.body.email);
if(!req.body.name || !req.body.password || !req.body.email)
res.json({
success: false,
message: "You've to fill all the fields."
});
else
next();
},function(req,res, next){
User.find({email: req.body.email}, function(err, users){
if(err)
throw(err);
if(users[0]){
return res.json({
success: false,
message: "this email is already registered"
});
}
else{
next();
}
});
},function(req, res, next){
User.find({name: req.body.name}, function(err, users) {
if(err)
throw(err);
if(users[0])
return res.json({
success: false,
message: "This username already exist."
});
else{
next();
}
});
},function(req, res, next){
var nick = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email,
blocked: true,
admin: true
});
// save the sample user
nick.save(function(err) {
if (err) throw err;
res.json({
success: true,
message: "User registered successfully!"
})
console.log('User saved successfully');
});
var id = nick._id;
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: config.email,
pass: config.password
}
});
var verify = config.home_path+ '/api/verify?token=' +id;
var mailOptions = {
from: config.email,
to: nick.email,
subject: 'Verify your AgentSim account!',
text: verify
};
transporter.sendMail(mailOptions, function(err, info){
if(err){
console.log("Invalid Email.");
res.json({
success: false,
message: "Invalid Email."
})
}
else {
console.log('Message sent: ' +info.response);
res.json({
success: true,
message: "Email di conferma inviata con successo!"
});
};
});
}
);
/*
* /verify route to verify an user's email
*
* user_id: user's id that needs to be verified [string]
*/
apiRoutes.get('/verify', function(req,res){
var id_token = req.query.token;
console.log(id_token);
User.update({"_id": id_token}, {"$set": {"blocked": false}}, function(err){
if(err)
throw(err);
});
res.writeHead(301,
{Location: config.home_path+'/#!/login'},
"User verified."
);
res.end();
});
/*
* /email_verify route to verify if it already exists an user with this email
*
* email: email that needs to be verified [string]
*/
apiRoutes.get('/email_verify', function(req, res){
User.find({email: req.query.email}, function(err, users){
if(err)
throw(err);
if(users[0])
res.json({
success: false,
message: "This email is already registered"
});
else
res.json({
success: true,
message: "Valid email"
});
});
});
apiRoutes.get('/nick_verify', function(req, res){
User.find({name: req.query.name}, function(err, users){
if(err)
throw(err);
if(users[0])
res.json({
success: false,
message: "This username already exists"
});
else
res.json({
success: true,
message: "Valid username"
})
});
});
/*
* /scripts route to return all scripts
*
* from: starting point to see the number of scripts. example: from=20 => it will show scripts from 20 to 40
*/
apiRoutes.get('/scripts', function(req, res){
Script.find({}, function(err, scripts){
res.json(scripts);
}).skip(req.query.from).sort({creation: -1});
});
/*
* /script/:user route to return all user's scripts
*
* from: starting point to see the number of scripts. example: from=20 => it will show scripts from 20 to 40
*/
apiRoutes.get('/scripts/:user', function(req, res){
var user = req.params.user;
Script.find({owner: user}, function(err, scripts){
res.json(scripts);
}).skip(req.query.from).sort({creation: -1});
});
/*
* /getExpireTime route to return token's remaining time
*
* token: token that needs to be verified
*/
apiRoutes.post('/getExpireTime', function(req, res){
var token = req.body.token;
var time;
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
time = decoded.iat;
}
});
res.send(time);
})
// route middleware to verify a token
apiRoutes.use(function(req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
// ######### API PROTECTED #########
/*
* /users route to return all users
*/
apiRoutes.get('/users', function(req, res) {
User.find({}, function(err, users) {
res.json(users);
});
});
/*
* /upload - route to upload new scripts
*
* param_script: content of the script
* name: name of the script
* description : description of the script
OR
* sampleFile: file.js that contain the script
*
* token: user's token
*/
apiRoutes.post('/upload', function(req, res, next){
req.id = req.decoded._doc._id;
req.name = req.decoded._doc.name;
next();
},function(req, res, next){
if(req.body.name){
req.body.name = req.body.name.replace(".js", "");
req.body.name = req.body.name+"-"+req.id+'.js';
Script.find({path : req.body.name}, function(err, scripts){
if(err)
throw(err);
if(scripts[0])
res.json({
success: false,
message: "It already exists a script with this name"
});
else
next();
});
}
if(req.files){
req.files.sampleFile.name = req.files.sampleFile.name.replace(".js", "-"+req.id+".js");
Script.find({path : req.files.sampleFile.name}, function(err, scripts){
if(err)
throw(err);
if(scripts[0])
res.json({
success: false,
message: "It already exists a script with this name"
});
else
next();
});
}
},function(req, res, next){
if(!req.files && !req.body.param_script)
return res.json({
success: false,
message: 'No file uploaded.'
});
var upload_path;
if(req.body.param_script && req.body.name) {
upload_path = req.body.name;
fs.writeFile('upload/'+upload_path, req.body.param_script, function(err){
if(err)
throw(err);
else{
console.log("File created and uploaded");
req.sample = false;
next();
}
})
}
else {
//the name of the input field is used to retrieve the uploaded file
let sampleFile = req.files.sampleFile;
//check if the file uploaded is html or javascript
if(sampleFile.mimetype != "application/javascript"){
return res.json({
success: false,
message: 'You can update only .js files'
});
}
//use the mv() method to place the file on server directory
upload_path = sampleFile.name;
sampleFile.mv('./upload/'+upload_path, function(err){
if(err)
throw err;
else{
console.log("File Uploaded");
req.sample = true;
next();
}
});
}
},function(req, res, next){
var tmp = req.id;
var name = req.name;
var upload_path;
var desc = req.body.description;
// create a sample script
if(req.sample)
upload_path = req.files.sampleFile.name
else
upload_path = req.body.name;
var script = new Script({
users_id: tmp,
path: upload_path,
owner: name,
description: desc
});
// save the sample script
script.save(function(err) {
if (err) throw err;
console.log('Script saved successfully');
res.json({
success: true,
message: "Scipt saved successfully"
})
});
}
);
/*
* /getScript/:id route to return all user's scripts
*/
apiRoutes.get('/getScript/:id', function(req, res){
Script.find({_id: req.params.id}, function(err, script){
if (script) {
fs.readFile('upload/' + script[0].path, function(err, data){
if(err)
throw(err);
var sendScript = {
path: script[0].path,
users_id: script[0].users_id,
owner: script[0].owner,
_id: script[0]._id,
updated: script[0].updated,
creation: script[0].creation,
code: data.toString(),
success: true
};
res.json(sendScript);
});
}
else {
res.json({
success: false,
message: "This script doesn't exist"
});
}
});
});
/*
* /modify route to modify a script
*
* token: user's token [token]
* id_script: script's id
* name: the new name the user want to give to own script
* value: the new modified text of the script
*
*/
apiRoutes.post('/modify', function(req, res, next){
req.tmp = req.decoded._doc.name;
req.id = req.decoded._doc._id;
next();
},function(req, res, next){
if(req.body.name){
req.body.name = req.body.name+"-"+req.id+'.js';
Script.find({path : req.body.name, _id : { $ne : req.body.id_script } }, function(err, scripts){
if(err)
throw(err);
if(scripts[0])
res.json({
success: false,
message: "It already exists a script with this name"
});
else
next();
});
}
},function(req, res, next){
Script.find({ $and: [ {_id: req.body.id_script}, {owner: req.tmp} ]}, function(err, users){
if(err)
throw(err);
else{
if(!users[0])
res.json({
success: false,
message: "You're not the owner of this script"
})
else{
req.script_name = users[0].path;
next();
}
}
})
},function(req, res, next){
if(req.body.name){
Script.update({"_id": req.body.id_script}, {"$set": {"path": req.body.name}}, function(err){
if(err)
throw(err);
else{
fs.rename('./upload/'+req.script_name, './upload/'+req.body.name, function(err){
if(err)
throw(err);
else{
req.script_name = req.body.name;
console.log("Name updated");
next();
}
});
}
});
}
else
next();
},function(req, res, next){
if(req.body.value){
fs.writeFile('upload/'+req.script_name, req.body.value, function(err){
if(err)
throw(err);
else{
console.log("File updated");
}
})
}
res.json({
success: true,
message: "File updated"
})
}
);
// =======================
// start the server ======
// =======================
app.listen(port);
console.log('AgentSimJS http://localhost:' + port);
/*
console.log(" █████╗ ██████╗ ███████╗███╗ ██╗████████╗ ███████╗██╗███╗ ███╗ ██╗███████╗");
console.log("██╔══██╗██╔════╝ ██╔════╝████╗ ██║╚══██╔══╝ ██╔════╝██║████╗ ████║ ██║██╔════╝");
console.log("███████║██║ ███╗█████╗ ██╔██╗ ██║ ██║ ███████╗██║██╔████╔██║ ██║███████╗");
console.log("██╔══██║██║ ██║██╔══╝ ██║╚██╗██║ ██║ ╚════██║██║██║╚██╔╝██║ ██ ██║╚════██║");
console.log("██║ ██║╚██████╔╝███████╗██║ ╚████║ ██║ ███████║██║██║ ╚═╝ ██║ ╚█████╔╝███████║");
console.log("╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝╚═╝ ╚═╝ ╚════╝ ╚══════╝");
*/