Add AuthScopedFilter to set AddedWho via middleware
Introduce AuthScopedFilter to automatically set the AddedWho property on IAuthScoped commands using configuration, and register it globally for all controllers. Remove manual AddedWho assignment from ResultViewController. Make AddedWho nullable in AuthScope and IAuthScoped.
This commit is contained in:
@@ -43,8 +43,6 @@ public class ResultViewController(IMediator mediator, IConfiguration config) : C
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create([FromBody] CreateResultViewCommand command, CancellationToken cancel)
|
||||
{
|
||||
// TODO: add middleware
|
||||
command.Scope.AddedWho = config?["AddedWho"] ?? throw new InvalidOperationException("The required 'AddedWho' configuration is missing. Please contact a system administrator.");
|
||||
await mediator.Send(command, cancel);
|
||||
return CreatedAtAction(nameof(Get), new { actionId = command.ActionId }, command);
|
||||
}
|
||||
|
||||
18
src/ReC.API/Middleware/AuthScopedFilter.cs
Normal file
18
src/ReC.API/Middleware/AuthScopedFilter.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using ReC.Application.Common.Interfaces;
|
||||
|
||||
namespace ReC.API.Middleware;
|
||||
|
||||
public class AuthScopedFilter(IConfiguration config) : IAsyncActionFilter
|
||||
{
|
||||
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
if (context.ActionArguments.TryGetValue("command", out var command) && command is IAuthScoped authScopedCommand)
|
||||
{
|
||||
var addedWho = config["AddedWho"] ?? throw new InvalidOperationException("The required 'AddedWho' configuration is missing. Please contact a system administrator.");
|
||||
authScopedCommand.Scope.AddedWho = addedWho;
|
||||
}
|
||||
|
||||
await next();
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,10 @@ try
|
||||
});
|
||||
});
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddControllers(options =>
|
||||
{
|
||||
options.Filters.Add<AuthScopedFilter>();
|
||||
});
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
|
||||
@@ -4,10 +4,10 @@ namespace ReC.Application.Common.Interfaces;
|
||||
|
||||
public record AuthScope
|
||||
{
|
||||
public string AddedWho { get; set; } = null!;
|
||||
public string? AddedWho { get; set; }
|
||||
}
|
||||
|
||||
public interface IAuthScoped : IScoped<AuthScope>
|
||||
{
|
||||
public string AddedWho => Scope.AddedWho;
|
||||
public string? AddedWho => Scope.AddedWho;
|
||||
}
|
||||
Reference in New Issue
Block a user