-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add RouteTemplateAuthorizationConvention
- Loading branch information
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
53 changes: 53 additions & 0 deletions
53
src/EthernaACR/Conventions/RouteTemplateAuthorizationConvention.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
} | ||
} | ||
} | ||
} |