-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.js
1294 lines (1227 loc) · 46.6 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
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
/** jQuery Initialisation **/
(function ($) {
$(function () {
}); // end of document ready
})(jQuery); // end of jQuery name space
function toggle_visibility(id) {
const e = document.getElementById(id);
e.classList.remove('may-be-hidden');
}
function hide(id) {
const e = document.getElementById(id);
e.classList.add('may-be-hidden');
}
/** WebSockets init**/
var arr = window.location.href.split('/');
var urlSockets = arr[0] + "//" + arr[2];
var socket;
async function fetchApi({
uri,
method = "GET",
headers = { "Content-Type": "application/json", 'Accept': 'application/json' },
body,
onSuccess, // res => {} (executed if status >= 200 && < 300)
onStatus = {}, // {status: (res) => {}}
}) {
try {
const res = await fetch(uri, { method, headers, body });
res.data = await res.json();
if (res.ok) {
await onSuccess?.(res);
} else if (res.data?.code === 'REDIRECT') {
window.alert("Session expirée. Veuillez vous reconnecter.")
return document.location.replace(res.data.path); // redirect to res.data.path (/login or /forbidden)
} else if (onStatus[res.status]) {
await onStatus[res.status](res);
} else {
const err = new Error(JSON.stringify({ status: res.status, data: res.data }));
err.res = res;
throw err;
}
return res;
} catch (err) {
console.error(err.res?.url || uri, err);
throw err;
}
}
/** base64url helper functions **/
/**
* Convert from a Base64URL-encoded string to an Array Buffer. Best used when converting a
* credential ID from a JSON string to an ArrayBuffer, like in allowCredentials or
* excludeCredentials
*
* Helper method to compliment `bufferToBase64URLString`
*/
function base64URLStringToBuffer(base64URLString) {
// Convert from Base64URL to Base64
const base64 = base64URLString.replace(/-/g, '+').replace(/_/g, '/');
/**
* Pad with '=' until it's a multiple of four
* (4 - (85 % 4 = 1) = 3) % 4 = 3 padding
* (4 - (86 % 4 = 2) = 2) % 4 = 2 padding
* (4 - (87 % 4 = 3) = 1) % 4 = 1 padding
* (4 - (88 % 4 = 0) = 4) % 4 = 0 padding
*/
const padLength = (4 - (base64.length % 4)) % 4;
const padded = base64.padEnd(base64.length + padLength, '=');
// Convert to a binary string
const binary = atob(padded);
// Convert binary string to buffer
const buffer = new ArrayBuffer(binary.length);
const bytes = new Uint8Array(buffer);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return buffer;
}
/**
* Convert the given array buffer into a Base64URL-encoded string. Ideal for converting various
* credential response ArrayBuffers to string for sending back to the server as JSON.
*
* Helper method to compliment `base64URLStringToBuffer`
*
* source: https://github.com/MasterKale/SimpleWebAuthn/blob/master/packages/browser/src/helpers/bufferToBase64URLString.ts
*/
function bufferToBase64URLString(buffer) {
const bytes = new Uint8Array(buffer);
let str = '';
for (const charCode of bytes) {
str += String.fromCharCode(charCode);
}
const base64String = btoa(str);
return base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
function getImgWithAltText({ qrCodeImg, qrCodeSrc, alt = "QR code Esup Auth" }) {
if (!qrCodeSrc) {
if (qrCodeImg) {
// extract src from img
qrCodeSrc = new DOMParser().parseFromString(qrCodeImg, 'text/html').querySelector('img')?.src;
} else {
return "";
}
}
return `<img src="${qrCodeSrc}" alt="${alt}">`;
}
function toast(message, displayLength, className){
Materialize.toast(message, displayLength, className);
$('.toast').last()[0].setAttribute('role', 'alert');
}
/** Vue.JS **/
/** User **/
var PushMethod = Vue.extend({
props: {
'user': Object,
'get_user': Function,
'messages': Object,
'infos': Object,
'activate': Function,
'deactivate': Function,
'switch_push_event': {}
},
created: function() {
socket = io.connect(urlSockets, { reconnect: true, path: "/sockets" });
socket.on('userPushActivate', () => {
this.activatePush();
});
socket.on('userPushActivateManager', () => {
this.activatePush();
});
socket.on('userPushDeactivate', () => {
this.deActivatePush();
});
},
methods: {
activatePush: function() {
this.setActivePush(true);
},
deActivatePush: function() {
this.setActivePush(false);
},
setActivePush: async function(active) {
// Temporarily set the opposite value, to help VueJs detect the change #33
this.$set(this.user.methods.push, "active", !active);
this.get_user(this.user.uid);
}
},
template: '#push-method'
});
var BypassMethod = Vue.extend({
props: {
'user': Object,
'generate_bypass': Function,
'activate': Function,
'deactivate': Function,
'messages': Object,
'infos': Object,
},
template: '#bypass-method'
});
const TotpMethod = Vue.extend({
props: {
'user': Object,
'generate_totp': Function,
'activate': Function,
'deactivate': Function,
'messages': Object,
'infos': Object,
'formatApiUri': Function,
},
methods: {
validate: function() {
const totpCode = this.user.methods.totp.validation_code;
this.user.methods.totp.validation_code = '';
return fetchApi({
method: "POST",
uri: this.formatApiUri("/totp/activate/confirm/" + totpCode),
onSuccess: res => {
if (res.data.code != "Ok") {
toast('Erreur, veuillez réessayer.', 3000, 'red darken-1');
} else {
this.user.methods.totp.active = true;
this.user.methods.totp.qrCode = '';
this.user.methods.totp.message = '';
toast('Code validé', 3000, 'green contrasted');
}
},
onStatus: {
401: res => {
toast(this.messages.api.methods.random_code.verify_code.wrong, 3000, 'red darken-1');
}
}
});
}
},
template: '#totp-method'
});
const WebAuthnMethod = Vue.extend({
props: {
'user': Object,
'activate': Function,
'deactivate': Function,
'messages': Object,
'infos': Object,
'formatApiUri': Function,
},
data() {
return {
realData: { // example (will be override by mounted() )
nonce: "",
auths: [], // [{credentialID: "", credentialPublicKey: "", counter: 0, name: ""}],
user_id: "",
rp: { "name": "Univ", "id": "univ.fr" },
pubKeyTypes: [{ "type": "public-key", "alg": - 7 }],
},
registrationInProgress: false,
}
},
async mounted() {
await this.fetchAuthData();
if(this.realData.auths.length === 0) {
this.generateWebauthn();
}
},
computed: {
descriptionMessage() {
switch (this.realData.auths.length) {
case 0:
return this.messages.api.methods.webauthn.no_authentificators;
case 1:
return this.messages.api.methods.webauthn.single_auth;
default:
return this.messages.api.methods.webauthn.nb_of_auths.replace('%NB%', this.realData.auths.length);
}
},
},
watch: {
'user.uid': function(newUid, oldUid) {
if (newUid !== oldUid) {
this.fetchAuthData();
}
}
},
methods: {
fetchAuthData: async function() {
const res = await fetchApi({
method: "POST",
uri: this.formatApiUri("/generate/webauthn"),
});
this.realData = res.data;
return this.realData;
},
getAuthById: function (id) {
return this.realData.auths.find(authenticator => authenticator.credentialID === id);
},
renameAuthenticator: function(authCredID) {
const auth = this.getAuthById(authCredID);
const previousName = auth.name;
return Swal.fire({ // https://sweetalert2.github.io/#configuration
title: this.messages.api.action.rename + ' ' + previousName,
input: "text",
icon: "question",
inputPlaceholder: this.messages.api.methods.webauthn.new_name,
inputValue: previousName,
customClass: { // https://sweetalert2.github.io/#customClass
input: "webauthn-factor-rename-input",
confirmButton: "waves-effect waves-light btn green contrasted",
cancelButton: "waves-effect waves-light btn red darken-1",
},
showCancelButton: true,
allowOutsideClick: false,
inputValidator: (newName) => {
if (!newName.trim()) {
return this.messages.error.webauthn.registration_failed;
}
},
showLoaderOnConfirm: true,
preConfirm: async (newName) => {
if (previousName == newName) {
return;
}
let statusCode;
try {
const res = await fetchApi({
method: "POST",
uri: this.formatApiUri("/webauthn/auth/" + authCredID),
body: JSON.stringify({
name: newName
}),
});
await this.fetchAuthData();
statusCode = res.status;
} catch (e) {
console.error(e);
}
if (statusCode == 200) {
toast(this.messages.success.webauthn.renamed, 3000, 'green contrasted');
} else {
toast(this.messages.error.webauthn.generic, 3000, 'red darken-1');
}
}
});
},
deleteAuthenticator: function(authCredID) {
// TODO : USE MESSAGES FILES FOR LOCALISATION
const auth = this.getAuthById(authCredID);
const name = auth.name;
return Swal.fire({ // https://sweetalert2.github.io/#configuration
title: this.messages.api.action.webauthn.confirm_delete.replace("%NAME%", name),
icon: "warning",
customClass: { // https://sweetalert2.github.io/#customClass
confirmButton: "waves-effect waves-light btn red darken-1",
cancelButton: "waves-effect waves-light btn green contrasted",
},
focusDeny: true,
reverseButtons: true,
showCancelButton: true,
allowOutsideClick: true,
showLoaderOnConfirm: true,
preConfirm: async () => {
let statusCode;
try {
const res = await fetchApi({
method: "DELETE",
uri: this.formatApiUri("/webauthn/auth/" + authCredID),
});
await this.fetchAuthData();
statusCode = res.status;
} catch (e) {
console.error(e);
}
if (statusCode == 200) {
toast(this.messages.success.webauthn.deleted, 3000, 'green contrasted');
} else {
toast(this.messages.error.webauthn.delete_failed, 3000, 'red darken-1');
}
}
});
},
generateWebauthn: async function() {
this.registrationInProgress = true;
try {
const data = await this.fetchAuthData();
// arguments for the webauthn registration
const publicKeyCredentialCreationOptions = {
challenge: base64URLStringToBuffer(data.nonce),
rp: data.rp,
rpId: data.rp.id,
user: {
id: Uint8Array.from(data.user_id),
name: `${this.user.uid}@${data.rp.id}`,
displayName: `${this.user.uid}`
},
// Spec recommends at least supporting these
pubKeyCredParams: data.pubKeyTypes,
// user has 3 * 60 seconds to register
timeout: 3 * 60000,
// leaks data about the user if in direct mode.
attestation: "none",
extensions: {
credProps: true,
},
authenticatorSelection: {
residentKey:"preferred",
requireResidentKey:false,
userVerification:"preferred"
},
// Don't register the same credentials twice
excludeCredentials: data.auths.map(a => ({id: base64URLStringToBuffer(a.credentialID), type: "public-key"})),
};
// register
const credentials = await navigator.credentials.create({publicKey: publicKeyCredentialCreationOptions});
// PublicKeyCredential can not be serialized
// because it contains some ArrayBuffers, which
// can not be serialized.
// This just translates the buffer to its' 'safe'
// version.
// This is only for the REGISTRATION part
// It is slightly different from what is
// used for authentication
const SerializePKC = PKC => {
return {
id: PKC.id,
type: PKC.type,
rawId: bufferToBase64URLString(PKC.rawId),
response: {
attestationObject: bufferToBase64URLString(PKC.response.attestationObject),
clientDataJSON: bufferToBase64URLString(PKC.response.clientDataJSON),
}
};
}
await fetchApi({
method: "POST",
uri: this.formatApiUri("/webauthn/confirm_activate"),
body: JSON.stringify({
cred: SerializePKC(credentials),
cred_name: "Authenticator " + credentials.id.slice(-5),
}),
onSuccess: async res => {
if (res.data.registered) { // SUCCESS
await this.fetchAuthData();
await this.renameAuthenticator(credentials.id);
}
else {
toast(this.messages.error.webauthn.registration_failed, 3000, 'red darken-1');
}
},
onStatus: {422: () => {
toast(this.messages.error.webauthn.timeout, 3000, 'red darken-1');
}},
});
}
catch(e) {
// Already registered
if(e.name === "InvalidStateError") {
toast(this.messages.error.webauthn.already_registered, 3000, 'red darken-1');
}
// user said no / something like that
else if(e.name === "NotAllowedError") {
toast(this.messages.error.webauthn.user_declined, 3000, 'red darken-1');
}
else {
toast(this.messages.error.webauthn.generic, 3000, 'red darken-1');
console.error("/api/webauthn/confirm_activate", e);
}
} finally {
this.registrationInProgress = false;
}
},
},
template: '#webauthn-method',
});
Vue.component('transport-form', {
props: {
'user': Object,
'messages': Object,
'infos': Object,
'transport': String,
'inputType': String,
'saveTransport': Function,
'deleteTransport': Function,
},
template: '#transport_form'
});
const RandomCodeMethod = Vue.extend({
props: {
'user': Object,
'messages': Object,
'infos': Object,
'activate': Function,
'deactivate': Function,
'formatApiUri': Function,
},
methods: {
saveTransport: async function(transport) {
const new_transport = document.getElementById(transport + '-input').value.trim();
try {
const res = await fetchApi({
method: "GET",
uri: this.formatApiUri('/transport/' + transport + '/' + new_transport + "/test"),
});
const data = res.data;
if (data.code != "Ok") {
toast('Erreur interne, veuillez réessayer plus tard.', 3000, 'red darken-1');
} else {
const expected = data.otp;
const verifyCodeMessages = this.messages.api.methods.random_code.verify_code;
Swal.fire({ // https://sweetalert2.github.io/#configuration
title: verifyCodeMessages[transport].title,
html: verifyCodeMessages[transport].pre + new_transport + verifyCodeMessages[transport].post,
input: "number",
icon: "question",
// inputLabel: "Code",
inputPlaceholder: "000000",
customClass: { // https://sweetalert2.github.io/#customClass
popup: "modal",
container: "modal-content",
input: "center-align",
confirmButton: "waves-effect waves-light btn green contrasted",
cancelButton: "waves-effect waves-light btn red darken-1",
},
showCancelButton: true,
allowOutsideClick: false,
inputValidator: input => {
if (input != expected) {
return verifyCodeMessages.wrong;
}
},
showLoaderOnConfirm: true,
preConfirm: async () => {
const res = await fetchApi({
method: "PUT",
uri: this.formatApiUri('/transport/' + transport + '/' + new_transport),
});
const data = res.data;
if (data.code != "Ok") {
toast('Erreur interne, veuillez réessayer plus tard.', 3000, 'red darken-1');
} else {
// equivalent to "this.user.transports[transport] = new_transport;", but allows new reactive property to be added dynamically
Vue.set(this.user.transports, transport, new_transport);
document.getElementById(transport + '-input').value = '';
toast('Transport vérifié', 3000, 'green contrasted');
}
}
});
}
} catch (err) {
toast(err, 3000, 'red darken-1');
};
},
deleteTransport: function(transport) {
var oldTransport = this.user.transports[transport];
this.user.transports[transport] = null;
return fetchApi({
method: "DELETE",
uri: this.formatApiUri('/transport/' + transport),
onSuccess: res => {
if (res.data.code != "Ok") {
throw new Error(JSON.stringify({ code: res.data.code }));
}
},
}).catch(err => {
this.user.transports[transport] = oldTransport;
toast(err, 3000, 'red darken-1');
});
},
},
template: '#random_code-method'
});
const RandomCodeMailMethod = RandomCodeMethod.extend({
template: '#random_code_mail-method'
});
var Esupnfc = Vue.extend({
template:'#esupnfc-method'
});
var UserDashboard = Vue.extend({
props: {
'messages': Object,
'infos': Object,
'methods': Object,
'user': Object,
'currentmethod': String,
'get_user': Function
},
components: {
"push": PushMethod,
"totp": TotpMethod,
"bypass": BypassMethod,
"webauthn": WebAuthnMethod,
"random_code": RandomCodeMethod,
"random_code_mail": RandomCodeMailMethod,
"esupnfc":Esupnfc
},
template: "#user-dashboard",
created: function () {
},
methods: {
formatApiUri: function(url) {
return '/api' + url;
},
activate: function (method) {
switch (method) {
case 'push':
this.askPushActivation();
break;
case 'bypass':
this.standardActivate(method);
this.generateBypass()
.catch(err => {
this.user.methods.bypass.active = false;
});
break;
case 'random_code':
this.standardActivate(method);
break;
case 'random_code_mail':
this.standardActivate(method);
break;
case 'totp':
this.generateTotp();
break;
case 'webauthn':
this.standardActivate(method);
break;
case 'esupnfc':
this.standardActivate(method);
break;
default:
this.user.methods[method].active = true;
break;
}
},
askPushActivation: function() {
this.user.methods.push.askActivation = true;
this.user.methods.push.active = true;
return fetchApi({
method: "PUT",
uri: "/api/push/activate",
onSuccess: res => {
const data = res.data;
if (data.code == "Ok") {
this.user.methods.push.activationCode = data.activationCode;
this.user.methods.push.qrCode = getImgWithAltText({ qrCodeImg: data.qrCode, qrCodeSrc: data.qrCodeSrc });
this.user.methods.push.api_url = this.infos.api_url;
} else {
throw new Error(JSON.stringify({ code: data.code }));
}
},
}).catch(err => {
toast('Erreur interne, veuillez réessayer plus tard.', 3000, 'red darken-1');
});
},
standardActivate: function(method) {
return fetchApi({
method: "PUT",
uri: "/api/" + method + "/activate",
onSuccess: res => {
const data = res.data;
if (data.code == "Ok") {
this.user.methods[method].active = true;
} else {
throw new Error(JSON.stringify({ code: data.code }));
}
},
}).catch(err => {
toast('Erreur interne, veuillez réessayer plus tard.', 3000, 'red darken-1');
});
},
deactivate: function(method) {
if (window.confirm(this.messages.api.action.confirm_deactivate)) {
if (this.user.methods[method].askActivation) {
this.user.methods[method].askActivation = false;
}
return fetchApi({
method: "PUT",
uri: "/api/" + method + "/deactivate",
onSuccess: res => {
const data = res.data;
if (data.code == "Ok") {
this.user.methods[method].active = false;
} else {
console.error(JSON.stringify({ code: data.code }));
throw new Error("Erreur interne, veuillez réessayer plus tard.");
}
},
}).catch(err => {
this.user.methods[method].active = true;
toast(err, 3000, 'red darken-1');
});
}
},
generateBypassConfirm : function(){
if (window.confirm(this.messages.api.action.confirm_generate))
this.generateBypass();
},
generateTotpConfirm : function(){
if (window.confirm(this.messages.api.action.confirm_generate))
this.generateTotp();
},
generateBypass: function() {
return fetchApi({
method: "POST",
uri: "/api/generate/bypass",
onSuccess: res => {
const data = res.data;
if (data.code == "Ok") {
this.user.methods.bypass.codes = data.codes;
} else {
throw new Error(JSON.stringify({ code: data.code }));
}
},
}).catch(err => {
toast(err, 3000, 'red darken-1');
throw err;
});
},
generateTotp: function() {
return fetchApi({
method: "POST",
uri: "/api/generate/totp?require_method_validation=true",
onSuccess: res => {
const data = res.data;
if (data.code == "Ok") {
this.user.methods.totp.active = true;
this.user.methods.totp.message = data.message;
this.user.methods.totp.qrCode = getImgWithAltText({ qrCodeImg: data.qrCode, qrCodeSrc: data.qrCodeSrc });
this.user.methods.totp.uid = this.user.uid;
} else {
throw new Error(JSON.stringify({ code: data.code }));
}
},
}).catch(err => {
toast(err, 3000, 'red darken-1');
throw err;
});
}
}
});
/** Manager **/
var UserView = Vue.extend({
props: {
'user': Object,
'methods': Object,
'messages': Object,
'infos': Object,
"get_user": Function
},
components: {
"push": PushMethod,
"totp": TotpMethod,
"bypass": BypassMethod,
"webauthn": WebAuthnMethod,
"random_code": RandomCodeMethod,
"random_code_mail": RandomCodeMailMethod,
"esupnfc":Esupnfc
},
data: function () {
return {
"switchPushEvent": MouseEvent
}
},
template: '#user-view',
methods: {
formatApiUri: function(url) {
return '/api/admin' + url + '/' + this.user.uid;
},
activate: function (method) {
switch (method) {
case 'push':
this.askPushActivation();
break;
case 'bypass':
this.standardActivate(method);
this.generateBypass()
.catch(err => {
this.user.methods.bypass.active = false;
});
break;
case 'webauthn':
this.standardActivate(method);
break;
case 'random_code':
this.standardActivate(method);
break;
case 'random_code_mail':
this.standardActivate(method);
break;
case 'totp':
this.generateTotp();
break;
case 'esupnfc':
this.standardActivate(method);
break;
default:
/** **/
this.user.methods[method].active = true;
break;
}
},
askPushActivation: function () {
this.user.methods.push.askActivation = true;
this.user.methods.push.active = true;
return fetchApi({
method: "PUT",
uri: "/api/admin/" + this.user.uid + "/push/activate",
onSuccess: res => {
const data = res.data;
if (data.code == "Ok") {
this.user.methods.push.activationCode = data.activationCode;
this.user.methods.push.qrCode = getImgWithAltText({ qrCodeImg: data.qrCode, qrCodeSrc: data.qrCodeSrc });
this.user.methods.push.api_url = this.infos.api_url;
} else {
throw new Error(JSON.stringify({ code: data.code }));
}
},
}).catch(err => {
toast('Erreur interne, veuillez réessayer plus tard.', 3000, 'red darken-1');
});
},
standardActivate: function(method) {
return fetchApi({
method: "PUT",
uri: "/api/admin/" + this.user.uid + "/" + method + "/activate",
onSuccess: res => {
const data = res.data;
if (data.code == "Ok") {
this.user.methods[method].active = true;
} else {
throw new Error(JSON.stringify({ code: data.code }));
}
},
}).catch(err => {
toast('Erreur interne, veuillez réessayer plus tard.', 3000, 'red darken-1');
});
},
deactivate: function(method) {
if (window.confirm(this.messages.api.action.confirm_deactivate)) {
if (this.user.methods[method].askActivation)
this.user.methods[method].askActivation = false;
return fetchApi({
method: "PUT",
uri: "/api/admin/" + this.user.uid + "/" + method + "/deactivate",
onSuccess: res => {
const data = res.data;
if (data.code == "Ok") {
this.user.methods[method].active = false;
} else {
console.error(JSON.stringify({ code: data.code }));
throw new Error("Erreur interne, veuillez réessayer plus tard.");
}
},
}).catch(err => {
this.user.methods[method].active = true;
toast(err, 3000, 'red darken-1');
});
}
},
generateBypassConfirm : function(){
if (window.confirm(this.messages.api.action.confirm_generate)) this.generateBypass();
},
generateTotpConfirm : function(){
if (window.confirm(this.messages.api.action.confirm_generate)) this.generateTotp();
},
generateBypass: function() {
return fetchApi({
method: "POST",
uri: "/api/admin/generate/bypass/" + this.user.uid,
onSuccess: res => {
const data = res.data;
if (data.code == "Ok") {
this.user.methods.bypass.codes = data.codes;
} else {
throw new Error(JSON.stringify({ code: data.code }));
}
},
}).catch(err => {
toast(err, 3000, 'red darken-1');
throw err;
});
},
generateTotp: function() {
return fetchApi({
method: "POST",
uri: "/api/admin/generate/totp/" + this.user.uid + "?require_method_validation=true",
onSuccess: res => {
const data = res.data;
if (data.code == "Ok") {
this.user.methods.totp.active = true;
this.user.methods.totp.message = data.message;
this.user.methods.totp.qrCode = getImgWithAltText({ qrCodeImg: data.qrCode, qrCodeSrc: data.qrCodeSrc });
this.user.methods.totp.uid = this.user.uid;
} else {
throw new Error(JSON.stringify({ code: data.code }));
}
},
}).catch(err => {
toast(err, 3000, 'red darken-1');
throw err;
});
},
}
});
var ManagerDashboard = Vue.extend({
props: {
'methods': Object,
'messages': Object,
'infos': Object,
},
components: {
"user-view": UserView
},
data: function () {
return {
user: {
uid: String,
methods: Object,
transports: Object
},
uids: [],
requestedUid: '',
}
},
computed: {
suggestions() {
return this.uids.filter(uid => uid.toLowerCase().includes(this.requestedUid.toLowerCase()));
},
requestedUidExists() {
return this.suggestions.includes(this.requestedUid);
},
},
created: function () {
if (this.uids?.length) {
return;
}
return fetchApi({
method: "GET",
uri: "/api/admin/users",
onSuccess: res => {
this.uids = res.data.uids;
},
}).catch(err => {
toast(err, 3000, 'red darken-1');
});
},
mounted: async function() {
const url = new URL(location);
const user = url.searchParams.get('user');
if (user) { // if url contains ?user=xxx
await this.$nextTick();
await this.getUser(user); // display user xxx
await this.$nextTick();
url.searchParams.set('user', '');
history.pushState({}, '', url); // and remove xxx from current url
}
},
methods: {
search: function () {
if (this.requestedUid) {
this.getUser(this.requestedUid);
if(!this.requestedUidExists) {
this.uids.push.push(this.requestedUid);
toast('utilisateur '+this.requestedUid+' ajouté avec succès', 3000, 'green contrasted');
}
this.requestedUid = '';
}
},
getUser: function(uid) {
return fetchApi({
method: "GET",
uri: "/api/admin/user/" + uid,
onSuccess: res => {
const data = res.data;
data.uid = uid;
this.setUser(data);
},
}).catch(err => {
toast(err, 3000, 'red darken-1');
});
},
setUser: function(data) {
this.user = {
uid: data.uid,
methods: data.user.methods,
transports: data.user.transports
}
}
},
template: '#manager-dashboard'