2023-11-28 03:19:07 +00:00
|
|
|
using Microsoft.AspNetCore.Http;
|
2024-05-06 07:37:58 +00:00
|
|
|
using System.Text.RegularExpressions;
|
2023-11-28 03:19:07 +00:00
|
|
|
|
|
|
|
|
namespace BotSharp.Plugin.ChatHub;
|
|
|
|
|
|
|
|
|
|
public class WebSocketsMiddleware
|
|
|
|
|
{
|
|
|
|
|
private readonly RequestDelegate _next;
|
|
|
|
|
|
|
|
|
|
public WebSocketsMiddleware(RequestDelegate next)
|
|
|
|
|
{
|
|
|
|
|
_next = next;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task Invoke(HttpContext httpContext)
|
|
|
|
|
{
|
2024-05-22 04:33:31 +00:00
|
|
|
var request = httpContext.Request;
|
2023-11-28 03:19:07 +00:00
|
|
|
|
|
|
|
|
// web sockets cannot pass headers so we must take the access token from query param and
|
|
|
|
|
// add it to the header before authentication middleware runs
|
2024-05-22 04:33:31 +00:00
|
|
|
if ((VerifyChatHubRequest(request) || VerifyGetRequest(request)) &&
|
2023-11-28 03:19:07 +00:00
|
|
|
request.Query.TryGetValue("access_token", out var accessToken))
|
|
|
|
|
{
|
2024-02-14 23:45:28 +00:00
|
|
|
request.Headers["Authorization"] = $"Bearer {accessToken}";
|
2023-11-28 03:19:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await _next(httpContext);
|
|
|
|
|
}
|
2024-05-22 04:33:31 +00:00
|
|
|
|
|
|
|
|
private bool VerifyChatHubRequest(HttpRequest request)
|
|
|
|
|
{
|
|
|
|
|
return request.Path.StartsWithSegments("/chatHub", StringComparison.OrdinalIgnoreCase);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private bool VerifyGetRequest(HttpRequest request)
|
|
|
|
|
{
|
|
|
|
|
var regexes = new List<Regex>
|
|
|
|
|
{
|
|
|
|
|
new Regex(@"/conversation/[a-z0-9-]+/message/[a-z0-9-]+/file/[a-z0-9-]+", RegexOptions.IgnoreCase),
|
|
|
|
|
new Regex(@"/user/avatar", RegexOptions.IgnoreCase)
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return request.Method.IsEqualTo("GET") && regexes.Any(x => x.IsMatch(request.Path.Value ?? string.Empty));
|
|
|
|
|
}
|
2023-11-28 03:19:07 +00:00
|
|
|
}
|