1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- using System;
- using System.Reflection;
- using Luticate2.Auth.Attributes;
- using Luticate2.Auth.Interfaces.Permissions;
- using Luticate2.Auth.Interfaces.Users;
- using Luticate2.Utils.Controllers;
- using Luticate2.Utils.Dbo.Result;
- using Microsoft.AspNetCore.Mvc.Controllers;
- using Microsoft.AspNetCore.Mvc.Filters;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace Luticate2.Auth.Middlewares
- {
- public class LuPermissionMiddleware : IActionFilter
- {
- private readonly IServiceProvider _serviceProvider;
- private readonly ILuPermissionsBusiness _luPermissionsBusiness;
-
- public LuPermissionMiddleware(IServiceProvider serviceProvider, ILuPermissionsBusiness luPermissionsBusiness)
- {
- _serviceProvider = serviceProvider;
- _luPermissionsBusiness = luPermissionsBusiness;
- }
-
- public void OnActionExecuting(ActionExecutingContext context)
- {
- var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
- if (actionDescriptor != null)
- {
- var attributes = actionDescriptor.MethodInfo.GetCustomAttributes<LuPermissionAttribute>();
- foreach (var attribute in attributes)
- {
- var srcAccessor = _serviceProvider.GetService(attribute.SrcEntityAccessor) as ILuAttrEntityAccessor;
- var dstAccessor = _serviceProvider.GetService(attribute.DstEntityAccessor) as ILuAttrEntityAccessor;
- var srcEntity = srcAccessor?.GetEntity(context, attribute.Id);
- var dstEntity = dstAccessor?.GetEntity(context, attribute.Id);
- var permissionValue = _luPermissionsBusiness.GetPermissionEffectiveValue(attribute.PermissionName,
- attribute.SrcEntityType, srcEntity, attribute.DstEntityType, dstEntity).ThrowIfNotSuccess();
- if (!permissionValue.Data)
- {
- var user = _serviceProvider.GetService<ILuLoggedUserAccessor>().GetLoggedUser();
- LuResult<object>.Error(LuStatus.PermissionError,$"user: {user?.Id} {user?.Username}",
- "Permission denied").Throw();
- }
- }
- }
- }
-
- public void OnActionExecuted(ActionExecutedContext context)
- {
- }
- }
- }
|