#nullable enable
using Bit.Core.Entities;
using Bit.Core.Models.Api;
using Bit.Core.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Bit.Api.Billing.Attributes;
///
/// An action filter that facilitates the injection of a parameter into the executing action method arguments.
///
///
/// This attribute retrieves the authorized user associated with the current HTTP context using the service.
/// If the user is unauthorized or cannot be found, the request is terminated with an unauthorized response.
/// The injected
/// parameter must be marked with a [BindNever] attribute to short-circuit the model-binding system.
///
///
/// EndpointAsync([BindNever] User user)
/// ]]>
///
///
public class InjectUserAttribute : ActionFilterAttribute
{
public override async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
var userService = context.HttpContext.RequestServices.GetRequiredService();
var user = await userService.GetUserByPrincipalAsync(context.HttpContext.User);
if (user == null)
{
context.Result = new UnauthorizedObjectResult(new ErrorResponseModel("Unauthorized."));
return;
}
var userParameter =
context.ActionDescriptor.Parameters.FirstOrDefault(parameter => parameter.ParameterType == typeof(User));
if (userParameter != null)
{
context.ActionArguments[userParameter.Name] = user;
}
await next();
}
}