From 8aff8c431e3a2873e3b222de590044da06c15b0c Mon Sep 17 00:00:00 2001 From: Mirko Da Corte Date: Sat, 7 Sep 2024 17:41:15 +0200 Subject: [PATCH] add RouteTemplateAuthorizationConvention --- .../RouteTemplateAuthorizationConvention.cs | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/EthernaACR/Conventions/RouteTemplateAuthorizationConvention.cs diff --git a/src/EthernaACR/Conventions/RouteTemplateAuthorizationConvention.cs b/src/EthernaACR/Conventions/RouteTemplateAuthorizationConvention.cs new file mode 100644 index 0000000..944f8ad --- /dev/null +++ b/src/EthernaACR/Conventions/RouteTemplateAuthorizationConvention.cs @@ -0,0 +1,53 @@ +// Copyright 2021-present Etherna SA +// This file is part of Etherna ACR. +// +// Etherna ACR is free software: you can redistribute it and/or modify it under the terms of the +// GNU Lesser General Public License as published by the Free Software Foundation, +// either version 3 of the License, or (at your option) any later version. +// +// Etherna ACR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +// See the GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License along with Etherna ACR. +// If not, see . + +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc.ApplicationModels; +using Microsoft.AspNetCore.Mvc.Authorization; +using System; +using System.Linq; + +namespace Etherna.ACR.Conventions +{ + public class RouteTemplateAuthorizationConvention : IApplicationModelConvention + { + private readonly string routeTemplate; + private readonly string policyName; + + public RouteTemplateAuthorizationConvention(string routeTemplate, string policyName) + { + this.routeTemplate = routeTemplate; + this.policyName = policyName; + } + + public void Apply(ApplicationModel application) + { + ArgumentNullException.ThrowIfNull(application, nameof(application)); + + foreach (var controller in application.Controllers) + { + var isInRouteTemplate = controller.Selectors.Any( + s => s.AttributeRouteModel?.Template?.StartsWith( + routeTemplate, + StringComparison.OrdinalIgnoreCase) ?? false); + + //give priority to authorize attribute + var hasAuthorizeAttribute = controller.Attributes.OfType().Any(); + + if (isInRouteTemplate && !hasAuthorizeAttribute) + controller.Filters.Add(new AuthorizeFilter(policyName)); + } + } + } +} \ No newline at end of file