-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
434 lines (380 loc) · 14.1 KB
/
Program.cs
File metadata and controls
434 lines (380 loc) · 14.1 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
// 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();
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;
}
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));
app.MapMethods("/ExecProc", new[] { "GET", "POST" }, async (HttpContext context, IConfiguration config) =>
{
var req = context.Request;
// SCALE may send the acting user in a header or within the UserInformation cookie.
var rawUsername = req.Headers["Username"].FirstOrDefault()
?? req.Headers["UserName"].FirstOrDefault()
?? TryGetUsernameFromUserInformationCookie(req)
?? context.User.Identity?.Name
?? "Anonymous";
// Keep the short username behavior for auditing and stored procedure compatibility.
var windowsIdentity = rawUsername.Contains('\\')
? rawUsername.Split('\\').Last()
: rawUsername.Contains('@')
? rawUsername.Split('@').First()
: rawUsername;
// Get 'action' from query string
var action = req.Query["action"].ToString();
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 = rawUsername,
AuditUser = windowsIdentity,
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", windowsIdentity); // Windows authenticated 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();