refine request path middleware

This commit is contained in:
Jicheng Lu 2024-05-06 02:37:58 -05:00
parent 67aa9ed0ae
commit 78fcda634b
2 changed files with 10 additions and 11 deletions

View file

@ -326,23 +326,20 @@ public class ConversationController : ControllerBase
return attachment.GetConversationFiles(conversationId, messageId);
}
[AllowAnonymous]
[HttpGet("/conversation/{conversationId}/message/{messageId}/file/{fileName}/type/{type}")]
public async Task<IActionResult> GetMessageFile([FromRoute] string conversationId, [FromRoute] string messageId,
[FromRoute] string fileName, [FromRoute] string type)
{
var attachment = _services.GetRequiredService<IBotSharpFileService>();
var file = attachment.GetMessageFile(conversationId, messageId, fileName, type);
if (!string.IsNullOrEmpty(file))
{
using Stream stream = System.IO.File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
return File(bytes, "application/octet-stream", Path.GetFileName(file));
}
else
if (string.IsNullOrEmpty(file))
{
return NotFound();
}
using Stream stream = System.IO.File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
return File(bytes, "application/octet-stream", Path.GetFileName(file));
}
}

View file

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Http;
using System.Text.RegularExpressions;
namespace BotSharp.Plugin.ChatHub;
@ -13,11 +14,12 @@ public class WebSocketsMiddleware
public async Task Invoke(HttpContext httpContext)
{
var request = httpContext.Request;
var request = httpContext.Request;;
var messageFileRegex = new Regex(@"/conversation/[a-z0-9_.-]+/message/[a-z0-9_.-]+/file/[a-z0-9_.-]+/type/[a-z0-9_.-]+", RegexOptions.IgnoreCase);
// 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
if (request.Path.StartsWithSegments("/chatHub", StringComparison.OrdinalIgnoreCase) &&
if ((request.Path.StartsWithSegments("/chatHub", StringComparison.OrdinalIgnoreCase) || messageFileRegex.IsMatch(request.Path.Value ?? string.Empty)) &&
request.Query.TryGetValue("access_token", out var accessToken))
{
request.Headers["Authorization"] = $"Bearer {accessToken}";