| | | 1 | | |
| | | 2 | | |
| | | 3 | | using System.Collections; |
| | | 4 | | using System.Security.Claims; |
| | | 5 | | using Kestrun.SignalR; |
| | | 6 | | using Microsoft.AspNetCore.Authentication; |
| | | 7 | | using Microsoft.AspNetCore.Http.Features; |
| | | 8 | | |
| | | 9 | | namespace Kestrun.Models; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Represents the context for a Kestrun request, including the request, response, HTTP context, and host. |
| | | 13 | | /// </summary> |
| | | 14 | | public sealed record KestrunContext |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Initializes a new instance of the <see cref="KestrunContext"/> class. |
| | | 18 | | /// This constructor is used when creating a new KestrunContext from an existing HTTP context. |
| | | 19 | | /// It initializes the KestrunRequest and KestrunResponse based on the provided HttpContext |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="host">The Kestrun host.</param> |
| | | 22 | | /// <param name="request">The Kestrun request.</param> |
| | | 23 | | /// <param name="response">The Kestrun response.</param> |
| | | 24 | | /// <param name="httpContext">The associated HTTP context.</param> |
| | 48 | 25 | | public KestrunContext(Hosting.KestrunHost host, KestrunRequest request, KestrunResponse response, HttpContext httpCo |
| | | 26 | | { |
| | 48 | 27 | | ArgumentNullException.ThrowIfNull(host); |
| | 48 | 28 | | ArgumentNullException.ThrowIfNull(request); |
| | 48 | 29 | | ArgumentNullException.ThrowIfNull(response); |
| | 48 | 30 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | | 31 | | |
| | 48 | 32 | | Host = host; |
| | 48 | 33 | | Request = request; |
| | 48 | 34 | | Response = response; |
| | 48 | 35 | | HttpContext = httpContext; |
| | 48 | 36 | | } |
| | | 37 | | |
| | | 38 | | /// <summary> |
| | | 39 | | /// Initializes a new instance of the <see cref="KestrunContext"/> class. |
| | | 40 | | /// This constructor is used when creating a new KestrunContext from an existing HTTP context. |
| | | 41 | | /// It initializes the KestrunRequest and KestrunResponse based on the provided HttpContext |
| | | 42 | | /// </summary> |
| | | 43 | | /// <param name="host">The Kestrun host.</param> |
| | | 44 | | /// <param name="httpContext">The associated HTTP context.</param> |
| | 1 | 45 | | public KestrunContext(Hosting.KestrunHost host, HttpContext httpContext) |
| | | 46 | | { |
| | 1 | 47 | | ArgumentNullException.ThrowIfNull(host); |
| | 1 | 48 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | | 49 | | |
| | 1 | 50 | | Host = host; |
| | 1 | 51 | | HttpContext = httpContext; |
| | | 52 | | |
| | 1 | 53 | | Request = KestrunRequest.NewRequestSync(HttpContext); |
| | 1 | 54 | | Response = new KestrunResponse(Request); |
| | 1 | 55 | | } |
| | | 56 | | |
| | | 57 | | /// <summary> |
| | | 58 | | /// The Kestrun host associated with this context. |
| | | 59 | | /// </summary> |
| | 52 | 60 | | public Hosting.KestrunHost Host { get; init; } |
| | | 61 | | /// <summary> |
| | | 62 | | /// The Kestrun request associated with this context. |
| | | 63 | | /// </summary> |
| | 77 | 64 | | public KestrunRequest Request { get; init; } |
| | | 65 | | /// <summary> |
| | | 66 | | /// The Kestrun response associated with this context. |
| | | 67 | | /// </summary> |
| | 81 | 68 | | public KestrunResponse Response { get; init; } |
| | | 69 | | /// <summary> |
| | | 70 | | /// The ASP.NET Core HTTP context associated with this Kestrun context. |
| | | 71 | | /// </summary> |
| | 82 | 72 | | public HttpContext HttpContext { get; init; } |
| | | 73 | | /// <summary> |
| | | 74 | | /// Returns the ASP.NET Core session if the Session middleware is active; otherwise null. |
| | | 75 | | /// </summary> |
| | 14 | 76 | | public ISession? Session => HttpContext.Features.Get<ISessionFeature>()?.Session; |
| | | 77 | | |
| | | 78 | | /// <summary> |
| | | 79 | | /// True if Session middleware is active for this request. |
| | | 80 | | /// </summary> |
| | 4 | 81 | | public bool HasSession => Session is not null; |
| | | 82 | | |
| | | 83 | | /// <summary> |
| | | 84 | | /// Try pattern to get session without exceptions. |
| | | 85 | | /// </summary> |
| | | 86 | | public bool TryGetSession(out ISession? session) |
| | | 87 | | { |
| | 2 | 88 | | session = Session; |
| | 2 | 89 | | return session is not null; |
| | | 90 | | } |
| | | 91 | | |
| | | 92 | | /// <summary> |
| | | 93 | | /// Gets the cancellation token that is triggered when the HTTP request is aborted. |
| | | 94 | | /// </summary> |
| | 1 | 95 | | public CancellationToken Ct => HttpContext.RequestAborted; |
| | | 96 | | /// <summary> |
| | | 97 | | /// Gets the collection of key/value pairs associated with the current HTTP context. |
| | | 98 | | /// </summary> |
| | 3 | 99 | | public IDictionary<object, object?> Items => HttpContext.Items; |
| | | 100 | | |
| | | 101 | | /// <summary> |
| | | 102 | | /// Gets the user associated with the current HTTP context. |
| | | 103 | | /// </summary> |
| | 2 | 104 | | public ClaimsPrincipal User => HttpContext.User; |
| | | 105 | | |
| | | 106 | | /// <summary> |
| | | 107 | | /// Gets the connection information for the current HTTP context. |
| | | 108 | | /// </summary> |
| | 0 | 109 | | public ConnectionInfo Connection => HttpContext.Connection; |
| | | 110 | | |
| | | 111 | | /// <summary> |
| | | 112 | | /// Returns a string representation of the KestrunContext, including path, user, and session status. |
| | | 113 | | /// </summary> |
| | | 114 | | public override string ToString() |
| | 2 | 115 | | => $"KestrunContext{{ Host={Host}, Path={HttpContext.Request.Path}, User={User?.Identity?.Name ?? "<anon>"}, Has |
| | | 116 | | |
| | | 117 | | |
| | | 118 | | /// <summary> |
| | | 119 | | /// Asynchronously broadcasts a log message to all connected SignalR clients using the IRealtimeBroadcaster service. |
| | | 120 | | /// </summary> |
| | | 121 | | /// <param name="level">The log level (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 122 | | /// <param name="message">The log message to broadcast.</param> |
| | | 123 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 124 | | /// <returns>True if the log was broadcast successfully; otherwise, false.</returns> |
| | | 125 | | public async Task<bool> BroadcastLogAsync(string level, string message, CancellationToken cancellationToken = defaul |
| | | 126 | | { |
| | 0 | 127 | | var svcProvider = HttpContext.RequestServices; |
| | | 128 | | |
| | 0 | 129 | | if (svcProvider == null) |
| | | 130 | | { |
| | 0 | 131 | | Host.Logger.Warning("No service provider available to resolve IRealtimeBroadcaster."); |
| | 0 | 132 | | return false; |
| | | 133 | | } |
| | 0 | 134 | | if (svcProvider.GetService(typeof(IRealtimeBroadcaster)) is not IRealtimeBroadcaster broadcaster) |
| | | 135 | | { |
| | 0 | 136 | | Host.Logger.Warning("IRealtimeBroadcaster service is not registered. Make sure SignalR is configured with Ke |
| | 0 | 137 | | return false; |
| | | 138 | | } |
| | | 139 | | try |
| | | 140 | | { |
| | 0 | 141 | | await broadcaster.BroadcastLogAsync(level, message, cancellationToken); |
| | 0 | 142 | | Host.Logger.Debug("Broadcasted log message via SignalR: {Level} - {Message}", level, message); |
| | 0 | 143 | | return true; |
| | | 144 | | } |
| | 0 | 145 | | catch (Exception ex) |
| | | 146 | | { |
| | 0 | 147 | | Host.Logger.Error(ex, "Failed to broadcast log message: {Level} - {Message}", level, message); |
| | 0 | 148 | | return false; |
| | | 149 | | } |
| | 0 | 150 | | } |
| | | 151 | | |
| | | 152 | | /// <summary> |
| | | 153 | | /// Synchronous wrapper for BroadcastLogAsync. |
| | | 154 | | /// </summary> |
| | | 155 | | /// <param name="level">The log level (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 156 | | /// <param name="message">The log message to broadcast.</param> |
| | | 157 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 158 | | /// <returns>True if the log was broadcast successfully; otherwise, false.</returns> |
| | | 159 | | public bool BroadcastLog(string level, string message, CancellationToken cancellationToken = default) => |
| | 0 | 160 | | BroadcastLogAsync(level, message, cancellationToken).GetAwaiter().GetResult(); |
| | | 161 | | |
| | | 162 | | |
| | | 163 | | /// <summary> |
| | | 164 | | /// Asynchronously broadcasts a custom event to all connected SignalR clients using the IRealtimeBroadcaster service |
| | | 165 | | /// </summary> |
| | | 166 | | /// <param name="eventName">The event name (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 167 | | /// <param name="data">The event data to broadcast.</param> |
| | | 168 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 169 | | /// <returns>True if the event was broadcast successfully; otherwise, false.</returns> |
| | | 170 | | public async Task<bool> BroadcastEventAsync(string eventName, object? data, CancellationToken cancellationToken = de |
| | | 171 | | { |
| | 0 | 172 | | var svcProvider = HttpContext.RequestServices; |
| | | 173 | | |
| | 0 | 174 | | if (svcProvider == null) |
| | | 175 | | { |
| | 0 | 176 | | Host.Logger.Warning("No service provider available to resolve IRealtimeBroadcaster."); |
| | 0 | 177 | | return false; |
| | | 178 | | } |
| | 0 | 179 | | if (svcProvider.GetService(typeof(IRealtimeBroadcaster)) is not IRealtimeBroadcaster broadcaster) |
| | | 180 | | { |
| | 0 | 181 | | Host.Logger.Warning("IRealtimeBroadcaster service is not registered. Make sure SignalR is configured with Ke |
| | 0 | 182 | | return false; |
| | | 183 | | } |
| | | 184 | | try |
| | | 185 | | { |
| | 0 | 186 | | await broadcaster.BroadcastEventAsync(eventName, data, cancellationToken); |
| | 0 | 187 | | Host.Logger.Debug("Broadcasted event via SignalR: {EventName} - {Data}", eventName, data); |
| | 0 | 188 | | return true; |
| | | 189 | | } |
| | 0 | 190 | | catch (Exception ex) |
| | | 191 | | { |
| | 0 | 192 | | Host.Logger.Error(ex, "Failed to broadcast event: {EventName} - {Data}", eventName, data); |
| | 0 | 193 | | return false; |
| | | 194 | | } |
| | 0 | 195 | | } |
| | | 196 | | |
| | | 197 | | /// <summary> |
| | | 198 | | /// Synchronous wrapper for BroadcastEventAsync. |
| | | 199 | | /// </summary> |
| | | 200 | | /// <param name="eventName">The event name (e.g., Information, Warning, Error, Debug, Verbose).</param> |
| | | 201 | | /// <param name="data">The event data to broadcast.</param> |
| | | 202 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 203 | | /// <returns>True if the event was broadcast successfully; otherwise, false.</returns> |
| | | 204 | | public bool BroadcastEvent(string eventName, object? data, CancellationToken cancellationToken = default) => |
| | 0 | 205 | | BroadcastEventAsync(eventName, data, cancellationToken).GetAwaiter().GetResult(); |
| | | 206 | | |
| | | 207 | | |
| | | 208 | | /// <summary> |
| | | 209 | | /// Asynchronously broadcasts a message to a specific group of SignalR clients using the IRealtimeBroadcaster servic |
| | | 210 | | /// </summary> |
| | | 211 | | /// <param name="groupName">The name of the group to broadcast the message to.</param> |
| | | 212 | | /// <param name="method">The name of the method to invoke on the client.</param> |
| | | 213 | | /// <param name="message">The message to broadcast.</param> |
| | | 214 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 215 | | /// <returns></returns> |
| | | 216 | | public async Task<bool> BroadcastToGroupAsync(string groupName, string method, object? message, CancellationToken ca |
| | | 217 | | { |
| | 0 | 218 | | var svcProvider = HttpContext.RequestServices; |
| | | 219 | | |
| | 0 | 220 | | if (svcProvider == null) |
| | | 221 | | { |
| | 0 | 222 | | Host.Logger.Warning("No service provider available to resolve IRealtimeBroadcaster."); |
| | 0 | 223 | | return false; |
| | | 224 | | } |
| | 0 | 225 | | if (svcProvider.GetService(typeof(IRealtimeBroadcaster)) is not IRealtimeBroadcaster broadcaster) |
| | | 226 | | { |
| | 0 | 227 | | Host.Logger.Warning("IRealtimeBroadcaster service is not registered. Make sure SignalR is configured with Ke |
| | 0 | 228 | | return false; |
| | | 229 | | } |
| | | 230 | | try |
| | | 231 | | { |
| | 0 | 232 | | await broadcaster.BroadcastToGroupAsync(groupName, method, message, cancellationToken); |
| | 0 | 233 | | Host.Logger.Debug("Broadcasted log message to group via SignalR: {GroupName} - {Method} - {Message}", groupN |
| | 0 | 234 | | return true; |
| | | 235 | | } |
| | 0 | 236 | | catch (Exception ex) |
| | | 237 | | { |
| | 0 | 238 | | Host.Logger.Error(ex, "Failed to broadcast log message: {GroupName} - {Method} - {Message}", groupName, meth |
| | 0 | 239 | | return false; |
| | | 240 | | } |
| | 0 | 241 | | } |
| | | 242 | | |
| | | 243 | | /// <summary> |
| | | 244 | | /// Synchronous wrapper for BroadcastToGroupAsync. |
| | | 245 | | /// </summary> |
| | | 246 | | /// <param name="groupName">The name of the group to broadcast the message to.</param> |
| | | 247 | | /// <param name="method">The name of the method to invoke on the client.</param> |
| | | 248 | | /// <param name="message">The message to broadcast.</param> |
| | | 249 | | /// <param name="cancellationToken">Optional: Cancellation token.</param> |
| | | 250 | | /// <returns></returns> |
| | | 251 | | public bool BroadcastToGroup(string groupName, string method, object? message, CancellationToken cancellationToken = |
| | 0 | 252 | | BroadcastToGroupAsync(groupName, method, message, cancellationToken).GetAwaiter().GetResult(); |
| | | 253 | | |
| | | 254 | | /// <summary> |
| | | 255 | | /// Synchronous wrapper for HttpContext.ChallengeAsync. |
| | | 256 | | /// </summary> |
| | | 257 | | /// <param name="scheme">The authentication scheme to challenge.</param> |
| | | 258 | | /// <param name="properties">The authentication properties to include in the challenge.</param> |
| | 0 | 259 | | public void Challenge(string? scheme, AuthenticationProperties? properties) => HttpContext.ChallengeAsync(scheme, pr |
| | | 260 | | |
| | | 261 | | /// <summary> |
| | | 262 | | /// Synchronous wrapper for HttpContext.ChallengeAsync using a Hashtable for properties. |
| | | 263 | | /// </summary> |
| | | 264 | | /// <param name="scheme">The authentication scheme to challenge.</param> |
| | | 265 | | /// <param name="properties">The authentication properties to include in the challenge.</param> |
| | | 266 | | public void Challenge(string? scheme, Hashtable? properties) |
| | | 267 | | { |
| | 0 | 268 | | var dict = new Dictionary<string, string?>(); |
| | 0 | 269 | | if (properties != null) |
| | | 270 | | { |
| | 0 | 271 | | foreach (DictionaryEntry entry in properties) |
| | | 272 | | { |
| | 0 | 273 | | dict[entry.Key.ToString()!] = entry.Value?.ToString(); |
| | | 274 | | } |
| | | 275 | | } |
| | 0 | 276 | | AuthenticationProperties authProps = new(dict); |
| | 0 | 277 | | HttpContext.ChallengeAsync(scheme, authProps).GetAwaiter().GetResult(); |
| | 0 | 278 | | } |
| | | 279 | | |
| | | 280 | | /// <summary> |
| | | 281 | | /// Synchronous wrapper for HttpContext.ChallengeAsync using a Dictionary for properties. |
| | | 282 | | /// </summary> |
| | | 283 | | /// <param name="scheme">The authentication scheme to challenge.</param> |
| | | 284 | | /// <param name="properties">The authentication properties to include in the challenge.</param> |
| | | 285 | | public void Challenge(string? scheme, Dictionary<string, string?>? properties) |
| | | 286 | | { |
| | 0 | 287 | | if (properties == null) |
| | | 288 | | { |
| | 0 | 289 | | HttpContext.ChallengeAsync(scheme).GetAwaiter().GetResult(); |
| | 0 | 290 | | return; |
| | | 291 | | } |
| | | 292 | | |
| | 0 | 293 | | AuthenticationProperties authProps = new(properties); |
| | 0 | 294 | | HttpContext.ChallengeAsync(scheme, authProps).GetAwaiter().GetResult(); |
| | 0 | 295 | | } |
| | | 296 | | |
| | | 297 | | /// <summary> |
| | | 298 | | /// Asynchronous wrapper for HttpContext.ChallengeAsync using a Hashtable for properties. |
| | | 299 | | /// </summary> |
| | | 300 | | /// <param name="scheme">The authentication scheme to challenge.</param> |
| | | 301 | | /// <param name="properties">The authentication properties to include in the challenge.</param> |
| | | 302 | | /// <returns>Task representing the asynchronous operation.</returns> |
| | | 303 | | public Task ChallengeAsync(string? scheme, Hashtable? properties) |
| | | 304 | | { |
| | 0 | 305 | | var dict = new Dictionary<string, string?>(); |
| | 0 | 306 | | if (properties != null) |
| | | 307 | | { |
| | 0 | 308 | | foreach (DictionaryEntry entry in properties) |
| | | 309 | | { |
| | 0 | 310 | | dict[entry.Key.ToString()!] = entry.Value?.ToString(); |
| | | 311 | | } |
| | | 312 | | } |
| | 0 | 313 | | AuthenticationProperties authProps = new(dict); |
| | 0 | 314 | | return HttpContext.ChallengeAsync(scheme, authProps); |
| | | 315 | | } |
| | | 316 | | |
| | | 317 | | /// <summary> |
| | | 318 | | /// Synchronous wrapper for HttpContext.SignOutAsync. |
| | | 319 | | /// </summary> |
| | | 320 | | /// <param name="scheme">The authentication scheme to sign out.</param> |
| | 0 | 321 | | public void SignOut(string? scheme) => HttpContext.SignOutAsync(scheme).GetAwaiter().GetResult(); |
| | | 322 | | /// <summary> |
| | | 323 | | /// Synchronous wrapper for HttpContext.SignOutAsync. |
| | | 324 | | /// </summary> |
| | | 325 | | /// <param name="scheme">The authentication scheme to sign out.</param> |
| | | 326 | | /// <param name="properties">The authentication properties to include in the sign-out.</param> |
| | | 327 | | public void SignOut(string? scheme, AuthenticationProperties? properties) |
| | | 328 | | { |
| | 0 | 329 | | HttpContext.SignOutAsync(scheme, properties).GetAwaiter().GetResult(); |
| | 0 | 330 | | if (properties != null && !string.IsNullOrWhiteSpace(properties.RedirectUri)) |
| | | 331 | | { |
| | 0 | 332 | | Response.WriteStatusOnly(302); |
| | | 333 | | } |
| | 0 | 334 | | } |
| | | 335 | | |
| | | 336 | | /// <summary> |
| | | 337 | | /// Synchronous wrapper for HttpContext.SignOutAsync using a Hashtable for properties. |
| | | 338 | | /// </summary> |
| | | 339 | | /// <param name="scheme">The authentication scheme to sign out.</param> |
| | | 340 | | /// <param name="properties">The authentication properties to include in the sign-out.</param> |
| | | 341 | | public void SignOut(string? scheme, Hashtable? properties) |
| | | 342 | | { |
| | 0 | 343 | | AuthenticationProperties? authProps = null; |
| | | 344 | | // Convert Hashtable to Dictionary<string, string?> for AuthenticationProperties |
| | 0 | 345 | | if (properties is not null) |
| | | 346 | | { |
| | 0 | 347 | | var dict = new Dictionary<string, string?>(); |
| | | 348 | | // Convert each entry in the Hashtable to a string key-value pair |
| | 0 | 349 | | foreach (DictionaryEntry entry in properties) |
| | | 350 | | { |
| | 0 | 351 | | dict[entry.Key.ToString()!] = entry.Value?.ToString(); |
| | | 352 | | } |
| | | 353 | | // Create AuthenticationProperties from the dictionary |
| | 0 | 354 | | authProps = new AuthenticationProperties(dict); |
| | | 355 | | } |
| | | 356 | | // Call SignOut with the constructed AuthenticationProperties |
| | 0 | 357 | | SignOut(scheme, authProps); |
| | 0 | 358 | | } |
| | | 359 | | } |