using Microsoft.Web.Administration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
public class IPFilterAttribute : ActionFilterAttribute
{
    private static List<string> _allowedIPs = new List<string>
    {
        "192.168.1.1",
        "10.0.0.0-10.0.0.255" // 支持IP段格式
    };
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string clientIP = GetClientIP();
        if (!IsAllowedIP(clientIP))
        {
            filterContext.Result = new RedirectResult("https://external-block-page.com");
            LogBlockedIP(clientIP);
        }
    }
    private string GetClientIP()
    {
        string ip = HttpContext.Current.Request.Headers["X-Forwarded-For"]?.Split(',')[0];
        return string.IsNullOrEmpty(ip) ? HttpContext.Current.Request.UserHostAddress : ip;
    }
    private bool IsAllowedIP(string ip)
    {
        return _allowedIPs.Contains(ip) || IPRangeContains(ip, _allowedIPs);
    }
    private bool IPRangeContains(string ip, List<string> ipRanges)
    {
        foreach (var range in ipRanges.Where(r => r.Contains('-')))
        {
            var start = IPAddress.Parse(range.Split('-')[0]);
            var end = IPAddress.Parse(range.Split('-')[1]);
            var client = IPAddress.Parse(ip);
            if (client.AddressFamily == AddressFamily.InterNetworkV6)
                throw new NotSupportedException("IPv6 range check not implemented");
            var bytes = client.GetAddressBytes();
            var startBytes = start.GetAddressBytes();
            var endBytes = end.GetAddressBytes();
            if (bytes.CompareTo(startBytes) >= 0 && bytes.CompareTo(endBytes) <= 0)
                return true;
        }
        return false;
    }
    private void LogBlockedIP(string ip)
    {
        File.AppendAllText("blocked_ips.log", $"{DateTime.Now}: Blocked IP - {ip}\n");
    }
    public static void SyncIISWhitelist()
    {
        try
        {
            using (ServerManager serverManager = new ServerManager())
            {
                var siteName = "OA_SITE"; // 替换为实际网站名称
                var site = serverManager.Sites.FirstOrDefault(s => s.Name == siteName);
                if (site == null) throw new Exception($"网站 '{siteName}' 未找到");
                var config = serverManager.GetApplicationHostConfiguration();
                var ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", siteName);
                
                if (ipSecuritySection == null)
                {
                    ipSecuritySection = config.CreateSection("system.webServer/security/ipSecurity", siteName);
                    ipSecuritySection["allowUnlisted"] = false; // 关键配置:未列出的IP自动拒绝
                }
                var ipCollection = ipSecuritySection.GetCollection();
                ipCollection.Clear(); // 清空现有规则
                foreach (var ip in _allowedIPs)
                {
                    var addElement = ipCollection.CreateElement("add");
                    addElement["ipAddress"] = ip;
                    addElement["action"] = "Allow";
                    addElement["allowed"] = true;
                    ipCollection.Add(addElement);
                }
                serverManager.CommitChanges();
            }
        }
        catch (Exception ex)
        {
            File.AppendAllText("sync_error.log", $"{DateTime.Now}: {ex.Message}\n");
        }
    }
}