-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
executable file
·17883 lines (16411 loc) · 928 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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//copyright 2022 servicemedia.net
var express = require("express")
, http = require("http")
, jwt = require("jsonwebtoken")
, axios = require("axios")
, path = require("path")
, fs = require("fs")
, bodyParser = require('body-parser')
, cookieParser = require('cookie-parser')
// , multer = require('multer') //done witchoo!
// , autoReap = require('multer-autoreap')
, mongojs = require("mongojs")
, methodOverride = require('method-override')
, session = require('express-session')
, entities = require("entities")
, validator = require('validator')
, minio = require('minio')
// , util = require('util')
, helmet = require('helmet')
, ObjectID = require("bson-objectid")
, MongoDBStore = require('connect-mongodb-session')(session) //theShit
, async = require('async')
, bcrypt = require('bcrypt-nodejs')
, shortid = require('shortid')
, QRCode = require('qrcode')
// , transloadit = require('node-transloadit') done witchoo!
// , internetradio = require('node-internet-radio') bad behavior..
, requireText = require('require-text');
app = express();
require('dotenv').config();
// app.use(helmet.contentSecurityPolicy());
app.use(helmet.dnsPrefetchControl());
app.use(helmet.expectCt());
app.use(helmet.hidePoweredBy());
app.use(helmet.hsts());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.permittedCrossDomainPolicies());
app.use(helmet.referrerPolicy());
app.use(helmet.xssFilter());
// require('./routes/oculus_routes')(app);
// app.cosnfigure(function(){
// app.use(bodyParser);
// });
var stripe = require("stripe")(process.env.STRIPE_KEY);
var rootHost = process.env.ROOT_HOST
var topName = process.env.ROOT_NAME;
var requirePayment = true; //if subscription is required to login, true for servicemedia
var adminEmail = process.env.ADMIN_EMAIL;
var domainAdminEmail = process.env.DOMAIN_ADMIN_EMAIL;
var whitelist = ['unityapp', 'http://smxr.net', 'https://smxr.net', 'https://servicemedia.s3.amazonaws.com/', 'http://localhost:3000', 'https://servicemedia.net', 'strr.us.s3.amazonaws.com', 'mvmv.us.s3.amazonaws.com', 'http://strr.us', 'https://strr.us',
'https://strr.us/socket.io', 'http://valuebring.com', 'http://elnoise.com', 'philosophersgarden.com', 'http://elnoise.com', 'http://eloquentnoise.com', 'http://thefamilyshare.com', 'http://little-red-schoolhouse.com',
'http://visiblecity.net', 'http://philosophersgarden.net', 'https://realitymangler.com', 'http://regalrooms.tv', 'https://mvmv.us', 'http://mvmv.us',
'http://nilch.com', 'https://servicemedia.net', 'http://kork.us', 'http://spacetimerailroad.com'];
var corsOptions = function (origin) {
// console.log("checking vs whitelist:" + origin);
if ( whitelist.indexOf(origin) !== -1 ) {
return true;
} else {
return true; //fornow...
}
};
var oneDay = 86400000;
// app.use (function (req, res, next) {
// var schema = (req.headers['x-forwarded-proto'] || '').toLowerCase();
// if (schema === 'https') {
// next();
// } else {
// // console.log ("non ssl request = " + req.headers.host + " tryna redirect");
// if (req.headers.host != "localhost:3000") { //TODO Enviromental Varz
// next(); //nm do it clientside... :()
// // var htmltext = "<html xmlns='http://www.w3.org/1999/xhtml'>" +
// // "<head></head><body> " +
// // "<h4>you must use https to access this site: <a href='https://servicemedia.net'>https://servicemedia.net</a></h4>" +
// // "</body><script>"+
// // "window.location.href = window.location.href.replace('http:', 'https:');"
// // "</script></html>";
// // res.send(htmltext);
// } else {
// next();
// }
// }
// });
var databaseUrl = process.env.MONGO_URL; //servicemedia connstring
// console.log(databaseUrl);
var collections = ["acl", "auth_req", "domains", "apps", "assets", "assetsbundles", "models", "users", "inventories", "inventory_items", "audio_items", "text_items", "audio_item_keys", "image_items", "video_items",
"obj_items", "paths", "keys", "traffic", "scores", "attributes", "achievements", "activity", "actions", "purchases", "storeitems", "scenes", "groups", "weblinks", "locations", "iap"];
var db = mongojs(databaseUrl, collections);
var store = new MongoDBStore({ //store session cookies in a separate db with different user, so nice
uri: process.env.MONGO_SESSIONS_URL,
collection: 'sessions'
});
store.on('connected', function() {
store.db; // The underlying MongoClient object from the MongoDB driver
});
app.use(express.static(path.join(__dirname, './'), { maxAge: oneDay }));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST');
res.header('Access-Control-Max-Age', '300');
res.header('Access-Control-Allow-Headers', 'Origin, Access-Control-Allow-Origin, x-unity-version, X-Unity-Version, token, cookie, appid, Cookie, X-Access-Token, x-access-token, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
res.header('Access-Control-Expose-Headers', 'set-cookie, Set-Cookie', 'token');
if ('OPTIONS' == req.method) {
res.send(200);
} else {
next();
}
});
app.use(methodOverride());
// var sessionStore = new session.MemoryStore();
var expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 2 hour
app.use(session({
resave: true,
saveUninitialized: true,
store: store,
rolling: true,
secret: process.env.JWT_SECRET }));
// app.use(router);
app.use(cookieParser());
// app.use(bodyParser());
// app.use(bodyParser.json({ "limit": "100mb", extended: true }));
app.use(bodyParser.json({ "limit": "150mb", extended: true })); //set this to route specific somehow, for add_scene_mods?
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
// app.use(autoReap);
var maxItems = 1000;
const { CloudSearch } = require("aws-sdk");
//var upload = multer({ dest: 'uploads/' });
var aws = require('aws-sdk');
const { json } = require("body-parser");
const { profile } = require("console");
const { lookupService, resolveNaptr, resolveCname, resolveMx } = require("dns");
aws.config = new aws.Config({accessKeyId: process.env.AWSKEY, secretAccessKey: process.env.AWSSECRET, region: process.env.AWSREGION});
var ses = new aws.SES({apiVersion : '2010-12-01'});
var s3 = new aws.S3();
var minioClient = null;
if (process.env.MINIOKEY && process.env.MINIOKEY != "" && process.env.MINIOENDPOINT && process.env.MINIOENDPOINT != "") {
minioClient = new minio.Client({
endPoint: process.env.MINIOENDPOINT,
port: 9000,
useSSL: false,
accessKey: process.env.MINIOKEY,
secretKey: process.env.MINIOSECRET
});
}
var appAuth = "noauth";
// let docClient = new aws.DynamoDB.DocumentClient();
// let trafficTable = "traffic_1";
var server = http.createServer(app);
server.timeout = 240000;
server.keepAliveTimeout = 24000;
server.listen(process.env.PORT || 3000, function() {
console.log("Express server listening on port 3000");
});
app.set('db', db);
app.set('store', store);
app.set('s3', s3);
db.scenes.createIndex( { short_id: -1 } );
//INCLUDE EXTERNAL ROUTES BELOW
var oculus_routes = require('./routes/oculus_routes');
app.use('/oculus', oculus_routes);
var webxr_routes = require('./routes/webxr_routes');
app.use('/webxr', webxr_routes);
var landing_routes = require('./routes/landing_routes');
app.use('/landing', landing_routes);
// io.attach(http);
// io.use(function(socket, next){
// console.log("Query: ", socket.handshake.query);
// // return the result of next() to accept the connection.
// if (socket.handshake.query.uname != undefined) {
// if (!socket.handshake.query.uname.includes("guest")) { //TODO put some token-fu on this
// socket.uname = socket.handshake.query.uname;
// db.scenes.findOne({ "short_id": socket.handshake.query.room}, function (err, scene) {
// if (err || !scene) {
// console.log("that scene does not exist " + socket.handshake.query.room);
// next(new Error('that scene is not'));
// } else {
// return next();
// console.log("that scene is");
// }
// });
// // return next();
// }
// } else {
// console.log("i gots nothin");
// next(new Error('Socket Authentication error'));
// }
// // call next() with an Error if you need to reject the connection.
// });
// io.use(function (socket, next){
// console.log("socket: s"ocket);
// return next();
// });
/////// this one is for aframe nat, no usrs
/*
const rooms = {};
io.on("connection", socket => {
console.log("user connected", socket.id);
let curRoom = null;
// socket.on('reconnect_attempt', () => {
// socket.io.opts.transports = ['polling', 'websocket'];
// });
socket.on("joinRoom", data => {
const { room } = data;
if (!rooms[room]) {
rooms[room] = {
name: room,
occupants: {},
};
}
const joinedTime = Date.now();
rooms[room].occupants[socket.id] = joinedTime;
curRoom = room;
console.log(`${socket.id} joined room ${room}`);
socket.join(room);
socket.emit("connectSuccess", { joinedTime });
const occupants = rooms[room].occupants;
io.in(curRoom).emit("occupantsChanged", { occupants });
});
socket.on("send", data => {
io.to(data.to).emit("send", data);
});
socket.on("broadcast", data => {
socket.to(curRoom).broadcast.emit("broadcast", data);
});
socket.on("disconnect", () => {
console.log('disconnected: ', socket.id, curRoom);
if (rooms[curRoom]) {
console.log("user disconnected", socket.id);
delete rooms[curRoom].occupants[socket.id];
const occupants = rooms[curRoom].occupants;
socket.to(curRoom).broadcast.emit("occupantsChanged", { occupants });
if (occupants == {}) {
console.log("everybody left room");
delete rooms[curRoom];
}
}
});
});
*/
/////// SHOW/HIDE Below to run socket.io on same port
///this one gets users through handshake
// var socketUsers = {};
// var allUsers = [];
var io = require('socket.io')(server);
// var mongoAdapter = require('socket.io-adapter-mongo');
// io.adapter(mongoAdapter( process.env.MONGO_SESSIONS_URL ));
// io.set('origins', 'servicemedia.net');
io.set('transports', ['polling', 'websocket']);
io.serveClient(true);
// socket = io;
io.on('connection', function(socket) {
var room = "";
socket.token = socket.handshake.query.token;
socket.uname = socket.handshake.query.uname; //set property on socket itself, rather than keeping a list
socket.color = socket.handshake.query.color;
// let tokenAuth = tokenAuthentication(socket.token);
if (socket.token != null && socket.uname != null && socket.color != null){
socket.on("disconnect", (reason) => {
console.log("closing connection because bad query from " + socket);
});
} else {
console.log(socket.uname + " " + socket.color + "connected");
}
socket.on('join', function(rm) {
console.log(socket.uname + " tryna join " + rm);
socket.join(rm);
socket.room = room;
room = rm; //set global room value for this socket, since we can only be in one at a time
jwt.verify(socket.token, process.env.JWT_SECRET, function (err, payload) {
console.log(JSON.stringify(payload));
if (payload) {
if (payload.userId != null){
// console.log("gotsa payload.userId : " + payload.userId);
if (payload.userId == "0000000000000") { //TODO check for expiration
console.log("payload is guest token");
console.log(socket.id + " named " + socket.uname + " tryna join " + rm );
socket.join(rm);
socket.room = room;
socket.userID = payload.userId;
room = rm; //set global room value for this socket, since we can only be in one at a time
io.to(room).emit('user joined', socket.uname, room);
} else { //maybe do lookup on join?
var oo_id = ObjectID(payload.userId);
db.users.findOne({_id: oo_id}, function (err, user) { //check user status
if (err != null) {
socket.on("disconnect", (reason) => {
console.log("closing connection because userlookup failed");
});
} else {
console.log("gotsa user " + user._id + " authLevel " + user.authLevel + " status " + user.status);
console.log(socket.id + " named " + socket.uname + " tryna join " + rm );
socket.join(rm);
socket.room = room;
room = rm; //set global room value for this socket, since we can only be in one at a time
socket.userID = payload.userId;
io.to(room).emit('user joined', socket.uname, room);
}
});
}
// next();
} else {
socket.on("disconnect", (reason) => {
console.log("closing connection because no userID in payload " + reason);
});
}
} else {
socket.on("disconnect", (reason) => {
console.log("closing connection because no payload " + reason);
});
}
});
});
socket.on('disconnect', function() {
console.log('Got disconnect: ' + socket.handshake.query.room);
socket.leave(socket.handshake.query.room);
socket.to(socket.handshake.query.room).emit('user left', socket.id);
// io.in(room).emit('disconnected', socket.uname);
if (io.sockets.adapter.rooms[room] != undefined) {
var roomUsers = io.sockets.adapter.rooms[room].sockets;
// console.log("roomUsers after disconnect " + JSON.stringify(roomUsers));
var returnObj = {};
Object.keys(roomUsers).forEach(function(key) {
// console.log("disconnect roomUsers key " + key + " uname " + io.sockets.connected[key].uname);
// let namedPlusColor = io.sockets.connected[key].uname + "~" +
// returnObj[key] = io.sockets.connected[key].uname; //socketID : username
let namePlusColor = io.sockets.connected[key].uname + "~" + io.sockets.connected[key].color;
returnObj[key] = namePlusColor;
// returnObj[io.sockets.connected[key].uname] = key; //cook up a nice dict for client to use
});
Object.keys(roomUsers).forEach(function(key) {
// console.log("roomUsers key " + key + " uname " + io.sockets.connected[key].uname);
// returnObj[key] = io.sockets.connected[key].uname; //socketID : username
// returnObj[io.sockets.connected[key].uname] = key; //cook up a nice dict for client to use
io.sockets.connected[key].emit('room users', JSON.stringify(returnObj));
});
}
// io.emit('disconnected');
});
socket.on('room users', function (room) {
if (io.sockets.adapter.rooms[room] != undefined) {
var roomUsers = io.sockets.adapter.rooms[room].sockets;
// console.log("roomUsers " + JSON.stringify(roomUsers));
var returnObj = {};
// async.each (Object.keys(roomUsers), function (key, callbackz) {
// returnObj[key] = io.sockets.connected[key].uname;
// callbackz();
// }, function(err) {
//
// if (err) {
// console.log('bad key');
// callbackz(err);
// }
// });
Object.keys(roomUsers).forEach(function(key) {
// console.log("roomUsers key " + key + " uname " + io.sockets.connected[key].uname);
// returnObj[key] = io.sockets.connected[key].uname; //socketID : username
let namePlusColor = io.sockets.connected[key].uname + "~" + io.sockets.connected[key].color;
returnObj[key] = namePlusColor;
// returnObj[io.sockets.connected[key].uname] = key; //cook up a nice dict for client to use
});
// console.log(roomUsersString);
// console.log("tryna get room users for " + room + " " + JSON.stringify(returnObj));
io.in(room).emit('room users', JSON.stringify(returnObj));
}
});
socket.on('pic frame', function(data, sid) { //sid = sender's socket.id
console.log("tryna send a pic frame : ");
socket.to(room).emit('getpicframe', data, sid);
// socket.broadcast.emit('broad',data);
});
socket.on('user message', function(data) {
// console.log(socket.uname + " user message: " + data + " for room " + room);
socket.in(room).emit('user messages', socket.uname, data);
// socket.broadcast.emit('messages',data);
});
socket.on('admin message', function(data) {
// console.log(socket.uname + " user message: " + data + " for room " + room);
socket.in(room).emit('admin message', data);
// socket.broadcast.emit('messages',data);
});
socket.on('activity message', function(data) {
console.log("room : " + room + "activity message: " + data)
socket.to(room).emit('messages', data);
// socket.broadcast.emit('messages',data);
});
socket.on('updateplayerposition', function(room, uname, posx, posy, posz, rotx, roty, rotz, sid, source) { //adding rot vals and source
// console.log(uname + ' sid ' + sid + ' moved to ' + posx+","+posy+","+posz + " in room " + room);
// socket.to(room).emit('messages', uname + ' moved to ' + posx+","+posy+","+posz);
// if (source == "aframe") { //if player is in aframe scene, flip the z - what about rotations?
// posz = posz * -1;
// }
socket.to(room).emit('playerposition', uname,posx,posy,posz,rotx, roty, rotz, sid, source);
});
});
//*/
function ReturnPresignedUrlSync (bucket, key, time) {
if (minioClient) {
minioClient.presignedGetObject(bucket, key, time, function(err, presignedUrl) { //use callback version here, can't await?
if (err) {
console.log(err);
return "err";
} else {
console.log("minio sync url " + presignedUrl)
return presignedUrl;
}
});
} else {
let url = s3.getSignedUrl('getObject', {Bucket: bucket, Key: key, Expires: time});
console.log("s3 sync url" + url);
return url;
}
}
function tokenAuthentication(token) { //use for route security?
jwt.verify(token, process.env.JWT_SECRET, function (err, payload) {
console.log(JSON.stringify(payload));
if (payload) {
if (payload.userId != null){
console.log("gotsa payload.userId : " + payload.userId);
var oo_id = ObjectID(payload.userId);
db.users.findOne({_id: oo_id}, function (err, user) { //check user status
if (err != null) {
req.session.error = 'Access denied!';
console.log("token authentication failed! User ID not found");
// res.send('noauth');
return ("no");
} else {
console.log("gotsa user " + user._id + " authLevel " + user.authLevel + " status " + user.status);
if (user.status == "validated") {
// userStatus = "subscriber";
console.log("gotsa subscriber!");
return ("yes");
} else {
req.session.error = 'Access denied!';
console.log("token authentication failed! not a subscriber");
return ("maybe");
}
}
});
// next();
} else {
return ("nope");
}
} else {
return ("nooo");
}
});
}
function checkAuthentication(req) { //maybe needed later? can just get session info in route
if (req.session.user && req.session.user.status == "validated") { //check using session cookie
if (requirePayment) {
if (req.session.user.paymentStatus == "ok") {
// next();
return "payment auth OK " + JSON.stringify(req.session.user);
} else {
req.session.error = 'Access denied! - payment status not ok';
res.send('payment status not OK');
return "payment status not OK";
}
} else {
console.log("authenticated!");
// next();
return "auth OK";
}
} else {
if (req.headers['x-access-token'] != null) { //check using json web token
var token = req.headers['x-access-token'];
console.log("req.headers.token: " + token);
jwt.verify(token, process.env.JWT_SECRET, function (err, payload) {
console.log(JSON.stringify(payload));
if (payload) {
// user.findById(payload.userId).then(
// (doc)=>{
// req.user=doc;
// next();
// }
// )
// console.log("gotsa token payload: " + req.session.user._id + " vs " + payload.userId);
if (payload.userId != null){
console.log("gotsa payload.userId : " + payload.userId);
var oo_id = ObjectID(payload.userId);
db.users.findOne({_id: oo_id}, function (err, user) { //check user status
if (err != null) {
req.session.error = 'Access denied!';
console.log("token authentication failed! User ID not found");
// res.send('noauth');
return "token auth failed, userID not found";
} else {
console.log("gotsa user " + user._id + " authLevel " + user.authLevel + " status " + user.status);
if (user.status == "validated") {
// userStatus = "subscriber";
console.log("gotsa subscriber!");
// next();
return "token auth OK";
} else {
req.session.error = 'Access denied!';
console.log("token authentication failed! not a subscriber");
// res.send('noauth');
return "token auth failed";
}
}
});
// next();
} else {
req.session.error = 'Access denied!';
console.log("token authentication failed! headers: " + JSON.stringify(req.headers));
// res.send('noauth');
return "token auth failed";
}
} else {
req.session.error = 'Access denied!';
console.log("token authentication failed! headers: " + JSON.stringify(req.headers));
// res.send('noauth');
return "token auth failed";
}
});
} else {
req.session.error = 'Access denied!';
console.log("authentication failed! No cookie or token found");
// res.send('noauth');
return "token auth failed";
}
}
}
function requiredAuthentication(req, res, next) { //primary auth method, used as argument in the routes below
if (req.session.user && req.session.user.status == "validated") { //check using session cookie
if (requirePayment) {
if (req.session.user.paymentStatus == "ok") {
next();
} else {
req.session.error = 'Access denied! - payment status not ok';
res.send('payment status not OK');
}
} else {
console.log("authenticated!");
next();
}
} else {
if (req.headers['x-access-token'] != null) { //check using json web token
var token = req.headers['x-access-token'];
console.log("req.headers.token: " + token);
jwt.verify(token, process.env.JWT_SECRET, function (err, payload) {
console.log(JSON.stringify(payload));
if (payload) {
// user.findById(payload.userId).then(
// (doc)=>{
// req.user=doc;
// next();
// }
// )
// console.log("gotsa token payload: " + req.session.user._id + " vs " + payload.userId);
if (payload.userId != null){
console.log("gotsa payload.userId : " + payload.userId);
var oo_id = ObjectID(payload.userId);
db.users.findOne({_id: oo_id}, function (err, user) { //check user status
if (err != null) {
req.session.error = 'Access denied!';
console.log("token authentication failed! User ID not found");
res.send('noauth');
} else {
console.log("gotsa user " + user._id + " authLevel " + user.authLevel + " status " + user.status);
if (user.status == "validated") {
// userStatus = "subscriber";
console.log("gotsa subscriber!");
next();
} else {
req.session.error = 'Access denied!';
console.log("token authentication failed! not a subscriber");
res.send('noauth');
}
}
});
// next();
} else {
req.session.error = 'Access denied!';
console.log("token authentication failed! headers: " + JSON.stringify(req.headers));
res.send('noauth');
}
} else {
req.session.error = 'Access denied!';
console.log("token authentication failed! headers: " + JSON.stringify(req.headers));
res.send('noauth');
}
});
} else {
req.session.error = 'Access denied!';
console.log("authentication failed! No cookie or token found");
res.send('noauth');
}
}
}
// function traffic (req, res, next) { //deprecated, used dynamodb
// let timestamp = Date.now();
// timestamp = parseInt(timestamp);
// console.log("tryna save req" + req.body);
// var ip = req.headers['x-forwarded-for'] ||
// req.socket.remoteAddress ||
// null;
// let params = {
// TableName: trafficTable, //dynamodb table name at aws
// Item: {
// timestamp: timestamp,
// baseUrl: req.baseUrl,
// body: JSON.stringify(req.body),
// fresh: req.fresh,
// hostname: req.hostname,
// ip: req.ip,
// referring_ip: ip,
// method: req.method,
// originalUrl: req.originalUrl,
// params: JSON.stringify(req.params),
// headers: JSON.stringify(req.headers)
// }
// };
// }
// function saveTraffic (req, res, next) {
// let timestamp = Date.now();
// timestamp = parseInt(timestamp);
// // console.log("tryna save req" + );
// var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress || null;
// // let request = {};
// var userdata = {
// username: req.session.user ? req.session.user.userName : "",
// _id: req.session.user ? req.session.user._id : "",
// email: req.session.user ? req.session.user.email : "",
// status: req.session.user ? req.session.user.status : "",
// authlevel: req.session.user ? req.session.user.authLevel : ""
// };
// // console.log("traffic userdata " + JSON.stringify(userdata));
// let data = {
// timestamp: timestamp,
// baseUrl: req.baseUrl,
// headers: JSON.stringify(req.headers),
// cookie: JSON.stringify(req.session.cookie),
// userdata: userdata,
// fresh: req.fresh,
// hostname: req.hostname,
// ip: req.ip,
// referring_ip: ip,
// method: req.method,
// originalUrl: req.originalUrl,
// params: JSON.stringify(req.params),
// }
// db.traffic.save(data, function (err, saved) {
// if ( err || !saved ) {
// console.log('traffic not saved!' + err);
// next();
// } else {
// next();
// // var item_id = saved._id.toString();
// // console.log('new traffic id: ' + item_id);
// }
// });
// }
function saveTraffic (req, domain, shortID) {
let timestamp = Date.now();
timestamp = parseInt(timestamp);
// console.log("tryna save req" + );
var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress || null;
// let request = {};
var userdata = {
username: req.session.user ? req.session.user.userName : "",
_id: req.session.user ? req.session.user._id : "",
email: req.session.user ? req.session.user.email : "",
status: req.session.user ? req.session.user.status : "",
authlevel: req.session.user ? req.session.user.authLevel : ""
};
// console.log("traffic userdata " + JSON.stringify(userdata));
let data = {
short_id: shortID,
appdomain: domain,
timestamp: timestamp,
baseUrl: req.baseUrl,
headers: JSON.stringify(req.headers),
cookie: JSON.stringify(req.session.cookie),
userdata: userdata,
fresh: req.fresh,
hostname: req.hostname,
ip: req.ip,
referring_ip: ip,
method: req.method,
originalUrl: req.originalUrl,
params: JSON.stringify(req.params),
}
db.traffic.save(data, function (err, saved) {
if ( err || !saved ) {
console.log('traffic not saved!' + err);
// next();
} else {
// next();
// var item_id = saved._id.toString();
// console.log('new traffic id: ' + item_id);
}
});
}
function nameCleaner(name) {
name = name.replace(/\s+/gi, '-'); // Replace white space with dash
return name.replace(/[^a-zA-Z0-9\-]/gi, ''); // Strip any special charactere
}
function checkAppID(req, res, next) {
console.log("req.headers: " + JSON.stringify(req.headers));
if (req.headers.appid) {
var a_id = ObjectID(req.headers.appid.toString().replace(":", ""));
db.apps.findOne({_id: a_id }, function (err, app) {
if (err || !app) {
console.log("no app id!");
req.session.error = 'Access denied!';
res.send("noappauth");
// next();
} else {
console.log("hey, gotsa appID!");
next();
}
});
} else {
console.log("no app id!");
req.session.error = 'Access denied!';
res.send("noappauth");
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function checkSceneTitle(titleString) {
}
function amirite (acl_rule, u_id) { //check user id against acl
// console.log("checking " + JSON.stringify(req.session));
// if (JSON.stringify(req.session.user._id.toString()) == u_id) {
// console.log("Logged in: " + req.session.user.userName);
// is there such a rule, and is this user id in it's userIDs array?
// var u_id = session.user._id;
console.log("lookin for u_id :" + u_id + " in " + acl_rule);
db.acl.findOne({$and: [{acl_rule: acl_rule}, {userIDs: {$in: [u_id]}}]}, function (err, rule) {
if (err || !rule) {
//req.session.error = 'Access denied!';
//res.send('noauth');
console.log("sorry, that's not in the acl");
return false;
} else {
console.log("yep, that's in the acl");
// next();
return true;
}
});
// }
}
function notify (req, res, next) {
}
function admin (req, res, next) { //check user id against acl
var u_id = req.session.user._id.toString();
if (req.session.user != undefined) {
if (req.session.user.authLevel != undefined) {
if (req.session.user.authLevel.includes("admin")) {
next();
} else {
req.session.error = 'Access denied!';
res.send('noauth');
}
}
}
// db.acl.findOne({$and: [{acl_rule: "admin"}, {userIDs: {$in: [u_id]}}]}, function (err, rule) {
// if (err || !rule) {
// req.session.error = 'Access denied!';
// res.send('noauth');
// console.log("sorry, that's not in the acl");
// // return false;
// } else {
// console.log("yep, that's in the acl");
// next();
// // return true;
// }
// });
}
function usercheck (req, res, next) { //gotsta beez the owner of requested resource
var u_id = req.session.user._id.toString();
var req_u_id = req.params._id;
// var scene_id = req.params.scene_id;
console.log("checkin " + u_id + " vs " + req_u_id);
if (u_id == req_u_id.toString().replace(":", "")) { //hrm.... dunno why the : needs trimming...
next();
} else {
req.session.error = 'Access denied!';
res.send('noauth');
}
}
function domainadmin (req, res, next) { //TODO also check acl
db.users.findOne({_id: ObjectID(req.session.user._id)}, function (err, user) {
if (err || !user) {
res.send("noauth");
} else {
if (user.authLevel.includes("domain_admin") || user.authLevel.includes("admin")) { //should be separate, but later..
next();
} else {
res.send("noauth");
}
}
})
}
function domainadminn (req, res, next) {
var u_id = req.session.user._id.toString();
// var req_u_id = req.params.user_id;
// var domain = req.params.domain;
// console.log("checkin " + u_id + " vs " + req_u_id);
// if (u_id == req_u_id.toString().replace(":", "")) { //hrm.... dunno why the : needs trimming...
var rule = "domain_admin_" + req.params.domain.toString().replace(":", "");
console.log("acl rule check " + rule + " vs " + u_id);
//either admin or domain admin, admin can do everything
db.acl.findOne({$or :[{$and: [{acl_rule:rule }, {userIDs: {$in: [u_id]}}]}, {$and: [{acl_rule: "admin"}, {userIDs: {$in: [u_id]}}]}]}, function (err, rule) {
if (err || !rule) {
req.session.error = 'Access denied!';
res.send('noauth');
console.log("sorry, that's not in the domain_admin acl");
// return false;
} else {
console.log("yep, that's in the domain_admin acl");
next();
// return true;
}
});
// next();
// } else {
// req.session.error = 'Access denied!';
// res.send('noauth');
// }
}
function uscene (req, res, next) { //check user id against acl, for scene writing
var u_id = req.session.user._id.toString();
var req_u_id = req.params.user_id;
var scene_id = req.params.scene_id.toString().replace(":", "");
console.log("checkin " + u_id + " vs " + req_u_id + " for " + scene_id);
if (req.session.user.authLevel.includes("admin")) {
next();
} else if (u_id == req_u_id.toString().replace(":", "")) { //hrm.... dunno why the : needs trimming...
db.acl.findOne({$and: [{"acl_rule": "write_scene_" + scene_id }, {"userIDs": {$in: [u_id]}}]}, function (err, rule) {
if (err || !rule) {
req.session.error = 'Access denied!';
res.send('noauth');
console.log("sorry, that's not in the acl");
// return false;
} else {
console.log("yep, that's in the acl");
next();
// return true;
}
});
// next();
} else {
req.session.error = 'Access denied!';
res.send('noauth');
}
}
function makeLowerCase(string) {
return string.toLowerCase();
}
function makeExtensionLowerCase (filename) {
var i = filename.lastIndexOf('.');
if (i < 0) {
return filename;
} else {
}
}
function getExtension(filename) {
// console.log("tryna get extension of " + filename);
var i = filename.lastIndexOf('.');
return (i < 0) ? '' : filename.substr(i);
}
function convertStringToObjectID (stringID) {
if (ObjectID.isValid(stringID)) {
return ObjectID(stringID);
} else {
return null;
}
}
function removeDuplicates(arr){
let unique_array = []
for(let i = 0;i < arr.length; i++){
if(unique_array.indexOf(arr[i]) == -1){
unique_array.push(arr[i])
}
}
return unique_array
}
function saveActivity (data) {
db.activity.save(data, function (err, saved) {
if ( err || !saved ) {
console.log('activity not saved..');
// res.send("nilch");
} else {
var item_id = saved._id.toString();