using Microsoft.AspNetCore.Mvc.Filters;

namespace NetinaCMS.Api.WebFramework.Bases;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class ClaimRequirement : AuthorizeAttribute, IAuthorizationFilter
{
    private readonly string _claimsType;
    private readonly string _claimsValue;

    public ClaimRequirement(string type,string value)
    {
        type = value;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;
        var permissions = user.Claims?.Where(c => c.Type == _claimsType)?.ToList();
        if (permissions == null)
        {
            context.Result = new StatusCodeResult((int)HttpStatusCode.Forbidden);
        }
        else
        {
            bool isAccepted = false;
                if (permissions.FirstOrDefault(p => p.Value == _claimsValue) != null)
                    isAccepted = true;
            if (!isAccepted)
                context.Result = new StatusCodeResult((int)HttpStatusCode.Forbidden);
        }
    }
}

