Started adding api permission check
This commit is contained in:
11
Moonlight/Core/Attributes/ApiPermissionAttribute.cs
Normal file
11
Moonlight/Core/Attributes/ApiPermissionAttribute.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace Moonlight.Core.Attributes;
|
||||
|
||||
public class ApiPermissionAttribute : Attribute
|
||||
{
|
||||
public string Permission { get; set; }
|
||||
|
||||
public ApiPermissionAttribute(string permission)
|
||||
{
|
||||
Permission = permission;
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ using Moonlight.Core.Repositories;
|
||||
using Moonlight.Core.Services;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Moonlight.Core.Attributes;
|
||||
using Moonlight.Core.Http.Middleware;
|
||||
using Moonlight.Core.Implementations.ApiDefinition;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
|
||||
@@ -253,6 +254,8 @@ public class CoreFeature : MoonlightFeature
|
||||
if (config.Development.EnableApiReference)
|
||||
app.MapSwagger("/api/core/reference/openapi/{documentName}");
|
||||
|
||||
app.UseMiddleware<ApiPermissionMiddleware>();
|
||||
|
||||
await pluginService.RegisterImplementation<IApiDefinition>(new InternalApiDefinition());
|
||||
}
|
||||
|
||||
|
||||
55
Moonlight/Core/Http/Middleware/ApiPermissionMiddleware.cs
Normal file
55
Moonlight/Core/Http/Middleware/ApiPermissionMiddleware.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using MoonCore.Helpers;
|
||||
using Moonlight.Core.Attributes;
|
||||
|
||||
namespace Moonlight.Core.Http.Middleware;
|
||||
|
||||
public class ApiPermissionMiddleware
|
||||
{
|
||||
private RequestDelegate Next;
|
||||
|
||||
public ApiPermissionMiddleware(RequestDelegate next)
|
||||
{
|
||||
Next = next;
|
||||
}
|
||||
|
||||
public async Task Invoke(HttpContext context)
|
||||
{
|
||||
if (CheckRequest(context))
|
||||
await Next(context);
|
||||
else
|
||||
{
|
||||
context.Response.StatusCode = 403;
|
||||
await context.Response.WriteAsync("Permission denied");
|
||||
}
|
||||
}
|
||||
|
||||
private bool CheckRequest(HttpContext context)
|
||||
{
|
||||
var endpoint = context.GetEndpoint();
|
||||
|
||||
if (endpoint == null)
|
||||
return true;
|
||||
|
||||
var metadata = endpoint
|
||||
.Metadata
|
||||
.GetMetadata<ControllerActionDescriptor>();
|
||||
|
||||
if (metadata == null)
|
||||
return true;
|
||||
|
||||
if (metadata.ControllerTypeInfo.CustomAttributes
|
||||
.All(x => x.AttributeType != typeof(ApiControllerAttribute)))
|
||||
return true;
|
||||
|
||||
var permissionAttr =
|
||||
metadata.ControllerTypeInfo.CustomAttributes.FirstOrDefault(x =>
|
||||
x.AttributeType == typeof(ApiPermissionAttribute));
|
||||
|
||||
if (permissionAttr == null)
|
||||
return true;
|
||||
|
||||
if(metadata.)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user