31 lines
901 B
C#
31 lines
901 B
C#
using GameList.Data;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
|
namespace GameList.Infrastructure;
|
|
|
|
public class EnsurePlayerExistsMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
|
|
public EnsurePlayerExistsMiddleware(RequestDelegate next)
|
|
{
|
|
_next = next;
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context, AppDbContext db)
|
|
{
|
|
if (context.User?.Identity?.IsAuthenticated == true)
|
|
{
|
|
var id = context.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
|
|
if (string.IsNullOrWhiteSpace(id) || !Guid.TryParse(id, out var playerId) || await db.Players.FindAsync(playerId) is null)
|
|
{
|
|
await context.SignOutAsync();
|
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
|
return;
|
|
}
|
|
}
|
|
|
|
await _next(context);
|
|
}
|
|
}
|