Rename folder from Shogi.Sockets to Shogi.Api

This commit is contained in:
2022-11-09 09:11:25 -06:00
parent 3257b420e9
commit a1f996e508
41 changed files with 6 additions and 6 deletions

View File

@@ -0,0 +1,30 @@
using System.Security.Claims;
namespace Shogi.Api.Extensions;
public static class Extensions
{
private static readonly string MsalUsernameClaim = "preferred_username";
public static string? GetGuestUserId(this ClaimsPrincipal self)
{
return self.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
}
public static string? DisplayName(this ClaimsPrincipal self)
{
return self.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
}
public static bool IsMicrosoft(this ClaimsPrincipal self)
{
return self.HasClaim(c => c.Type == MsalUsernameClaim);
}
public static string? GetMicrosoftUserId(this ClaimsPrincipal self)
{
return self.Claims.FirstOrDefault(c => c.Type == MsalUsernameClaim)?.Value;
}
public static string? GetShogiUserId(this ClaimsPrincipal self) => self.IsMicrosoft() ? self.GetMicrosoftUserId() : self.GetGuestUserId();
}

View File

@@ -0,0 +1,50 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Shogi.Api.Extensions
{
public class LogMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger logger;
public LogMiddleware(RequestDelegate next, ILoggerFactory factory)
{
this.next = next;
logger = factory.CreateLogger<LogMiddleware>();
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
finally
{
using var stream = new MemoryStream();
context.Request?.Body.CopyToAsync(stream);
logger.LogInformation("Request {method} {url} => {statusCode} \n Body: {body}",
context.Request?.Method,
context.Request?.Path.Value,
context.Response?.StatusCode,
Encoding.UTF8.GetString(stream.ToArray()));
}
}
}
public static class IApplicationBuilderExtensions
{
public static IApplicationBuilder UseRequestResponseLogging(this IApplicationBuilder builder)
{
builder.UseMiddleware<LogMiddleware>();
return builder;
}
}
}

View File

@@ -0,0 +1,21 @@
using System.Net.WebSockets;
using System.Text;
namespace Shogi.Api.Extensions
{
public static class WebSocketExtensions
{
public static async Task SendTextAsync(this WebSocket self, string message)
{
await self.SendAsync(Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text, true, CancellationToken.None);
}
public static async Task<string> ReceiveTextAsync(this WebSocket self)
{
var buffer = new ArraySegment<byte>(new byte[2048]);
var receive = await self.ReceiveAsync(buffer, CancellationToken.None);
return Encoding.UTF8.GetString(buffer.Slice(0, receive.Count));
// TODO: Make this robust to multi-frame messages.
}
}
}