BaseController.cs 5.38 KB
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using System.Reflection;
using HHECS.Web.Aop;
using HHECS.WebCommon.Http;
using HHECS.WebCommon;
using HHECS.Application.Enums;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using HHECS.Model.Entities;
using HHECS.Dal.Repository;
using HHECS.Application.Service;
using HHECS.WebCommon.Json;
using System.Collections.Generic;
using HHECS.Infrastructure.LogHelper;
using HHECS.Model.ViewEntity;

namespace HHECS.Web
{
    /// <summary>
    /// 基础控制器
    /// <para>用于控制登录用户是否有权限访问指定的Action</para>
    /// </summary>

    public class BaseController : Controller
    {

        protected string controllerName;   //当前控制器小写名称
        protected string actionName;        //当前Action小写名称

        protected HttpContext Context { get; set; }
        public const string token = "Token";
        public const string referer = "Referer";
        public const string origin = "Origin";



        public static List<User> Users = new List<User>();

        /// <summary>
        /// 用户信息
        /// </summary>
        public new User User { get; set; }

        /// <summary>
        /// https://blog.csdn.net/mango_love/article/details/84992020
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Context = HttpContext;
            var principal = HttpContext.AuthenticateAsync().Result.Principal;

            if (principal == null)
            {
                filterContext.Result = new RedirectResult("/Login/Index");
            }
            else if (!CheckLogin())
            {
                filterContext.Result = new RedirectResult("/Login/Index");
            }
            else if (string.IsNullOrWhiteSpace(principal.Identity.Name))
            {
                filterContext.Result = new RedirectResult("/Login/Index");
            }
        }

        public void ResponseEnumJosn()
        {
            try
            {
                //枚举输出到页面json 
                ViewBag.EnumIsVisible = typeof(EnumIsVisible)?.GetJsonEnum();
                ViewBag.EnumIsDisable = typeof(EnumIsDisable)?.GetJsonEnum();
                ViewBag.EnumPermissionType = EnumExtensions.GetEnumDescriptionList<EnumPermissionType>();
                ViewBag.Company = DateTime.Now.Year + "-" + new CompanyRepository().Where(t => true).ToOne()?.Name;
            }
            catch (Exception ex )
            {
                Log4NetHelper.Instance.Error($"ResponseEnumJosn 绑定页面数据异常:{ex.Message}");
            }
        }

        public string GetToken()
        {
            string tempToken = Context.Request.Query[token];
            if (!String.IsNullOrEmpty(tempToken)) return tempToken;
            var cookie = Context.Request.Cookies[token];
            if (string.IsNullOrWhiteSpace(cookie))
            {
                cookie = Context.Request.Headers["access-token"];
            }
            return string.IsNullOrWhiteSpace(cookie) ? String.Empty : cookie;
        }

        bool CheckLogin()
        {
            try
            {
                var token = GetToken();
                if (string.IsNullOrWhiteSpace(token)) return false;
                User = Users.Find(t => token == t.Token);
                if (User != null) return true;
                if (User?.Token == token) return true;
                User = new UserRepository().Where(t => t.Token == token).First();
                if (User != null)
                {
                    var users = new UserRoleRepository().Where(t => t.UserId == User.Id).ToList();
                    var roleIds = users.Select(t => t.RoleId).ToList();
                    var permissions = new PermissionRepository().Where(t => t.MenuType == "WEB").ToList();
                    User.Roles = new RoleRepository().Where(t => roleIds.Contains(t.Id)).ToList();
                    if (User.Roles.Any(t => t.RoleName == "管理员"))
                        User.Roles.ForEach(t => { t.Permissions = permissions; });
                    else
                    {
                        User.Roles.ForEach(t =>
                        {
                            var rolePermissions = new RolePermissionRepository().Where(c => c.RoleId == t.Id).ToList();
                            var permissionIds = rolePermissions.Select(t => t.PermissionId).ToList();
                            t.Permissions = permissions.Where(c => permissionIds.Contains(c.Id)).ToList();
                        });
                    }
                    if (!Users.Any(t => User.Token == t.Token)) Users.Add(User);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.Instance.Error($"检测用户权限异常:{ex.Message}");
            }
            return false;
        }

        public Response Response { get; set; } = new Response();
        public dynamic Execute(Func<dynamic> action, string methodName = "", Action actionFinally = null, Action actionCatCh = null)
        {
            return ExceptionsHelp.Instance.Execute(action, methodName, actionFinally, actionCatCh: actionCatCh);
        }
    }
}