-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
895 lines (792 loc) · 29.7 KB
/
Program.cs
File metadata and controls
895 lines (792 loc) · 29.7 KB
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
// Program.cs (ASP.NET Core 8/9 Minimal API)
using Microsoft.Data.SqlClient;
using System.Data;
using System.Net;
using System.Security.Principal;
var builder = WebApplication.CreateBuilder(args);
// Enforce HTTPS and HSTS
builder.Services.AddHsts(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(60);
});
var app = builder.Build();
var requestDiagnosticsLogger = app.Services.GetRequiredService<ILoggerFactory>()
.CreateLogger("ScaleUserAction.RequestDiagnostics");
app.UseHsts();
app.UseHttpsRedirection();
// Global exception handler middleware (production safe)
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
// Log the error (replace with your logging framework as needed)
app.Logger.LogError(ex, "Unhandled exception");
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
var errorJson = System.Text.Json.JsonSerializer.Serialize(new
{
error = "An unexpected error occurred."
});
await context.Response.WriteAsync(errorJson);
}
});
static string? TryGetUsernameFromUserInformationCookie(HttpRequest request)
{
if (request.Cookies.TryGetValue("UserInformation", out var userInformationCookie))
{
var cookieUsername = TryParseUsernameFromCookieValue(userInformationCookie);
if (!string.IsNullOrWhiteSpace(cookieUsername))
return cookieUsername;
}
return TryGetUsernameFromCookieHeader(request.Headers.Cookie);
}
static string? TryGetUsernameFromCookieHeader(IEnumerable<string> cookieHeaders)
{
foreach (var cookieHeader in cookieHeaders)
{
if (string.IsNullOrWhiteSpace(cookieHeader))
continue;
foreach (var cookiePart in cookieHeader.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
{
var separatorIndex = cookiePart.IndexOf('=');
if (separatorIndex <= 0)
continue;
var cookieName = cookiePart[..separatorIndex];
if (!cookieName.Equals("UserInformation", StringComparison.OrdinalIgnoreCase))
continue;
var cookieValue = cookiePart[(separatorIndex + 1)..];
var cookieUsername = TryParseUsernameFromCookieValue(cookieValue);
if (!string.IsNullOrWhiteSpace(cookieUsername))
return cookieUsername;
}
}
return null;
}
static string? TryParseUsernameFromCookieValue(string? cookieValue)
{
if (string.IsNullOrWhiteSpace(cookieValue))
return null;
var decodedCookieValue = WebUtility.UrlDecode(cookieValue);
foreach (var part in decodedCookieValue.Split('&', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
{
var separatorIndex = part.IndexOf('=');
if (separatorIndex <= 0)
continue;
var key = part[..separatorIndex];
if (!key.Equals("UserName", StringComparison.OrdinalIgnoreCase))
continue;
var value = separatorIndex == part.Length - 1 ? string.Empty : part[(separatorIndex + 1)..];
return string.IsNullOrWhiteSpace(value) ? null : WebUtility.UrlDecode(value);
}
return null;
}
static (string? Username, string? ClaimSource, string ClaimNames, string CandidateClaims) TryParseUsernameFromAuthorizationHeaderValue(string? authorizationHeader)
{
var claims = TryParseJwtClaimsFromAuthorizationHeaderValue(authorizationHeader);
if (claims == null || claims.Count == 0)
return (null, null, string.Empty, string.Empty);
var username = TryResolveUsernameFromJwtClaims(claims, out var claimSource);
var claimNames = string.Join(", ", claims.Keys.OrderBy(key => key, StringComparer.OrdinalIgnoreCase));
var candidateClaims = string.Join(", ", GetJwtIdentityClaimPairs(claims));
return (username, claimSource, claimNames, candidateClaims);
}
static Dictionary<string, string?>? TryParseJwtClaimsFromAuthorizationHeaderValue(string? authorizationHeader)
{
const string bearerPrefix = "Bearer ";
if (string.IsNullOrWhiteSpace(authorizationHeader)
|| !authorizationHeader.StartsWith(bearerPrefix, StringComparison.OrdinalIgnoreCase))
{
return null;
}
var token = authorizationHeader[bearerPrefix.Length..].Trim();
if (string.IsNullOrWhiteSpace(token))
return null;
var tokenParts = token.Split('.');
if (tokenParts.Length < 2)
return null;
try
{
var payloadJson = DecodeJwtPayload(tokenParts[1]);
using var document = System.Text.Json.JsonDocument.Parse(payloadJson);
if (document.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object)
return null;
var claims = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
foreach (var property in document.RootElement.EnumerateObject())
{
claims[property.Name] = property.Value.ValueKind switch
{
System.Text.Json.JsonValueKind.String => property.Value.GetString(),
System.Text.Json.JsonValueKind.Number => property.Value.ToString(),
System.Text.Json.JsonValueKind.True => bool.TrueString,
System.Text.Json.JsonValueKind.False => bool.FalseString,
_ => null
};
}
return claims;
}
catch
{
return null;
}
}
static string? TryResolveUsernameFromJwtClaims(IReadOnlyDictionary<string, string?> claims, out string? claimSource)
{
foreach (var candidateClaim in new[]
{
"preferred_username",
"unique_name",
"upn",
"username",
"user_name",
"userid",
"email",
"name",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
})
{
if (!claims.TryGetValue(candidateClaim, out var claimValue)
|| string.IsNullOrWhiteSpace(claimValue))
{
continue;
}
claimSource = candidateClaim;
return claimValue;
}
if (claims.TryGetValue("sub", out var subject)
&& !string.IsNullOrWhiteSpace(subject)
&& !Guid.TryParse(subject, out _))
{
claimSource = "sub";
return subject;
}
claimSource = null;
return null;
}
static IEnumerable<string> GetJwtIdentityClaimPairs(IReadOnlyDictionary<string, string?> claims)
{
foreach (var candidateClaim in new[]
{
"preferred_username",
"unique_name",
"upn",
"username",
"user_name",
"userid",
"email",
"name",
"sub",
"oid",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
})
{
if (!claims.TryGetValue(candidateClaim, out var claimValue)
|| string.IsNullOrWhiteSpace(claimValue))
{
continue;
}
yield return $"{candidateClaim}={claimValue}";
}
}
static string DecodeJwtPayload(string payload)
{
var base64 = payload.Replace('-', '+').Replace('_', '/');
var remainder = base64.Length % 4;
if (remainder != 0)
base64 = base64.PadRight(base64.Length + (4 - remainder), '=');
var bytes = Convert.FromBase64String(base64);
return System.Text.Encoding.UTF8.GetString(bytes);
}
static string? TryGetAuthorizationScheme(string? authorizationHeader)
{
if (string.IsNullOrWhiteSpace(authorizationHeader))
return null;
var separatorIndex = authorizationHeader.IndexOf(' ');
return separatorIndex <= 0
? authorizationHeader.Trim()
: authorizationHeader[..separatorIndex].Trim();
}
static (string? HeaderUsername,
string? CookieUsername,
string? BearerUsername,
string? BearerUsernameClaim,
string? BearerClaimNames,
string? BearerCandidateClaims,
string SourceUsername,
string ResolvedUsername,
string AuditUser) ResolveRequestUserInfo(HttpContext context)
{
var request = context.Request;
var headerUsername = request.Headers["Username"].FirstOrDefault();
var cookieUsername = TryGetUsernameFromUserInformationCookie(request);
var authorizationUserInfo = TryParseUsernameFromAuthorizationHeaderValue(request.Headers.Authorization.FirstOrDefault());
var bearerUsername = authorizationUserInfo.Username;
var sourceUsername = headerUsername
?? bearerUsername
?? cookieUsername
?? context.User.Identity?.Name
?? "Anonymous";
var auditUser = sourceUsername.Contains('\\')
? sourceUsername.Split('\\').Last()
: sourceUsername.Contains('@')
? sourceUsername.Split('@').First()
: sourceUsername;
return (
headerUsername,
cookieUsername,
bearerUsername,
authorizationUserInfo.ClaimSource,
authorizationUserInfo.ClaimNames,
authorizationUserInfo.CandidateClaims,
sourceUsername,
auditUser,
auditUser);
}
static IReadOnlyList<string> GetArchivedPdfAllowedRoots(IConfiguration config)
{
var roots = config.GetSection("ArchivedPdfPreview:AllowedRoots")
.GetChildren()
.Select(section => section.Value)
.Where(value => !string.IsNullOrWhiteSpace(value))
.Select(value => NormalizeDirectoryPath(value!))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
var singleRoot = config["ArchivedPdfPreview:AllowedRoot"];
if (!string.IsNullOrWhiteSpace(singleRoot))
{
roots.Add(NormalizeDirectoryPath(singleRoot));
}
return roots
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
}
static string NormalizeDirectoryPath(string path)
{
return Path.GetFullPath(path.Trim())
.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
static bool IsPathWithinRoot(string fullFilePath, string normalizedRoot)
{
if (string.Equals(fullFilePath, normalizedRoot, StringComparison.OrdinalIgnoreCase))
return true;
var rootWithSeparator = normalizedRoot + Path.DirectorySeparatorChar;
return fullFilePath.StartsWith(rootWithSeparator, StringComparison.OrdinalIgnoreCase);
}
static void LogArchivedPdfPreviewRequestDiagnostics(
ILogger logger,
HttpContext context,
string? requestedFilePath,
IReadOnlyList<string> allowedRoots,
bool pathValidated,
string sourceUsername,
string resolvedUsername,
string auditUser)
{
var request = context.Request;
logger.LogInformation(
"ArchivedPdfPreview request diagnostics: Method={Method}; Path={Path}; QueryKeys={QueryKeys}; RemoteIp={RemoteIp}; RequestedFilePath={RequestedFilePath}; RequestedFileName={RequestedFileName}; AllowedRootCount={AllowedRootCount}; PathValidated={PathValidated}; SourceUser={SourceUser}; ResolvedUser={ResolvedUser}; AuditUser={AuditUser}",
request.Method,
request.Path.Value,
string.Join(", ", request.Query.Keys.OrderBy(key => key, StringComparer.OrdinalIgnoreCase)),
context.Connection.RemoteIpAddress?.ToString(),
requestedFilePath,
string.IsNullOrWhiteSpace(requestedFilePath) ? null : Path.GetFileName(requestedFilePath),
allowedRoots.Count,
pathValidated,
sourceUsername,
resolvedUsername,
auditUser);
if (string.Equals(resolvedUsername, "Anonymous", StringComparison.OrdinalIgnoreCase))
{
logger.LogWarning(
"ArchivedPdfPreview request resolved to Anonymous. None of Username header, UserInformation cookie, supported bearer token identity claims, or HttpContext user identity produced a user.");
}
}
static void LogExecProcRequestDiagnostics(
ILogger logger,
HttpContext context,
string? action,
string? headerUsername,
string? cookieUsername,
string? bearerUsername,
string? bearerUsernameClaim,
string? bearerClaimNames,
string? bearerCandidateClaims,
string sourceUsername,
string resolvedUsername,
string auditUser)
{
var req = context.Request;
var authorizationHeader = req.Headers.Authorization.FirstOrDefault();
var hasUserInformationCookie = req.Cookies.ContainsKey("UserInformation")
|| req.Headers.Cookie.Any(cookieHeader => !string.IsNullOrWhiteSpace(cookieHeader)
&& cookieHeader.Contains("UserInformation=", StringComparison.OrdinalIgnoreCase));
logger.LogInformation(
"ExecProc request diagnostics: Action={Action}; Method={Method}; Path={Path}; QueryKeys={QueryKeys}; ContentType={ContentType}; ContentLength={ContentLength}; RemoteIp={RemoteIp}; HeaderNames={HeaderNames}; UsernameHeader={UsernameHeader}; HasUserInformationCookie={HasUserInformationCookie}; CookieUsername={CookieUsername}; HasAuthorizationHeader={HasAuthorizationHeader}; AuthorizationScheme={AuthorizationScheme}; BearerUsername={BearerUsername}; BearerUsernameClaim={BearerUsernameClaim}; BearerClaimNames={BearerClaimNames}; BearerCandidateClaims={BearerCandidateClaims}; IsAuthenticated={IsAuthenticated}; IdentityName={IdentityName}; SourceUser={SourceUser}; ResolvedUser={ResolvedUser}; AuditUser={AuditUser}",
string.IsNullOrWhiteSpace(action) ? "<missing>" : action,
req.Method,
req.Path.Value,
string.Join(", ", req.Query.Keys.OrderBy(key => key, StringComparer.OrdinalIgnoreCase)),
req.ContentType,
req.ContentLength,
context.Connection.RemoteIpAddress?.ToString(),
string.Join(", ", req.Headers.Keys.OrderBy(key => key, StringComparer.OrdinalIgnoreCase)),
headerUsername,
hasUserInformationCookie,
cookieUsername,
!string.IsNullOrWhiteSpace(authorizationHeader),
TryGetAuthorizationScheme(authorizationHeader),
bearerUsername,
bearerUsernameClaim,
bearerClaimNames,
bearerCandidateClaims,
context.User.Identity?.IsAuthenticated ?? false,
context.User.Identity?.Name,
sourceUsername,
resolvedUsername,
auditUser);
if (string.Equals(resolvedUsername, "Anonymous", StringComparison.OrdinalIgnoreCase))
{
logger.LogWarning(
"ExecProc request resolved to Anonymous. None of Username header, UserInformation cookie, supported bearer token identity claims, or HttpContext user identity produced a user.");
}
}
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));
app.MapGet("/ArchivedPdfPreview", (HttpContext context, IConfiguration config) =>
{
var userInfo = ResolveRequestUserInfo(context);
var request = context.Request;
var requestedFilePath = request.Query["filePath"].ToString();
var allowedRoots = GetArchivedPdfAllowedRoots(config);
if (string.IsNullOrWhiteSpace(requestedFilePath))
{
LogArchivedPdfPreviewRequestDiagnostics(
requestDiagnosticsLogger,
context,
requestedFilePath,
allowedRoots,
false,
userInfo.SourceUsername,
userInfo.ResolvedUsername,
userInfo.AuditUser);
return Results.BadRequest(new
{
ErrorCode = "MissingFilePath",
ErrorType = 1,
Message = "Missing required query parameter 'filePath'.",
AdditionalErrors = Array.Empty<string>(),
Data = (object?)null
});
}
if (allowedRoots.Count == 0)
{
LogArchivedPdfPreviewRequestDiagnostics(
requestDiagnosticsLogger,
context,
requestedFilePath,
allowedRoots,
false,
userInfo.SourceUsername,
userInfo.ResolvedUsername,
userInfo.AuditUser);
return Results.Json(new
{
ErrorCode = "MissingPreviewRoots",
ErrorType = 1,
Message = "Archived PDF preview is not configured. No allowed roots are defined.",
AdditionalErrors = Array.Empty<string>(),
Data = (object?)null
}, statusCode: 500);
}
string fullFilePath;
try
{
fullFilePath = Path.GetFullPath(requestedFilePath.Trim());
}
catch (Exception ex)
{
LogArchivedPdfPreviewRequestDiagnostics(
requestDiagnosticsLogger,
context,
requestedFilePath,
allowedRoots,
false,
userInfo.SourceUsername,
userInfo.ResolvedUsername,
userInfo.AuditUser);
return Results.BadRequest(new
{
ErrorCode = "InvalidFilePath",
ErrorType = 1,
Message = "The requested file path is invalid.",
AdditionalErrors = new[] { ex.Message },
Data = (object?)null
});
}
if (!string.Equals(Path.GetExtension(fullFilePath), ".pdf", StringComparison.OrdinalIgnoreCase))
{
LogArchivedPdfPreviewRequestDiagnostics(
requestDiagnosticsLogger,
context,
requestedFilePath,
allowedRoots,
false,
userInfo.SourceUsername,
userInfo.ResolvedUsername,
userInfo.AuditUser);
return Results.BadRequest(new
{
ErrorCode = "InvalidFileType",
ErrorType = 1,
Message = "Only PDF files can be previewed.",
AdditionalErrors = Array.Empty<string>(),
Data = (object?)null
});
}
var pathValidated = allowedRoots.Any(root => IsPathWithinRoot(fullFilePath, root));
LogArchivedPdfPreviewRequestDiagnostics(
requestDiagnosticsLogger,
context,
requestedFilePath,
allowedRoots,
pathValidated,
userInfo.SourceUsername,
userInfo.ResolvedUsername,
userInfo.AuditUser);
if (!pathValidated)
{
return Results.BadRequest(new
{
ErrorCode = "PathNotAllowed",
ErrorType = 1,
Message = "The requested PDF is outside the configured preview roots.",
AdditionalErrors = Array.Empty<string>(),
Data = (object?)null
});
}
if (!File.Exists(fullFilePath))
{
return Results.NotFound(new
{
ErrorCode = "FileNotFound",
ErrorType = 1,
Message = "The requested PDF could not be found.",
AdditionalErrors = Array.Empty<string>(),
Data = (object?)null
});
}
var fileName = Path.GetFileName(fullFilePath);
context.Response.Headers.ContentDisposition = $"inline; filename=\"{fileName}\"; filename*=UTF-8''{Uri.EscapeDataString(fileName)}";
return Results.File(
fullFilePath,
contentType: "application/pdf",
enableRangeProcessing: true,
lastModified: File.GetLastWriteTimeUtc(fullFilePath));
});
app.MapMethods("/ExecProc", new[] { "GET", "POST" }, async (HttpContext context, IConfiguration config) =>
{
var req = context.Request;
var userInfo = ResolveRequestUserInfo(context);
// Get 'action' from query string
var action = req.Query["action"].ToString();
LogExecProcRequestDiagnostics(
requestDiagnosticsLogger,
context,
action,
userInfo.HeaderUsername,
userInfo.CookieUsername,
userInfo.BearerUsername,
userInfo.BearerUsernameClaim,
userInfo.BearerClaimNames,
userInfo.BearerCandidateClaims,
userInfo.SourceUsername,
userInfo.ResolvedUsername,
userInfo.AuditUser);
if (string.IsNullOrWhiteSpace(action))
{
return Results.BadRequest(new
{
ErrorCode = "MissingAction",
ErrorType = 1,
Message = "Missing required query parameter 'action'.",
AdditionalErrors = Array.Empty<string>(),
Data = (object?)null
});
}
List<Dictionary<string, object>> items = [];
if (HttpMethods.IsGet(req.Method))
{
items.Add(new Dictionary<string, object>
{
["internalID"] = req.Query["internalID"].ToString(),
["changeValue"] = req.Query["changeValue"].ToString()
});
}
else
{
// Limit request body size (e.g., 10 KB)
if (req.ContentLength is > 10_240)
{
return Results.BadRequest(new
{
ErrorCode = "PayloadTooLarge",
ErrorType = 1,
Message = "Request payload too large.",
AdditionalErrors = Array.Empty<string>(),
Data = (object?)null
});
}
using var reader = new StreamReader(req.Body);
var raw = await reader.ReadToEndAsync();
try
{
items = System.Text.Json.JsonSerializer.Deserialize<List<Dictionary<string, object>>>(raw)
?? [];
}
catch
{
try
{
var obj = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(raw);
if (obj != null)
items.Add(obj);
}
catch
{
return Results.BadRequest(new
{
ErrorCode = "InvalidPayload",
ErrorType = 1,
Message = "Invalid payload.",
AdditionalErrors = Array.Empty<string>(),
Data = (object?)null
});
}
}
}
if (items.Count == 0)
{
return Results.BadRequest(new
{
ErrorCode = "InvalidPayload",
ErrorType = 1,
Message = "Invalid payload.",
AdditionalErrors = Array.Empty<string>(),
Data = (object?)null
});
}
var connStr = config.GetConnectionString("DefaultConnection");
if (string.IsNullOrWhiteSpace(connStr))
{
return Results.Json(new
{
ErrorCode = "MissingConnectionString",
ErrorType = 1,
Message = "Connection string not configured.",
AdditionalErrors = Array.Empty<string>(),
Data = (object?)null
}, statusCode: 500);
}
await using var conn = new SqlConnection(connStr);
try
{
await conn.OpenAsync();
}
catch (Exception ex)
{
var csb = new SqlConnectionStringBuilder(connStr);
var processIdentity = OperatingSystem.IsWindows()
? WindowsIdentity.GetCurrent()?.Name ?? "Unknown"
: "Non-Windows";
return Results.Json(new
{
ErrorCode = "DatabaseConnectionFailed",
ErrorType = 1,
Message = "Database connection failed.",
AdditionalErrors = new[]
{
ex.Message
},
Data = new
{
RequestUser = userInfo.ResolvedUsername,
SourceUser = userInfo.SourceUsername,
AuditUser = userInfo.AuditUser,
ProcessIdentity = processIdentity,
SqlServer = csb.DataSource,
Database = csb.InitialCatalog,
IntegratedSecurity = csb.IntegratedSecurity,
SqlUser = string.IsNullOrWhiteSpace(csb.UserID) ? "<none>" : csb.UserID
}
}, statusCode: 500);
}
// Verify all items have required fields first
foreach (var item in items)
{
if (!item.TryGetValue("internalID", out var _) || !item.TryGetValue("changeValue", out var _))
{
return Results.BadRequest(new Dictionary<string, object?>
{
["ErrorCode"] = "MissingParams",
["ErrorType"] = 1,
["Message"] = "Missing required params 'internalID' and/or 'changeValue'.",
["AdditionalErrors"] = Array.Empty<string>(),
["Data"] = null
});
}
}
// Build comma-separated list of internal IDs (for single or multiple items)
var internalIDs = string.Join(",", items.Select(item =>
{
var id = item["internalID"];
if (id is System.Text.Json.JsonElement je && je.ValueKind == System.Text.Json.JsonValueKind.Number)
return je.GetInt32().ToString();
if (id is System.Text.Json.JsonElement jes && jes.ValueKind == System.Text.Json.JsonValueKind.String)
return jes.GetString() ?? "";
return id?.ToString() ?? "";
}));
// Use first item's changeValue (all rows share same value)
var changeValueRaw = items[0]["changeValue"];
object? changeValueObj = changeValueRaw is System.Text.Json.JsonElement jeCV && jeCV.ValueKind == System.Text.Json.JsonValueKind.Number
? jeCV.GetInt32()
: changeValueRaw is System.Text.Json.JsonElement jeCVs && jeCVs.ValueKind == System.Text.Json.JsonValueKind.String
? jeCVs.GetString()
: changeValueRaw;
// Call stored procedure ONCE with comma-separated IDs and Windows username
await using var cmd = new SqlCommand("usp_UserAction", conn) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.AddWithValue("@action", action ?? (object)DBNull.Value);
cmd.Parameters.AddWithValue("@internalID", internalIDs); // CSV list
cmd.Parameters.AddWithValue("@changeValue", changeValueObj ?? DBNull.Value);
cmd.Parameters.AddWithValue("@userName", userInfo.AuditUser); // user
// Preserve both standard MessageCode/Message responses and arbitrary result sets.
var successMessages = new List<string>();
var errorMessages = new List<string>();
string? finalCode = null;
Dictionary<string, object?>? firstRow = null;
var arbitraryRows = new List<Dictionary<string, object?>>();
var hasMessageColumns = false;
try
{
await using var procReader = await cmd.ExecuteReaderAsync();
var columnNames = Enumerable.Range(0, procReader.FieldCount)
.Select(procReader.GetName)
.ToList();
hasMessageColumns = columnNames.Contains("MessageCode", StringComparer.OrdinalIgnoreCase)
&& columnNames.Contains("Message", StringComparer.OrdinalIgnoreCase);
while (await procReader.ReadAsync())
{
var row = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
for (var index = 0; index < procReader.FieldCount; index++)
{
var value = procReader.IsDBNull(index) ? null : procReader.GetValue(index);
row[procReader.GetName(index)] = value;
}
firstRow ??= row;
if (hasMessageColumns)
{
var messageCode = row.TryGetValue("MessageCode", out var codeObj) ? codeObj?.ToString() ?? string.Empty : string.Empty;
var message = row.TryGetValue("Message", out var messageObj) ? messageObj?.ToString() ?? string.Empty : string.Empty;
if (messageCode.StartsWith("ERR_", StringComparison.OrdinalIgnoreCase))
{
errorMessages.Add(message);
finalCode ??= messageCode;
}
else
{
successMessages.Add(message);
finalCode ??= messageCode;
}
}
else
{
arbitraryRows.Add(row);
}
}
procReader.Close();
}
catch (Exception ex)
{
return Results.BadRequest(new Dictionary<string, object?>
{
["ErrorCode"] = "SqlError",
["ErrorType"] = 1,
["Message"] = ex.Message,
["AdditionalErrors"] = new[] { ex.ToString() },
["Data"] = new Dictionary<string, object?>
{
["action"] = action,
["internalID"] = internalIDs,
["changeValue"] = changeValueObj
}
});
}
// If no results returned, return error
if (firstRow == null)
{
return Results.BadRequest(new Dictionary<string, object?>
{
["ErrorCode"] = "NoResults",
["ErrorType"] = 1,
["Message"] = "Stored procedure returned no results.",
["AdditionalErrors"] = Array.Empty<string>(),
["Data"] = null
});
}
if (!hasMessageColumns)
{
if (arbitraryRows.Count == 1)
return Results.Ok(arbitraryRows[0]);
return Results.Ok(arbitraryRows);
}
if (finalCode == null)
{
return Results.BadRequest(new Dictionary<string, object?>
{
["ErrorCode"] = "NoResults",
["ErrorType"] = 1,
["Message"] = "Stored procedure returned no results.",
["AdditionalErrors"] = Array.Empty<string>(),
["Data"] = null
});
}
// Combine all messages into a single message
var combinedMessage = string.Join(" ", successMessages.Concat(errorMessages));
// If there are any errors, return BadRequest
if (errorMessages.Count > 0)
{
return Results.BadRequest(new Dictionary<string, object?>
{
["ErrorCode"] = finalCode,
["ErrorType"] = 1,
["Message"] = combinedMessage,
["AdditionalErrors"] = Array.Empty<string>(),
["Data"] = null
});
}
// All success - return OK
var response = new Dictionary<string, object?>
{
["ConfirmationMessageCode"] = null,
["ConfirmationMessage"] = null,
["MessageCode"] = finalCode,
["Message"] = combinedMessage
};
foreach (var entry in firstRow)
{
if (!response.ContainsKey(entry.Key))
response[entry.Key] = entry.Value;
}
return Results.Ok(response);
});
app.Run();