Skip to content

Commit

Permalink
Merge pull request #21 from Etherna/feature/ACR-27-RouteTemplateAutho…
Browse files Browse the repository at this point in the history
…rizationConvention

add RouteTemplateAuthorizationConvention
  • Loading branch information
tmm360 authored Sep 7, 2024
2 parents db7a3ac + 8aff8c4 commit bb025fc
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/EthernaACR/Conventions/RouteTemplateAuthorizationConvention.cs
Original file line number Diff line number Diff line change
@@ -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 <https://www.gnu.org/licenses/>.

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<AuthorizeAttribute>().Any();

if (isInRouteTemplate && !hasAuthorizeAttribute)
controller.Filters.Add(new AuthorizeFilter(policyName));
}
}
}
}

0 comments on commit bb025fc

Please sign in to comment.