-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
1187 lines (1124 loc) · 45.2 KB
/
index.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
"use strict";
var express = require("express");
var router = express.Router();
var ErrorSerializer = require("../serializers/error");
var timeoutNotification;
function sendNotification(pushSubscription, payload) {
let result = t6notifications.sendPush(pushSubscription, payload).catch((error) => {
t6console.debug("pushSubscription", pushSubscription);
users.chain().find({ "id": pushSubscription.user_id }).update(function(u) {
u.pushSubscription = {};
db_users.save();
});
t6console.debug("pushSubscription is now disabled on User", error);
});
if(result && typeof result.statusCode!=="undefined" && (result.statusCode === 404 || result.statusCode === 410)) {
t6console.debug("pushSubscription", pushSubscription);
t6console.debug("Can't sendPush because of a status code Error", result.statusCode);
users.chain().find({ "id": pushSubscription.user_id }).update(function(u) {
u.pushSubscription = {};
db_users.save();
});
t6console.debug("pushSubscription is now disabled on User", error);
}
clearTimeout(timeoutNotification);
}
const getDurationInMilliseconds = (start) => {
const NS_PER_SEC = 1e9;
const NS_TO_MS = 1e6;
const diff = process.hrtime(start);
return (diff[0] * NS_PER_SEC + diff[1]) / NS_TO_MS;
};
const challengeOTP = (res, req, rp, defaultUser) => new Promise((resolve, reject) => {
let user = typeof req.user!=="undefined"?req.user:{isOTP:null};
let currentLocationIp = req.ip;
let ua = req.headers["user-agent"];
let forceOTP = req.query.forceOTP;
let geo = geoip.lookup(currentLocationIp)!==null?geoip.lookup(currentLocationIp):{};
let agent = useragent.parse(ua);
let currentDevice = typeof agent.toAgent()!=="undefined"?agent.toAgent():"";
if (typeof user.email==="undefined") {
t6console.debug("user undefined ==> No OTP");
reject("OTP challenge ==> No OTP (user undefined)");
} else {
t6console.debug("=============================== OTP ===================================");
let otpChallenge = false;
let bruteForceCount = 0;
typeof user.lastLogon!=="undefined"?user.lastLogon:0;
typeof user.lastOTP!=="undefined"?user.lastOTP:0;
if(defaultUser.session_id!=="") {
let queryBruteForce = `SELECT count(url) FROM ${rp}.requests WHERE (session_id='${defaultUser.session_id}') AND (time>now() - ${otpBruteForceWindow}) LIMIT 1`;
//t6console.debug("OTP challenge test brute force attempt", queryBruteForce);
dbInfluxDB.query(queryBruteForce).then((data) => {
bruteForceCount = typeof data[0]!=="undefined"?data[0].count:0;
t6console.debug("OTP challenge test brute force attempt", bruteForceCount);
}).catch((error) => {
t6console.error(`OTP challenge test brute force attempt error: ${error}`);
});
}
//t6console.debug("REQ", req.path);
//t6console.debug("REQ", req.user);
otpChallenge = [
//(req.path==="/objects/" && req.method==="GET"),
// New IP identified
typeof (user.geoip?.ip)!=="undefined"?((user.geoip?.ip).indexOf(currentLocationIp)===-1 && currentDevice !== "Other 0.0.0"):false,
// New localization identified
// New device identified
typeof (user.device)!=="undefined"?((user.device).indexOf(currentDevice)===-1 && currentDevice !== "Other 0.0.0"):false,
// Connexions à des heures inhabituelles
//(Date.now() > 1676147987697)
// Important user modification
(req.path==="/users/"+req.user.id && req.method==="PUT"),
// User last logged in for a while
(moment(parseInt(user.lastLogon, 10)).isBefore(moment().subtract(15, "days"))),
// Threashold on Brute Force attempt - based on session
(bruteForceCount>otpBruteForceCount), // this is async and not available // TODO
// or when user never had an OTP
(typeof req.user.lastOTP==="undefined" || req.user.lastOTP===null),
].some(isRequireChallenge);
if(str2bool(forceOTP)===true) {
otpChallenge = true;
}
if( (req.headers["x-otp"] && req.headers["x-hash"]) || (req.query.otp && req.query.hash) ) {
let otp = typeof req.headers["x-otp"]!=="undefined"?req.headers["x-otp"]:req.query.otp;
let hash = typeof req.headers["x-hash"]!=="undefined"?req.headers["x-hash"]:req.query.hash;
if ( otpTool.verifyOTP(user.email, otp, hash, otpKey, otpAlgorithm) ) {
t6events.addAudit("t6App", "OTP challenge succeed", user.id, user.id, {"status": 200});
t6events.addStat("t6App", "OTP challenge succeed", user.id, user.id, {"status": 200});
otpChallenge = false;
resolve({user, hash:null});
} else {
t6events.addAudit("t6App", "OTP challenge failed", user.id, user.id, {"status": 200});
t6events.addStat("t6App", "OTP challenge failed", user.id, user.id, {"status": 200});
reject("OTP challenge failed");
}
}
if(otpChallenge &&
// OTP requested from rules AND (either lastOTP never occured OR occured more than half the expiration)
( (typeof req.user.lastOTP==="undefined" || req.user.lastOTP===null) || (moment(parseInt(req.user.lastOTP, 10)).isBefore(moment().subtract(otpExpiresAfter/2, "minutes")))) &&
// Do not create OTP challenge if the user already have one in the past 5 days
(req.user.lastOTP!==null && moment(parseInt(req.user.lastOTP, 10)).isBefore(moment().subtract(5, "days"))) // TODO
) {
// Do not send OTP challenge more than 2 times within the OTP duration
user.lastOTP = moment().format("x");
user.isOTP = true;
user.currentLocationIp = currentLocationIp;
user.currentDevice = currentDevice;
t6console.debug("OTP challenge lastOTP is updated");
let otp = t6mailer.generateOTP(user, res);
req.user = user;
otp.then((otp) => {
t6events.addAudit("t6App", "OTP challenge emailed", user.id, user.id, {"status": 307, "error_id": 1029});
t6events.addStat("t6App", "OTP challenge emailed", user.id, user.id, {"status": 307, "error_id": 1029});
t6console.debug("============================== END OTP ==================================");
if(process.env.NODE_ENV === "development" && ua.match(/node-superagent/gi) ) {
// on development environment and when using jsonapitest
res.header("Location", `${baseUrl_https}/v${version}${req.path}?hash=${otp.hash}&otp=123456`);
}
res.status(307).json( {"hash": otp.hash} );
resolve({user, hash:otp.hash});
});
} else {
t6console.debug("OTP challenge : not necessary, bypassed");
resolve({user, hash:null});
}
}
});
/**
* @apiDefine 200
* @apiSuccess 200 Server successfully understood the request
* @apiSuccessExample {json} 200 Success
* HTTP/1.1 200 Response
* {
* }
*/
/**
* @apiDefine 201
* @apiSuccess 201 Creation of a new resource was successful
* @apiSuccessExample {json} 201 Created
* HTTP/1.1 201 Created
* {
* "message": "Created",
* "id": "",
* "code": 201
* }
*/
/**
* @apiDefine 202
* @apiSuccess 202 Server successfully understood the request, it will be done asynchroneously
* @apiSuccessExample {json} 202 Accepted
* HTTP/1.1 202 Accepted
* {
* }
*/
/**
* @apiDefine 203
* @apiSuccess 203 Non-Authoritative Information
* @apiSuccessExample {json} 203 Non-Authoritative Information
* HTTP/1.1 203 Non-Authoritative Information
* {
* }
*/
/**
* @apiDefine 204
* @apiSuccess 204 No Content on response
* @apiSuccessExample {json} 204 No Content
* HTTP/1.1 204 No Content
* {
* }
*/
/**
* @apiDefine 307
* @apiError 307 Temporary Redirect
* @apiErrorExample {json} 307 Temporary Redirect
* HTTP/1.1 307 Temporary Redirect
* {
* "message": "Temporary Redirect",
* "id": "",
* "code": 307
* }
*/
/**
* @apiDefine 400
* @apiError 400 Bad Request, require a Bearer Authentication or revision is incorrect
* @apiErrorExample {json} 400 Response
* HTTP/1.1 400 Bad Request
* {
* "message": "Bad Request",
* "id": "",
* "code": 400
* }
*/
/**
* @apiDefine 401
* @apiError 401 Require a Bearer Authentication
* @apiErrorExample {json} 401 Response
* HTTP/1.1 401 Not Authorized
* {
* "message": "Not Authorized",
* "id": "",
* "code": 401
* }
*/
/**
* @apiDefine 401sign
* @apiError 401 Signature is invalid and is required
* @apiErrorExample {json} 401sign Response
* HTTP/1.1 401 Invalid Signature
* {
* "message": "Invalid Signature",
* "id": "",
* "code": 401
* }
*/
/**
* @apiDefine 403
* @apiError 403 Forbidden Token used in transaction is not valid - check your token and/or permission
* @apiErrorExample {json} 403 Response
* HTTP/1.1 403 Forbidden
* {
* "message": "Forbidden",
* "id": "",
* "code": 403
* }
*/
/**
* @apiDefine 404
* @apiError 404 Not Found We couldn't find the resource you are trying to access
* @apiErrorExample {json} 404 Response
* HTTP/1.1 404 Not Found
* {
* "message": "Not Found",
* "id": "",
* "code": 404
* }
*/
/**
* @apiDefine 405
* @apiError 405 Method Not Allowed ; API endpoint does not accept the method used
* @apiErrorExample {json} 405 Response
* HTTP/1.1 405 Method Not Allowed
* {
* "message": "Not Authorized",
* "id": "",
* "code": 405
* }
*/
/**
* @apiDefine 409
* @apiError 409 Conflict
* @apiErrorExample {json} 409 Response
* HTTP/1.1 409 conflict
* {
* "message": "conflict",
* "id": "",
* "code": 409
* }
*/
/**
* @apiDefine 412
* @apiError 412 Precondition Failed
* @apiErrorExample {json} 412 Response
* HTTP/1.1 412 Precondition Failed
* {
* "message": "Precondition Failed",
* "id": "",
* "code": 412
* }
*/
/**
* @apiDefine 429
* @apiError 429 Too Many Requests
* @apiErrorExample {json} 429 Response
* HTTP/1.1 429 Too Many Requests
* {
* "message": "Too Many Requests",
* "id": "",
* "code": 429
* }
*/
/**
* @apiDefine 500
* @apiError 500 Internal Server Error
* @apiErrorExample {json} 500 Response
* HTTP/1.1 500 Internal Error
* {
* "message": "Internal Error",
* "id": "",
* "code": 500
* }
*/
/**
* @apiDefine NoAuth
* @apiHeader {String} [Accept=application/json] application/json
* @apiHeader {String} [Content-Type=application/json] application/json
*/
/**
* @apiDefine Auth
* @apiHeader {String} Authorization=Bearer:eyJh...sw5c Bearer <Token>
* @apiHeader {String} [Accept=application/json] application/json
* @apiHeader {String} [Content-Type=application/json] application/json
* @apiHeader {String} [x-hash] OTP Hash
* @apiHeader {String} [x-otp] One Time Password
*/
/**
* @apiDefine AuthAdmin Admin access rights needed.
* Only t6 Administrator users have permission to this Endpoint.
*
* @apiHeader {String} Authorization=Bearer:eyJh...sw5c Bearer <Token>
* @apiHeader {String} [Accept=application/json] application/json
* @apiHeader {String} [Content-Type=application/json] application/json
*/
router.use((req, res, next) => {
req.startTime = process.hrtime();
next();
});
//catch API calls for quotas and OTP
router.all("*", function (req, res, next) {
let rp = typeof influxSettings.retentionPolicies.requests!=="undefined"?influxSettings.retentionPolicies.requests:"quota4w";
var o = {
key: typeof req.user!=="undefined"?req.user.key:null,
secret: typeof req.user!=="undefined"?req.user.secret:null,
user_id: typeof req.user!=="undefined",
session_id: typeof req.sessionID!=="undefined"?req.sessionID:(typeof req.user!=="undefined"?req.user.session_id:null),
verb: req.method,
url: typeof req.path!=="undefined"?req.path:req.originalUrl,
query: (Object.keys(req.query).length > 0)?JSON.stringify(req.query):"",
date: moment().format("x")
};
if ( !req.user && req.headers.authorization && req.headers.authorization.split(" ")[1] !== null && req.headers.authorization.split(" ")[1] !== "null" ) {
jsonwebtoken.verify(req.headers.authorization.split(" ")[1], jwtsettings.secret, function(err, decodedPayload) {
if(req.headers.authorization.split(" ")[0]==="Bearer" && err) {
t6console.debug("User can't be determined:", err);
} else if(req.headers.authorization.split(" ")[0]==="Basic") {
let credentials = atob(req.headers.authorization.split(" ")[1])?.split(":");
switch(credentials[0]) {
case oauth2.find(({ name }) => name === "ifttt").config.serviceClientId:
req.user = {"name": "ifttt", "role": "oauth2"};
break;
case oauth2.find(({ name }) => name === "auth0").config.serviceClientId:
req.user = {"name": "auth0", "role": "oauth2"};
break;
default:
req.user = null;
t6console.debug("User is valid on Basic auth but we can't identify it'.");
break;
}
t6console.debug("User is valid on Basic auth", req.user);
} else {
req.user = decodedPayload;
t6console.debug("User is valid on jwt.");
}
});
}
if (
req.user &&
(
(req.headers.authorization && req.headers.authorization.split(" ")[1] !== null && req.headers.authorization.split(" ")[1] !== "null") ||
(req.headers["x-api-key"] && req.headers["x-api-secret"])
)
) {
var limit = req.user!==null?(quota[req.user.role]).calls:-1;
if (req.user !== null && req.user.role !== null ) {
res.header("X-RateLimit-Limit", limit);
}
let i;
let user_id = typeof req.user.id!=="undefined"?req.user.id:o.user_id;
let query = `SELECT count(url) FROM ${rp}.requests WHERE (user_id='${user_id}') AND (time>now() - 2w) LIMIT 1`;
dbInfluxDB.query(query).then((data) => {
i = typeof data[0]!=="undefined"?data[0].count:0;
if ( limit-i > 0 && !res.headersSent ) {
res.header("X-RateLimit-Remaining", limit-i);
//res.header("X-RateLimit-Reset", "");
}
res.header("Cache-Control", "no-cache, max-age=360, private, must-revalidate, proxy-revalidate");
if( (req.user && i >= limit) ) {
t6events.addAudit("t6Api", "api 429", typeof req.user.id!=="undefined"?req.user.id:o.user_id, typeof req.user.id!=="undefined"?req.user.id:o.user_id);
res.status(429).send(new ErrorSerializer({"id": 17329, "code": 429, "message": "Too Many Requests"}));
//return;
} else {
t6console.debug("challengeOTP starting");
let agent = useragent.parse(req.headers["user-agent"]);
let currentDevice = typeof agent.toAgent()!=="undefined"?agent.toAgent():"";
challengeOTP(res, req, rp, o).then((challenge) => {
t6console.debug("challengeOTP is completed");
req.user = challenge.user;
if ( challenge.hash!==null ) {
return;
} else {
next();
}
})
.catch((err) => {
t6console.debug("challengeOTP rejected", err);
return;
});
res.on("close", () => {
t6console.debug("Setting up the onClose rule");
let tags = {
rp: rp,
user_id: typeof req.user.id!=="undefined"?req.user.id:o.user_id,
verb: o.verb,
environment: process.env.NODE_ENV,
ip: (req.headers["x-forwarded-for"] || req.connection.remoteAddress || "").split(",")[0].trim()
};
if (o.query!=="") {
tags.query = o.query;
}
let fields = {url: o.url, durationInMilliseconds: getDurationInMilliseconds(req.startTime),session_id: typeof o.session_id!=="undefined"?o.session_id:null,};
req.session.cookie.secure = true;
req.session.user_id = req.user.id;
let dbWrite = typeof dbTelegraf!=="undefined"?dbTelegraf:dbInfluxDB;
dbWrite.writePoints([{
measurement: "requests",
tags: tags,
fields: fields,
}], { precision: "s", retentionPolicy: rp })
.then((err) => {
if (err) {
t6console.error("Error catch on writePoints to influxDb", {"err": err, "tags": tags, "fields": fields[0]});
}
}).catch((err) => {
t6console.error("Error catch on writting to influxDb", {"err": err, "tags": tags, "fields": fields[0]});
});
});
}
}).catch((err) => {
t6console.error("ERROR", err);
t6console.error("Query to count requests in the past 2w", query);
t6console.error("Role", req.user.role);
t6console.error("Limit", limit);
if(typeof i!=="undefined") {
t6console.error("429 ", i, err);
res.status(429).send(new ErrorSerializer({"id": 17330, "code": 429, "message": "Too Many Requests; or we can't perform your request."}));
next();
} else {
t6console.error("Error, i is undefined", i, err);
next();
}
});
} else {
t6console.debug("User and authorization are not defined", req.user, req.headers?.authorization);
var tags = {
rp: rp,
user_id: "anonymous",
verb: o.verb,
environment: process.env.NODE_ENV,
ip: (req.headers["x-forwarded-for"] || req.connection.remoteAddress || "").split(",")[0].trim()
};
var fields = {url: o.url,session_id: typeof o.session_id!=="undefined"?o.session_id:null,};
let dbWrite = typeof dbTelegraf!=="undefined"?dbTelegraf:dbInfluxDB;
dbWrite.writePoints([{
measurement: "requests",
tags: tags,
fields: fields,
}], { precision: "s", retentionPolicy: rp }).then((err) => {
if (err) {
t6console.error(
sprintf(
"Error on writePoints to influxDb for anonymous %s",
{"err": err, "tags": tags, "fields": fields[0]}
)
);
}
next(); // no User Auth..
}).catch((err) => {
t6console.error(
sprintf(
"Error catch on writePoints to influxDb for anonymous %s",
{"err": err, "tags": tags, "fields": fields[0]}
)
);
next(); // no User Auth..
});
}
});
function checkForTooManyFailure(req, res, email) {
// Invalid Credentials
var query = `SELECT count(*) FROM ${t6events.getMeasurement()} WHERE (what='user login failure') AND (who='${email}') AND (time>now() - 1h)`;
t6console.debug("query checkForTooManyFailure", query);
dbInfluxDB.query(query).then((data) => {
if( typeof data==="object" && typeof data[0]!=="undefined" && data[0].count_who > 2 && data[0].count_who < 4 ) {
// when >4, then we should block the account and maybe ban the IP address
var geo = geoip.lookup(req.ip)!==null?geoip.lookup(req.ip):{};
geo.ip = req.ip;
var agent = useragent.parse(req.headers["user-agent"]);
res.render("emails/loginfailure", {device: typeof agent.toAgent()!=="undefined"?agent.toAgent():"", geoip: geo}, function(err, html) {
var to = email;
var mailOptions = {
from: from,
bcc: typeof bcc!=="undefined"?bcc:null,
to: to,
user_id: "unknown",
subject: "t6 warning notification",
text: "Html email client is required",
html: html
};
t6mailer.sendMail(mailOptions).then(function(info){
t6console.info("info" + info);
}).catch(function(error){
t6console.error("t6mailer.sendMail error" + error.info.code + error.info.response + error.info.responseCode + error.info.command);
});
});
return data[0].count_who;
}
}).catch((err) => {
t6console.error(err);
t6events.addAudit("t6App", "user login failure", email, email);
return undefined;
});
}
function isRequireChallenge(element, index, array) {
return element===true;
}
/**
* @api {delete} /tokens/all Delete all expired users tokens
* @apiName Delete all expired users tokens
* @apiGroup 8. Administration
* @apiVersion 2.0.1
* @apiUse AuthAdmin
* @apiPermission AuthAdmin
*
* @apiUse 201
* @apiUse 403
*/
router.delete("/tokens/all", function (req, res) {
if ( req.user.role === "admin" ) {
tokens = db_tokens.getCollection("tokens");
var expired = tokens.find( { "$and": [{ "expiration" : { "$lt": moment().format("x") } }, { "expiration" : { "$ne": "" } } ]} );
if ( expired ) {
tokens.remove(expired);
db_tokens.save();
}
t6events.addAudit("t6App", "AuthAdmin: {delete} /tokens/all", "", "", {"status": "201", error_id: "00003"});
return res.status(201).json( {status: "ok", "cleaned": expired.length} );
} else {
t6events.addAudit("t6App", "AuthAdmin: {delete} /tokens/all", "", "", {"status": "403", error_id: "17050"});
return res.status(403).send(new ErrorSerializer({"id": 17050, "code": 403, "message": "Forbidden, You should be an Admin!"}).serialize());
}
});
/**
* @api {post} /authenticate Authenticate - JWT Token
* @apiName Authenticate - JWT Token
* @apiDescription The authenticate endpoint provide an access token which is multiple use but expiring within 5 minutes.
* Once it has expired an access_token can be refreshed to extend duration or you can generate a new one from this authenticate endpoint.
* Several Authentification process are handled: using your personnal credentials, using a Key+Secret Access long life Token (which can be revoked)
* @apiGroup 13. Users
* @apiVersion 2.0.1
*
* @apiBody (Body) {String="password","refresh_token","access_token"} grant_type="password" Grant type is the method to authenticate using your own credentials, using a pair of Key/Secret or refreshing a Bearer token before it expires.
* @apiBody (Body) {String} [username] Your own username, required only when grant_type="password"
* @apiBody (Body) {String} [password] Your own password, required only when grant_type="password"
* @apiBody (Body) {String} [key=undefined] Client Api Key, required only when grant_type="access_token"
* @apiBody {String} [secret=undefined] Client Api Secret, required only when grant_type="access_token"
* @apiBody {String} [refresh_token=undefined] The refresh_token you want to use in order to get a new token
* @apiQuery {String} [forceOTP] Force One Time Password request
*
* @apiSuccess {String} status Status of the Authentication
* @apiSuccess {String} token JWT Token
* @apiSuccess {timestamp} tokenExp Expiration timestamp of the JWT Token
* @apiSuccess {String} refresh_token Token that can be used to refresh the Token
* @apiSuccess {timestamp} refreshTokenExp Expiration timestamp of the Refresh Token
*
* @apiUse NoAuth
* @apiUse 200
* @apiUse 307
* @apiUse 400
* @apiUse 401
* @apiUse 403
*/
router.post("/authenticate", function (req, res) {
let meta = { pushSubscription : (typeof req.body.pushSubscription?.endpoint!=="undefined" && typeof req.body.pushSubscription?.keys!=="undefined")?req.body.pushSubscription:undefined};
let rp = typeof influxSettings.retentionPolicies.requests!=="undefined"?influxSettings.retentionPolicies.requests:"quota4w";
let o = {
key: typeof req.user!=="undefined"?req.user.key:null,
secret: typeof req.user!=="undefined"?req.user.secret:null,
user_id: typeof req.user!=="undefined",
session_id: typeof req.sessionID!=="undefined"?req.sessionID:(typeof req.user!=="undefined"?req.user.session_id:null),
verb: req.method,
url: typeof req.path!=="undefined"?req.path:req.originalUrl,
query: (Object.keys(req.query).length > 0)?JSON.stringify(req.query):"",
date: moment().format("x")
};
if ( (req.body.username !== "" && req.body.password !== "") && (!req.body.grant_type || req.body.grant_type === "password") ) {
let email = (req.body.username).toLowerCase();
let password = req.body.password;
let queryU = { "$and": [ { "email": email } ] };
let user = users.findOne(queryU);
if ( user && typeof user.password!=="undefined" ) {
user.quotausage = undefined;
user.data = undefined;
let geo = geoip.lookup(req.ip)!==null?geoip.lookup(req.ip):{};
let agent = useragent.parse(req.headers["user-agent"]);
let currentDevice = typeof agent.toAgent()!=="undefined"?agent.toAgent():"";
if ( bcrypt.compareSync(password, user.password) || md5(password) === user.password ) {
user.location = {geo: geo};
user.isOTP=false; // reset value
req.user = user;
challengeOTP(res, req, rp, o).then((challenge) => {
t6console.debug("challengeOTP is completed", challenge);
req.user = challenge.user;
user = req.user;
if ( challenge.hash!==null ) {
t6console.debug("challengeOTP challenged at login");
return;
} else {
if(Array.isArray(user.geoip?.ip)===true) {
if((user.geoip?.ip).indexOf(req.ip)===-1) {
(user.geoip?.ip).push(req.ip);
t6console.debug("IP added the the list for that user.");
} else {
t6console.debug("IP already listed for that user.");
}
} else {
if(typeof user.geoip!=="undefined" && user.geoip?.ip!==null) {
user.geoip.ip = [user.geoip?.ip];
} else {
user.geoip = {ip:[]};
}
(user.geoip?.ip).push(req.ip);
t6console.debug("IP added the the list for that user.");
}
if(Array.isArray(user.device)===true) {
if((user.device).indexOf(currentDevice)===-1) {
(user.device).push(currentDevice);
t6console.debug("Device added the the list for that user.");
} else {
t6console.debug("Device already listed for that user.");
}
} else {
if(user.device!==null) {
user.device = [user.device];
}
(user.device).push(currentDevice);
t6console.debug("Device added the the list for that user.");
}
/* pushSubscription */
if ( typeof meta.pushSubscription !== "undefined" ) {
let payloadMessage = "{\"type\": \"message\", \"title\": \"Successfully auth\", \"body\": \"Welcome back to t6! Enjoy.\", \"icon\": null, \"vibrate\":[200, 100, 200, 100, 200, 100, 200]}";
meta.user_id = user.id;
timeoutNotification = setTimeout(sendNotification, 5000, meta, payloadMessage);
user.pushSubscription = meta.pushSubscription;
}
user.lastLogon = moment().format("x");
t6console.debug("User is logged in. Updated the lastLogon value.");
users.update(user);
db_users.save();
req.session.cookie.secure = true;
req.session.cookie.user_id = user.id;
let payload = JSON.parse(JSON.stringify(user));
payload.unsubscription = user.unsubscription;
payload.permissions = undefined;
payload.token = undefined;
payload.password = undefined;
payload.gravatar = undefined;
payload.meta = undefined;
payload.$loki = undefined;
payload.geoip = undefined;
payload.device = undefined;
payload.token_type = "Bearer";
payload.scope = "Application";
payload.sub = "/users/"+user.id;
if ( user.location && user.location.ip ) {
payload.iss = req.ip+" - "+user.location.ip;
}
if(req.headers && req.headers["user-agent"] && (req.headers["user-agent"]).indexOf("t6iot-library") > -1) {
payload.location = undefined;
payload.unsubscription_token = undefined;
payload.passwordLastUpdated = undefined;
payload.iftttCode = undefined;
payload.iftttTrigger_identity = undefined;
payload.subscription = undefined;
payload.unsubscription = undefined;
payload.pushSubscription = undefined;
payload.reminderMail = undefined;
payload.changePassword = undefined;
payload.newsletter = undefined;
payload.quotausage = undefined;
payload.data = undefined;
payload.changePasswordMail = undefined;
payload.mail_hash = undefined;
payload.update_date = undefined;
payload.subscription_date = undefined;
payload.scope = undefined;
payload.firstName = undefined;
payload.lastName = undefined;
payload.iss = undefined;
payload.sub = undefined;
payload.token_type = undefined;
}
var token = jsonwebtoken.sign(payload, jwtsettings.secret, { expiresIn: jwtsettings.expiresInSeconds });
var refreshPayload = crypto.randomBytes(40).toString("hex");
var refreshTokenExp = moment().add(jwtsettings.refreshExpiresInSeconds, "seconds").format("x");
let t = {
user_id: user.id,
refresh_token: refreshPayload,
expiration: refreshTokenExp,
"user-agent": {
"agent": agent.toAgent(),
"string": agent.toString(),
"version": agent.toVersion(),
"os": agent.os.toString(),
"osVersion": agent.os.toVersion(),
},
"device": agent.device.toString(),
"geo": geoip.lookup(req.ip)!==null?geoip.lookup(req.ip):{},
};
tokens.insert(t);
var expired = tokens.find( { "$and": [{ "expiration" : { "$lt": moment().format("x") } }, { "expiration" : { "$ne": "" } } ]} );
if ( expired ) {
tokens.remove(expired);
db_tokens.save(); // There might be a bug here. not the same tokens !
}
var refresh_token = user.id + "." + refreshPayload;
t6events.addAudit("t6App", "POST_authenticate password", user.id, user.id, {"status": 200});
t6events.addStat("t6App", "POST_authenticate password", user.id, user.id, {"status": 200});
if(!user.isOTP) { // TODO: we should not use that tips ! This is to prevent 'already sent headers'' error
return res.status(200).json( {status: "ok", token: token, tokenExp: jwtsettings.expiresInSeconds, refresh_token: refresh_token, refreshTokenExp: refreshTokenExp} );
}
}
})
.catch((err) => {
t6console.debug("challengeOTP rejected", err);
t6events.addAudit("t6App", "POST_authenticate password", user.id, user.id, {"status": 403, "error_id": 102.31});
t6events.addStat("t6App", "POST_authenticate password", user.id, user.id, {"status": 403, "error_id": 102.31});
return res.status(403).send(new ErrorSerializer({"id": 17350, "code": 403, "message": "OTP challenge rejected"}).serialize());
});
} else {
let count = checkForTooManyFailure(req, res, email);
t6events.addAudit("t6App", "POST_authenticate password", user.id, user.id, {"status": 403, "error_id": 102.11});
t6events.addStat("t6App", "POST_authenticate password", user.id, user.id, {"status": 403, "error_id": 102.11});
return res.status(403).send(new ErrorSerializer({"id": 17150, "code": 403, "message": "Forbidden"}).serialize());
}
} else {
t6console.debug("No user found or no password set yet.");
t6events.addAudit("t6App", "POST_authenticate password", email, email, {"status": 403, "error_id": 102.21});
t6events.addStat("t6App", "POST_authenticate password", email, email, {"status": 403, "error_id": 102.21});
t6console.error("Auth Error", email, req.body.username, {"status": 403, "error_id": 102.21});
return res.status(403).send(new ErrorSerializer({"id": 17250, "code": 403, "message": "Forbidden"}).serialize());
}
} else if ( ( req.body.key && req.body.secret ) && req.body.grant_type === "access_token" ) {
let queryT = {
"$and": [
{ "key": req.body.key },
{ "secret": req.body.secret },
]
};
let u = access_tokens.findOne(queryT);
if ( u && typeof u.user_id !== "undefined" ) {
let user = users.findOne({id: u.user_id});
let geo = geoip.lookup(req.ip);
user.location = {geo: geo, ip: req.ip,}
/* pushSubscription */
if ( typeof meta.pushSubscription !== "undefined" ) {
let payloadMessage = "{\"type\": \"message\", \"title\": \"Successfully auth\", \"body\": \"Welcome back to t6! Enjoy.\", \"icon\": null, \"vibrate\":[200, 100, 200, 100, 200, 100, 200]}";
meta.user_id = user.id;
timeoutNotification = setTimeout(sendNotification, 5000, meta, payloadMessage);
user.pushSubscription = meta.pushSubscription;
}
users.update(user);
db_users.save();
let payload = JSON.parse(JSON.stringify(user));
payload.permissions = undefined;
payload.token = undefined;
payload.password = undefined;
payload.gravatar = undefined;
payload.meta = undefined;
payload.$loki = undefined;
payload.geoip = undefined;
payload.device = undefined;
payload.token_type = "Bearer";
payload.scope = "ClientApi";
payload.sub = "/users/"+user.id;
if ( user.location && user.location.ip ) {
payload.iss = req.ip+" - "+user.location.ip;
}
if(req.headers && req.headers["user-agent"] && (req.headers["user-agent"]).indexOf("t6iot-library") > -1) {
payload.location = undefined;
payload.unsubscription_token = undefined;
payload.passwordLastUpdated = undefined;
payload.iftttCode = undefined;
payload.iftttTrigger_identity = undefined;
payload.subscription = undefined;
payload.unsubscription = undefined;
payload.pushSubscription = undefined;
payload.reminderMail = undefined;
payload.changePassword = undefined;
payload.newsletter = undefined;
payload.quotausage = undefined;
payload.data = undefined;
}
let token = jsonwebtoken.sign(payload, jwtsettings.secret, { expiresIn: jwtsettings.expiresInSeconds });
let refreshPayload = crypto.randomBytes(40).toString("hex");
let refreshTokenExp = moment().add(jwtsettings.refreshExpiresInSeconds, "seconds").format("x");
let agent = useragent.parse(req.headers["user-agent"]);
let t = {
user_id: user.id,
refresh_token: refreshPayload,
expiration: refreshTokenExp,
"user-agent": {
"agent": agent.toAgent(),
"string": agent.toString(),
"version": agent.toVersion(),
"os": agent.os.toString(),
"osVersion": agent.os.toVersion(),
},
"device": agent.device.toString(),
"geo": geoip.lookup(req.ip)!==null?geoip.lookup(req.ip):{},
};
tokens.insert(t);
let expired = tokens.find( { "$and": [{ "expiration" : { "$lt": moment().format("x") } }, { "expiration" : { "$ne": "" } } ]} );
if ( expired ) {
tokens.remove(expired);
db_tokens.save();
}
let refresh_token = user.id + "." + refreshPayload;
t6events.addAudit("t6App", "POST_authenticate access_token", user.id, user.id, {"status": 200});
t6events.addStat("t6App", "POST_authenticate access_token", user.id, user.id, {"status": 200});
return res.status(200).json( {status: "ok", token: token, tokenExp: jwtsettings.expiresInSeconds, refresh_token: refresh_token, refreshTokenExp: refreshTokenExp} );
} else {
t6events.addAudit("t6App", "POST_authenticate access_token", req.body.key, req.body.key, {"status": 403, "error_id": 102.32});
t6events.addStat("t6App", "POST_authenticate access_token", req.body.key, req.body.key, {"status": 403, "error_id": 102.32});
return res.status(403).send(new ErrorSerializer({"id": 17350, "code": 403, "message": "Forbidden"}).serialize());
}
} else if ( typeof req.body.refresh_token!=="undefined" && req.body.refresh_token!=="" && req.body.grant_type === "refresh_token" ) {
let user_id = req.body.refresh_token.split(".")[0];
let token = req.body.refresh_token.split(".")[1];
let queryT = {
"$and": [
{ "user_id": user_id },
{ "refresh_token": token },
{ "expiration": { "$gte": moment().format("x") } },
]
};
if ( user_id && token && tokens.findOne(queryT) ) {
// Sign a new token
let user = users.findOne({ "id": user_id });
let geo = geoip.lookup(req.ip);
user.location = {geo: geo, ip: req.ip,}
users.update(user);
db_users.save();
let payload = JSON.parse(JSON.stringify(user));
payload.permissions = undefined;
payload.token = undefined;
payload.password = undefined;
payload.gravatar = undefined;
payload.meta = undefined;
payload.$loki = undefined;
payload.geoip = undefined;
payload.device = undefined;
payload.token_type = "Bearer";
payload.scope = "ClientApi";
payload.sub = "/users/"+user.id;
if(req.headers && req.headers["user-agent"] && (req.headers["user-agent"]).indexOf("t6iot-library") > -1) {
payload.location = undefined;
payload.unsubscription_token = undefined;
payload.passwordLastUpdated = undefined;
payload.iftttCode = undefined;
payload.iftttTrigger_identity = undefined;
payload.subscription = undefined;
payload.unsubscription = undefined;
payload.pushSubscription = undefined;
payload.reminderMail = undefined;
payload.changePassword = undefined;
payload.newsletter = undefined;
payload.quotausage = undefined;
payload.data = undefined;
}
let token = jsonwebtoken.sign(payload, jwtsettings.secret, { expiresIn: jwtsettings.expiresInSeconds });
let refreshPayload = crypto.randomBytes(40).toString("hex");
let refreshTokenExp = moment().add(jwtsettings.refreshExpiresInSeconds, "seconds").format("x");
let agent = useragent.parse(req.headers["user-agent"]);
let t = {
user_id: user.id,
refresh_token: refreshPayload,
expiration: refreshTokenExp,
"user-agent": {
"agent": agent.toAgent(),
"string": agent.toString(),
"version": agent.toVersion(),
"os": agent.os.toString(),
"osVersion": agent.os.toVersion(),
},
"device": agent.device.toString(),
"geo": geoip.lookup(req.ip)!==null?geoip.lookup(req.ip):{},
};
tokens.insert(t);
/* Added the new refresh token, then we should remove the one used in the refresh process */
let tQ = {
"$and": [
{ "user_id": user.id },
{ "refresh_token": req.body.refresh_token.split(".")[1] },
]
};
tokens.findAndRemove(tQ);
let expired = tokens.find( { "$and": [{ "expiration" : { "$lt": moment().format("x") } }, { "expiration" : { "$ne": "" } } ]} );
if ( expired ) {
tokens.remove(expired);
db_tokens.save();
}
let refresh_token = user.id + "." + refreshPayload;
t6events.addAudit("t6App", "POST_authenticate refresh_token", user_id, user_id, {"status": 200});
t6events.addStat("t6App", "POST_authenticate refresh_token", user_id, user_id, {"status": 200});
return res.status(200).json( {status: "ok", token: token, tokenExp: jwtsettings.expiresInSeconds, refresh_token: refresh_token, refreshTokenExp: refreshTokenExp} );
} else {
t6events.addAudit("t6App", "POST_authenticate refresh_token", user_id, user_id, {"status": 403, "error_id": 102.43});
t6events.addStat("t6App", "POST_authenticate refresh_token", user_id, user_id, {"status": 403, "error_id": 102.43});
return res.status(403).send(new ErrorSerializer({"id": 17450, "code": 403, "message": "Invalid Refresh Token"}).serialize());
}
} else {
t6events.addAudit("t6App", "POST_authenticate refresh_token", null, null, {"status": 400, "error_id": 102.33});
t6events.addStat("t6App", "POST_authenticate refresh_token", null, null, {"status": 400, "error_id": 102.33});
return res.status(400).send(new ErrorSerializer({"id": 17550, "code": 400, "message": "Required param grant_type and/or username+password needs to be defined"}).serialize());
}
});
/**
* @api {post} /refresh Refresh a JWT Token
* @apiName Refresh a JWT Token
* @apiDescription This endpoint allows you to extend access_token expiration date. The extension is the same (5 minutes) as the authenticate endpoint.
*
* @apiGroup 13. Users
* @apiVersion 2.0.1
*
* @apiHeader {String} Authorization Bearer <Token>
* @apiHeader {String} [Accept] application/json
* @apiHeader {String} [Content-Type] application/json
*
* @apiUse NoAuth
* @apiUse 200
* @apiUse 403
*/
router.post("/refresh", function (req, res) {
// get the refreshToken from body
var refreshToken = req.body.refreshToken;
// Find that refreshToken in Db
tokens = db_tokens.getCollection("tokens");
var queryT = {
"$and": [
{ "refreshToken": refreshToken },
{"expiration": { "$gte": moment().format("x") }},
]
};
var expired = tokens.find( { "$and": [{ "expiration" : { "$lt": moment().format("x") } }, { "expiration" : { "$ne": "" } } ]} );
if ( expired ) {
tokens.remove(expired);
db_tokens.save();
}