-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathM365_Token_Repeater.html
1554 lines (1311 loc) · 53 KB
/
M365_Token_Repeater.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>M365 Token Repeater</title>
<style>
body, html {
height: 100%;
margin: 0;
font-feature-settings: normal;
font-family: monospace;
font-variation-settings: normal;
line-height: 1.5;
tab-size: 4;
}
.container {
display: flex;
height: 100%;
}
.left-panel {
flex-shrink: 0;
width: 20%;
background-color: black;
padding: 20px;
overflow: auto;
}
.middle-content {
flex-grow: 1;
padding: 20px;
overflow-y: auto;
color: white;
background-color: #343541;
}
.button-left{
display: block;
width: 100%;
padding: 10px;
margin-bottom: 10px;
background-color: #343541;
color: white;
border: none;
text-align: left;
cursor: pointer;
border-radius: 5px;
}
.button-center {
display: block;
/* width: 100%; */
padding: 10px;
margin-bottom: 10px;
background-color: #343541;
color: white;
border: none;
text-align: left;
cursor: pointer;
/* border-radius: 5px; */
}
.button-center1 {
/* display: block; */
/* width: 100%; */
padding: 10px;
margin-bottom: 10px;
background-color: darkred;
color: white;
border: none;
text-align: left;
cursor: pointer;
}
.button-left:hover {
background-color: #1f1f24;
}
.button-center {
background-color: darkred;
}
.button-center:hover {
background-color: black;
}
.button-center1:hover {
background-color: black;
}
.search-input {
display: none;
}
.tab {
overflow: hidden;
/* border: 1px solid #ccc; */
/* background-color: #f1f1f1; */
}
.tab button {
background-color: inherit;
color: white;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
.tab button:hover {
background-color: #ddd;
color: black;
}
.tab button.active {
background-color: #ccc;
color: black;
}
.tabcontent {
display: none;
padding: 6px 12px;
/* border: 1px solid #ccc; */
border-top: none;
}
.tabcontent {
padding: 10px; /* Adjust as needed */
}
.tabcontent textarea {
width: 100%;
max-width: 100%;
height: 150px;
box-sizing: border-box;
padding: 4px;
margin-bottom: 10px;
border: 1px solid #ccc;
resize: vertical;
}
.tabcontent {
width: 100%;
}
#refreshTokens select,
#refreshTokens textarea {
width: 100%;
box-sizing: border-box;
}
#refreshTokens textarea {
height: 157px;
}
@media (max-width: 980px) {
#refreshTokens select,
#refreshTokens textarea {
max-width: none;
}
}
#accessTokens select,
#accessTokens textarea {
width: 100%;
box-sizing: border-box;
}
#accessTokens textarea {
height: 157px;
}
@media (max-width: 980px) {
#accessTokens select,
#accessTokens textarea {
max-width: none;
}
}
.response {
display: block;
width: 100%;
padding: 10px;
margin-bottom: 10px;
background-color: #343541;
color: white;
border: none;
text-align: left;
cursor: pointer;
border-radius: 5px;
}
pre {
white-space: pre-wrap;
word-wrap: break-word;
overflow-wrap: break-word;
word-break: break-all;
width: 100%;
}
.tablinks{
margin-left: 10px;
}
#idToken{
margin-left: 10px;
}
.input-center{
/* display: block; */
width: 300px;
height: 24px;
padding: 5px;
margin-bottom: 10px;
margin-left: 10px;
background-color: white;
color: black;
border: none;
text-align: left;
/* border-radius: 5px; */
}
.left-panel-line{
border: 1px solid #fff;
}
#responseOutput table {
background-color: black;
}
#responseOutput table tbody tr.highlight {
background-color: red;
}
.chart-wrapper {
background-color: black;
}
</style>
</head>
<body>
<div class="container">
<!-- Left Panel -->
<div class="left-panel">
<button id="uploadButton" class="button-left">Upload HAR File...</button>
<input type="file" id="fileInput" accept=".har" multiple class="search-input" style="display:none;">
<button id="uploadButtonJson" class="button-left">Upload JSON File...</button>
<input type="file" id="fileInputJson" accept=".json" multiple class="search-input" style="display:none;">
<button id= "accessTokenButton" class="button-left" >Access Token</button>
<button id= "refreshTokenButton" class="button-left" >Refresh Token</button>
<pre class="left-panel-line"></pre>
<button id= "meButton" class="button-left">Info (me)</button>
<button id= "listUsersButton" class="button-left" >List Users</button>
<button id= "listGroupsButton" class="button-left" >List Groups</button>
<button id= "listDevices" class="button-left">List Devices</button>
<button id= "MFAPrediction" class="button-left" >MFA Prediction</button>
<pre class="left-panel-line"></pre>
<button id= "exportUsersButton" class="button-left" >Export Users</button>
<button id= "exportAllUsersButton" class="button-left" >Export Users Full</button>
<button id= "exportGroupsButton" class="button-left" >Export Groups</button>
<button id= "exportDevicesButton" class="button-left" >Export Devices</button>
<p style="color: white;">
Version: 1.0 @quahac
<a title="https://github.com/quahac" href="https://github.com/quahac" target="_blank" style="color: white; text-decoration: underline;">GitHub</a>
<a title="https://x.com/quahac" href="https://x.com/quahac" target="_blank" style="color: white; text-decoration: underline;">X</a>
</p>
</div>
<!-- Left Panel End -->
<!-- Middle Panel -->
<div class="middle-content">
<!-- Access Token -->
<div id="accessTokenTab" class="tabcontent">
<div id="accessTokens">
<label>Url:</label><br>
<select id="urlsAccessTokens" size="5"></select>
<br><label>Bearer in request:</label><br>
<select id="headerAccessTokens" size="3"></select>
</div>
</div>
<!-- Refresh token -->
<div id="refreshTokenTab" class="tabcontent">
<div id="refreshTokens">
<label>Url:</label><br>
<select id="urlsRefreshTokens" size="3"></select><br>
<label>Request:</label><br>
<textarea id="requestRefreshTokens" rows="10" cols="50"></textarea>
<br>
<button class="button-center" id="requestButtonRefreshTokens">Replay Request to Generate Access Token</button>
<textarea id="responseRefreshTokens" rows="10" cols="50"></textarea>
</div>
</div>
<!-- Token Input -->
<label id="idToken" for="token">Access Token:</label>
<input class="input-center" type="text" id="token" name="token" required>
<button class="button-center1" id="parseTokenButton">Parse Token</button>
<button class="button-center1" id="clearTokenButton">Clear Token</button>
<button class="button-center1" id="copyTokenButton">Copy Token</button>
<pre class="response" id="jwtFields"></pre>
<!-- <input type="text" id="searchInput" onkeyup="searchTable()" placeholder="Search for names..">
<div id="chart_div" style="width: 400px; height: 120px;"></div> -->
<pre id="responseOutput"></pre>
<!-- <p id="coords">Mouse Position: X: 0, Y: 0</p> -->
</div>
<!-- Middle Panel End -->
<script>
const accessTokenButton = document.getElementById('accessTokenButton');
const refreshTokenButton = document.getElementById('refreshTokenButton');
const uploadButton = document.getElementById('uploadButton');
const fileInput = document.getElementById('fileInput');
const uploadButtonJson = document.getElementById('uploadButtonJson');
const fileInputJson = document.getElementById('fileInputJson');
const parseTokenButton = document.getElementById('parseTokenButton');
const clearTokenButton = document.getElementById('clearTokenButton');
const copyTokenButton = document.getElementById('copyTokenButton');
const tabcontent = document.getElementsByClassName("tabcontent");
const tablinks = document.getElementsByClassName("tablinks");
const urlsAccessTokens = document.getElementById('urlsAccessTokens');
const headerAccessTokens = document.getElementById('headerAccessTokens');
const urlsRefreshTokens = document.getElementById('urlsRefreshTokens');
const requestRefreshTokens = document.getElementById('requestRefreshTokens');
const requestButtonRefreshTokens = document.getElementById('requestButtonRefreshTokens');
const responseRefreshTokens = document.getElementById('responseRefreshTokens');
const tokenInput = document.getElementById('token');
const jwtFieldsContainer = document.getElementById('jwtFields');
const responseOutput = document.getElementById('responseOutput');
const listUsersButton = document.getElementById('listUsersButton');
const exportUsersButton = document.getElementById('exportUsersButton');
const exportAllUsersButton = document.getElementById('exportAllUsersButton');
const exportGroupsButton = document.getElementById('exportGroupsButton');
const exportDevicesButton = document.getElementById('exportDevicesButton');
const MFAPredictionButton = document.getElementById('MFAPrediction');
const listGroupsButton = document.getElementById('listGroupsButton');
const meButton = document.getElementById('meButton');
const listDevices = document.getElementById('listDevices');
listGroupsButton.addEventListener('click',()=> listGroupsFunction())
listDevices.addEventListener('click',()=> listDevicesFunction())
meButton.addEventListener('click',()=> meInfo())
exportAllUsersButton.addEventListener('click',() => downloadAllUsers())
exportGroupsButton.addEventListener('click',() => downloadGroups())
exportDevicesButton.addEventListener('click',() => downloadDevices())
MFAPredictionButton.addEventListener('click',() => getUsersDataFull())
accessTokenButton.addEventListener('click',() => openTab(event, 'accessTokenTab'))
refreshTokenButton.addEventListener('click',() => openTab(event, 'refreshTokenTab'))
// jwtFieldsContainer.addEventListener('click',() => openTab(event, 'refreshTokenTab'))
urlsAccessTokens.addEventListener('change',() => updateHeaders(urlsAccessTokens.value))
headerAccessTokens.addEventListener('change',() => copyToInput())
// urlsRefreshTokens.addEventListener('click',()=> displayRequestDetails())
urlsRefreshTokens.addEventListener('change',()=> displayRequestDetails())
requestButtonRefreshTokens.addEventListener('click',()=> replayRequest())
parseTokenButton.addEventListener('click', parseAndDisplayToken);
clearTokenButton.addEventListener('click', clearToken);
copyTokenButton.addEventListener('click', copyText);
// File Input Handle
uploadButton.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', () => {
const fileNames = Array.from(fileInput.files).map(file => file.name).join(', ');
uploadButton.textContent = fileNames.length > 0 ? `Files Selected: ${fileNames}` : 'Select Files';
allUsers.length = 0 // CLEAR ALL USERS
allDevices.length = 0 // CLEAR ALL DEVICES
});
// File Input Handle
uploadButtonJson.addEventListener('click', () => fileInputJson.click());
// fileInputJson.addEventListener('change', () => {
// const fileNames = Array.from(fileInputJson.files).map(file => file.name).join(', ');
// uploadButtonJson.textContent = fileInputJson.length > 0 ? `Files Selected: ${fileNames}` : 'Select Files';
// // allUsers.length = 0 // CLEAR ALL USERS
// // allDevices.length = 0 // CLEAR ALL DEVICES
// });
function openTab(evt, documentIdName) {
// Use forEach for cleaner iteration over HTMLCollections
Array.from(tabcontent).forEach(content => content.style.display = "none");
Array.from(tablinks).forEach(link => link.classList.remove("active"));
// Display the clicked tab's content and add "active" class to the clicked tab link
document.getElementById(documentIdName).style.display = "block";
evt.currentTarget.classList.add("active");
responseOutput.textContent = ''
jwtFieldsContainer.style.display = "block"
}
// HAR file read input file // AccessToken / RefreshToken parse
let headersByURL = {};
fileInput.addEventListener('change', function(event) {
headersByURL = {};
clearSelectionBoxes();
const files = event.target.files;
if (!files) {
return;
}
Array.from(files).forEach(file => {
const reader = new FileReader();
reader.onload = function(e) {
const content = e.target.result;
const har = JSON.parse(content);
processHarFile(har);
filteredEntries = har.log.entries.filter(entry =>
entry.request.postData && entry.request.postData.text.includes('grant_type=refresh_token'));
populateListbox(filteredEntries);
};
reader.readAsText(file);
});
});
function processHarFile(har) {
const entries = har.log.entries;
entries.forEach(entry => {
entry.request.headers.forEach(header => {
if (header.name.toLowerCase() === 'authorization'
&& header.value.toLowerCase().includes('bearer')
&& header.value.length > 10) {
const url = entry.request.url;
if (!headersByURL[url]) {
headersByURL[url] = new Set();
}
headersByURL[url].add(header.value);
}
});
});
updateUrlsSelectBox();
}
function updateUrlsSelectBox() {
urlsAccessTokens.innerHTML = '';
for (const url in headersByURL) {
const option = document.createElement('option');
option.textContent = url;
option.value = url;
urlsAccessTokens.appendChild(option);
}
}
function clearSelectionBoxes() {
if (urlsAccessTokens) urlsAccessTokens.innerHTML = '';
if (headerAccessTokens) headerAccessTokens.innerHTML = '';
}
function updateHeaders(selectedUrl) {
headerAccessTokens.innerHTML = '';
if (headersByURL[selectedUrl]) {
headersByURL[selectedUrl].forEach(headerValue => {
const bearerToken = headerValue.replace('Bearer ', '').trim();
const option = document.createElement('option');
option.textContent = bearerToken;
headerAccessTokens.appendChild(option);
});
if (headerAccessTokens.options.length > 0) {
headerAccessTokens.selectedIndex = 0; // Select the first item
copyToInput(); // Copy the value of the first item to the input
parseAndDisplayToken();
}
}
}
function copyToInput() {
if (headerAccessTokens.selectedIndex >= 0) {
tokenInput.value = headerAccessTokens.options[headerAccessTokens.selectedIndex].text;
}
parseAndDisplayToken();
}
function populateListbox(entries) {
urlsRefreshTokens.innerHTML = '';
entries.forEach((entry, index) => {
const option = document.createElement('option');
option.value = index;
option.textContent = entry.request.url;
urlsRefreshTokens.appendChild(option);
});
}
function displayRequestDetails() {
const selectedIndex = urlsRefreshTokens.selectedIndex;
const selectedEntry = filteredEntries[selectedIndex];
if (selectedEntry) {
const requestLine = `${selectedEntry.request.method} ${selectedEntry.request.url} HTTP/1.1\n`;
// const headers = selectedEntry.request.headers.map(header => `${header.name}: ${header.value}`).join('\n');
const headers = selectedEntry.request.headers
.filter(header => !header.name.startsWith(':'))
.map(header => `${header.name}: ${header.value}`)
.join('\n');
const body = selectedEntry.request.postData ? `\n\n${selectedEntry.request.postData.text}` : '';
requestRefreshTokens.value = requestLine + headers + body;
}
}
async function replayRequest() {
const requestDetails = requestRefreshTokens.value;
try {
const { url, options } = parseRequestDetails(requestDetails);
const response = await fetch(url, options);
const text = await response.text();
responseRefreshTokens.value = text;
// Check if response is JSON and extract access_token
try {
const jsonResponse = JSON.parse(text);
if (jsonResponse.access_token) {
tokenInput.value = jsonResponse.access_token;
document.getElementById('parseTokenButton').click(); // Programmatically click the button
}
} catch (jsonError) {
// Handle the case where the response is not JSON or doesn't contain access_token
console.error('JSON parsing error or access_token not found:', jsonError);
}
} catch (error) {
responseRefreshTokens.value = 'Error: ' + error.message;
}
}
function parseRequestDetails(details) {
const lines = details.split('\n');
const requestLine = lines[0].split(' ');
const method = requestLine[0];
const url = requestLine[1];
const headers = {};
let body = null;
let isBody = false;
lines.slice(1).forEach(line => {
if (line === '') {
isBody = true;
return;
}
if (!isBody) {
const [key, value] = line.split(': ');
headers[key] = value;
} else {
body = (body || '') + line;
}
});
return {
url: url,
options: {
method: method,
headers: headers,
body: method !== 'GET' ? body : undefined
}
};
}
// DISPLAY TOKEN
function parseAndDisplayToken() {
allDevices.length = 0
allUsers.length = 0
const jwt = tokenInput.value;
try {
// Ensure the JWT format is correct
if (!jwt || jwt.split('.').length !== 3) {
throw new Error('Invalid JWT format');
}
// Parse the JWT payload (second part of the JWT)
const payloadBase64 = jwt.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
const decodedPayload = atob(payloadBase64);
let payload;
try {
payload = JSON.parse(decodedPayload);
} catch (e) {
throw new Error('Invalid payload: Not valid JSON');
}
// Calculate minutes to expire
const expirationDate = new Date(payload.exp * 1000);
const currentDate = new Date();
const differenceInMilliseconds = expirationDate - currentDate;
const minutesToExpire = Math.floor(differenceInMilliseconds / 60000);
// Extract the desired fields and add Minutes to Expire
const extractedFields = {
Token: minutesToExpire >= 0 ? `${minutesToExpire} minutes to expire` : 'Expired',
Audience: payload.aud || 'n/a',
Issuer: payload.iss || 'n/a',
// Consider using toLocaleString() with options for better readability
ExpirationTime: expirationDate.toLocaleString(),
AppDisplayName: payload.app_displayname || 'n/a',
AppID: payload.appid || 'n/a',
Name: payload.name || 'n/a',
UserPrincipalName: payload.upn || 'n/a',
Scope: payload.scp || 'n/a',
TenantID: payload.tid || 'n/a',
};
jwtFieldsContainer.innerHTML = '';
Object.entries(extractedFields).forEach(([field, value]) => {
const div = document.createElement('div');
if (field === 'Token') {
const contentSpan = document.createElement('span');
contentSpan.textContent = value;
contentSpan.style.backgroundColor = value === 'Expired' ? 'darkred' : 'darkgreen';
contentSpan.style.color = 'white';
div.textContent = `${field}: `;
div.appendChild(contentSpan);
} else {
div.textContent = `${field}: ${value}`;
}
jwtFieldsContainer.appendChild(div);
});
} catch (error) {
jwtFieldsContainer.innerHTML = '';
const errorDiv = document.createElement('div');
errorDiv.textContent = error.message;
errorDiv.style.backgroundColor = 'darkred';
errorDiv.style.color = 'white';
jwtFieldsContainer.appendChild(errorDiv);
}
}
let me_info = []
function meInfo() {
responseOutput.textContent = 'Loading...';
document.getElementById("accessTokenTab").style.display = "none";
document.getElementById("refreshTokenTab").style.display = "none";
const accessToken = tokenInput.value;
fetch('https://graph.microsoft.com/v1.0/me', {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`, // Authorization header with the access token
'Content-Type': 'application/json' // Additional headers can be specified here
}
})
.then(response => {
if (response.ok) {
return response.json(); // Parse JSON response if response was ok
}
switch (response.status) {
case 400:
throw new Error('Bad Request. Please check your request parameters.');
case 401:
throw new Error('Unauthorized. Please check your access token.');
case 403:
throw new Error('Forbidden. You do not have permission to access this resource.');
case 404:
throw new Error('Not Found. The requested resource could not be found.');
case 500:
throw new Error('Internal Server Error. Something went wrong on the server.');
default:
throw new Error(`Error: ${response.status}. ${response.statusText}`);
}
})
.then(data => {
// Display the data in a table format
const table = document.createElement('table');
for (const key in data) {
if (key !== "@odata.context") { // Skip the @odata.context field
const row = table.insertRow();
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
cell1.textContent = key.charAt(0).toUpperCase() + key.slice(1); // Capitalize first letter
cell2.textContent = Array.isArray(data[key]) ? data[key].join(', ') : data[key];
}
}
// Clear the previous content and append the new table
responseOutput.innerHTML = '';
responseOutput.appendChild(table);
jwtFieldsContainer.style.display = "none";
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
responseOutput.textContent = error.toString();
});
}
//List Users
let allUsers = [] //STORE USERS
async function allUsers_get() {
// allUsers.length = 0
clearDisplay();
if (allUsers && allUsers.length > 0) {
const userPrincipalNames = allUsers.map(user => user.userPrincipalName);
responseOutput.textContent = userPrincipalNames.join('\n');
console.log("Displaying users from memory");
return; // Exit the function
}
const token = tokenInput.value;
try {
allUsers = await fetchAllUsers(token);
// Display userPrincipalName fields only
if (allUsers && allUsers.length > 0) {
const userPrincipalNames = allUsers.map(user => user.userPrincipalName);
responseOutput.textContent = userPrincipalNames.join('\n');
window.userPrincipalNamesForExport = userPrincipalNames; // Store for exporting
} else {
responseOutput.textContent = 'No users found.';
}
} catch (error) {
responseOutput.textContent = 'Error: ' + error.message;
}
}
// Use the async function directly in the event listener
listUsersButton.addEventListener('click', async function() {
await allUsers_get();
});
// Function to fetch all users using pagination
async function fetchAllUsers(token) {
const initialUrl = 'https://graph.microsoft.com/v1.0/users';
// let allUsers = [];
let url = initialUrl;
while (url) {
const response = await fetch(url, {
headers: { Authorization: `Bearer ${token}` }
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); // Handle HTTP errors
}
const data = await response.json();
if (data.value) {
allUsers.push(...data.value); // Efficiently add users to the array
}
url = data['@odata.nextLink'];
}
return allUsers;
}
// Function to copy text to clipboard
function copyTextToClipboard(text) {
const textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
// Event listener for clicks on the document
jwtFieldsContainer.addEventListener("click", function(event) {
const target = event.target; // The clicked element
if (target.id) { // Check if the element has an ID
const textToCopy = target.innerText || target.textContent; // Get the text content
// console.log(textToCopy)
copyTextToClipboard(textToCopy);
// alert("Text copied: " + textToCopy);
}
});
// Assuming listUsers is an async function or returns a promise that resolves once userPrincipalNamesForExport is populated
function listUsers() {
return new Promise((resolve, reject) => {
listUsersButton.click();
// Wait for some condition to be met (e.g., userPrincipalNamesForExport is populated)
// This is a placeholder; you need to replace it with actual logic to determine when the operation is complete
let checkInterval = setInterval(() => {
if (window.userPrincipalNamesForExport) {
clearInterval(checkInterval);
resolve();
}
// Optionally, include a timeout to reject the promise if it takes too long
}, 100); // Check every 100ms
});
}
// Function to export users to a text file
function exportUsersToFile(users) {
const userText = users.join('\n');
const blob = new Blob([userText], { type: 'text/plain' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'users.txt';
a.click();
}
// Export Users
exportUsersButton.addEventListener('click', function() {
clearDisplay()
if (window.userPrincipalNamesForExport) {
exportUsersToFile(window.userPrincipalNamesForExport);
} else {
listUsers().then(() => {
if (window.userPrincipalNamesForExport) {
exportUsersToFile(window.userPrincipalNamesForExport);
} else {
alert('No user data available for export.');
}
}).catch((error) => {
console.error('Error listing users:', error);
alert('Failed to list users.');
});
}
});
let myData = []
let mergedData = []
// USER DATA EXPORT
// USER DATA EXPORT
function getUsersDataFull() {
clearDisplay()
if(mergedData && mergedData.length > 0){
generateAndInsertTable(mergedData,1)
return
}
function downloadJSON(content, filename) {
const blob = new Blob([content], { type: 'text/plain' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
}
const secret = document.getElementById("token").value;
async function fetchData(id) {
const response = await fetch("https://graph.microsoft.com/beta/users/" + id + "?$select=id,accountEnabled,userPrincipalName,lastPasswordChangeDateTime,createdDateTime", {
headers: {
accept: "application/json, text/plain, */*",
authorization: "Bearer " + secret
},
method: "GET"
});
return response.json();
}
let formattedData = [];
async function fetchUserData() {
let tableString = ""
lengthUsers = myData.length + 1
for (const data of myData) {
try {
const userData = await fetchData(data.id);
const formattedUserDisplay = {
id: userData.id,
userPrincipalName: userData.userPrincipalName,
countLengthUsers: lengthUsers = lengthUsers-1
};
const timeDifference = Math.floor((new Date(userData.lastPasswordChangeDateTime).getTime() - new Date(userData.createdDateTime).getTime()) / 1000);
const formattedUser = {
id: userData.id,
userPrincipalName: userData.userPrincipalName,
lastPasswordChangeDateTime: userData.lastPasswordChangeDateTime,
createdDateTime: userData.createdDateTime,
timeDifference: timeDifference,
accountEnabled: userData.accountEnabled,
mfaEnabled: (Math.floor((new Date(userData.lastPasswordChangeDateTime).getTime() - new Date(userData.createdDateTime).getTime()) / 1000) <= 0) ? 'false' : '?'
};
formattedData.push(formattedUser);
// if (userData.accountEnabled){
// Format each user's data with fixed-width columns
tableString += `${formattedUserDisplay.countLengthUsers.toString().padEnd(2)} - ${formattedUserDisplay.userPrincipalName.toString().padEnd(97)}\n`;
//}
} catch (error) {
console.error(error);
}
// Set the table string as the textContent of the pre element
document.getElementById('responseOutput').textContent = tableString;
}
}
async function fetchAllDataAndUserData() {
async function fetchData(url) {
try {
const response = await fetch(url, {
"headers": {
"accept": "application/json, text/plain, */*",
"authorization": "Bearer " + secret
},
"method": "GET"
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
return data;
} catch (error) {
throw error;
}
}
async function fetchAllData() {
try {
let url = "https://graph.microsoft.com/beta/users";
while (url) {
const data = await fetchData(url);
if (data && data.value) {
myData = myData.concat(data.value);
}
await new Promise(resolve => setTimeout(resolve, 1000));
url = data['@odata.nextLink'];
}
} catch (error) {
console.error('Error:', error);
}
}
await fetchAllData();
await fetchUserData();
}
(async () => {
await fetchAllDataAndUserData();
mergedData = myData.map(data => {
const formattedUser = formattedData.find(user => user.id === data.id);
return { ...data, ...formattedUser };
});
generateAndInsertTable(mergedData,1)
// const mergedJSON = JSON.stringify(mergedData);
// downloadJSON(mergedJSON, "users_full.json");
// document.getElementById("MFAPrediction").style.display = "block";
})();
}
function downloadAllUsers(){
function downloadJSON(content, filename) {
const blob = new Blob([content], { type: 'text/plain' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
}
const mergedJSON = JSON.stringify(mergedData);
downloadJSON(mergedJSON, "users_full.json");
}
let allGroupsList
async function listGroupsFunction() {
clearDisplay();
if(allGroupsList && allGroupsList.length > 0){
jsonGroups()
return