1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- using Base;
- using Infrastructure;
- using Infrastructure.Model;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Mvc.Filters;
- using Model;
- using Model.Base;
- using Services;
- using Util;
- namespace Middleware
- {
- /// <summary>
- /// API授权判断
- /// </summary>
- public class ActionPermissionFilter : ActionFilterAttribute//, IAsyncActionFilter
- {
- private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
- /// <summary>
- /// 权限字符串,例如 system:user:view
- /// </summary>
- public string Permission { get; set; } = string.Empty;
- /// <summary>
- /// 角色字符串,例如 common,admin
- /// </summary>
- public string RolePermi { get; set; } = string.Empty;
- private bool HasPermi { get; set; }
- public ActionPermissionFilter() { }
- public ActionPermissionFilter(string permission)
- {
- Permission = permission;
- HasPermi = !string.IsNullOrEmpty(Permission);
- }
- /// <summary>
- /// 执行Action前校验是否有权限访问
- /// </summary>
- /// <param name="context"></param>
- /// <param name="next"></param>
- /// <returns></returns>
- public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
- {
- TokenModel info = JwtUtil.GetLoginUser(context.HttpContext);
- if (info != null && info?.userId > 0)
- {
- long userId = info.userId;
- List<string> perms = CacheService.GetUserPerms(GlobalConstant.UserPermKEY + userId);
- List<string> rolePerms = info.RoleIds;
- if (perms == null)
- {
- var sysPermissionService = App.GetService<ISysPermissionService>();
- perms = sysPermissionService.List();
- CacheService.SetUserPerms(GlobalConstant.UserPermKEY + userId, perms);
- }
- if (perms.Exists(f => f.Equals(GlobalConstant.AdminPerm)))
- {
- HasPermi = true;
- }
- else if (rolePerms.Exists(f => f.Equals(GlobalConstant.AdminRole)))
- {
- HasPermi = true;
- }
- else if (!string.IsNullOrEmpty(Permission))
- {
- HasPermi = perms.Exists(f => f.ToLower() == Permission.ToLower());
- }
- if (!HasPermi && !string.IsNullOrEmpty(RolePermi))
- {
- HasPermi = info.RoleIds.Contains(RolePermi);
- }
- var url = context.HttpContext.Request.Path;
- if (!HasPermi && !Permission.Equals("common"))
- {
- logger.Info($"用户{info.username}没有权限访问{url},当前权限[{Permission}]");
- JsonResult result = new(new ApiResult((int)ResultCode.FORBIDDEN, $"你当前没有权限访问,请联系管理员", url))
- {
- ContentType = "application/json",
- };
- context.HttpContext.Response.StatusCode = 403;
- context.Result = result;
- }
- }
- return base.OnActionExecutionAsync(context, next);
- }
- }
- }
|