using Microsoft.AspNetCore.Mvc.Filters;
using NetPanel.Help;

namespace NetPanel.Filter
{
    public class ActionFilter : IAuthorizationFilter
    {

        private readonly IConfiguration _configuration;

        public ActionFilter(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //(1). 方法1
            //  string c= context.ActionDescriptor.RouteValues["area"].ToString();

            //  context.ActionDescriptor.RouteValues[“controller”].ToString();

            //  context.ActionDescriptor.RouteValues[“action”].ToString();

            //  (2). 方法2：

            //  context.RouteData.Values[“controller”].ToString();

            //  context.RouteData.Values[“action”].ToString();

            //  context.HttpContext.Connection.RemoteIpAddress


            string isAdmin = _configuration.GetConnectionString("IsAdmin");
            if (isAdmin == "1")
            {
                return;
            }

            //控制器名称
            string controllerName = context.ActionDescriptor.RouteValues["controller"].ToString();
            string action = context.ActionDescriptor.RouteValues["action"].ToString();
            if (controllerName == "Login" || controllerName == "Api" || (controllerName == "Home" && action == "Error"))
            {
                return;
            }
            string sUser = context.HttpContext.Session.GetString("user");
            if (sUser.IsNull())
            {
                context.Result = new Microsoft.AspNetCore.Mvc.RedirectResult("/Login/Login");
            }
        }
    }
}
