Files
jwxt/app/ip_middleware.py

115 lines
3.8 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
IP访问控制中间件
- 拦截非中国IP
- 拦截已封禁IP
- 记录访问日志
跳过静态资源、/blocked、/api/admin/ip/unban_temp 等路由
"""
import logging
from flask import request, render_template, g
from app.ip_manager import (
_get_real_ip, query_ip_geo, is_china_ip, is_ip_banned,
record_access, flush_logs_if_needed, _set_app, _utc_to_timestamp
)
logger = logging.getLogger(__name__)
# 不做IP检测的路径前缀
_SKIP_PREFIXES = (
'/static/',
'/blocked',
'/favicon.ico',
'/notify', # 支付平台回调:来源 IP 不可控(可能境外/数据中心),不能被 IP 风控拦截
)
# 不记日志的路径(太频繁)
_NO_LOG_PREFIXES = (
'/static/',
'/favicon.ico',
)
def _should_skip(path: str) -> bool:
return any(path.startswith(p) for p in _SKIP_PREFIXES)
def _should_log(path: str) -> bool:
return not any(path.startswith(p) for p in _NO_LOG_PREFIXES)
def init_ip_middleware(app):
"""注册IP中间件到Flask应用"""
_set_app(app)
@app.before_request
def ip_guard():
path = request.path
if _should_skip(path):
return None
ip = _get_real_ip(request)
g.client_ip = ip # 挂到g上,路由层可以直接用
# 查询地理位置(带缓存)
geo = query_ip_geo(ip)
g.client_geo = geo
country = geo.get('country', '')
g.client_country = country
# 1. 检查是否已被封禁
banned, ban_reason, expires_at = is_ip_banned(ip, country)
if banned:
if _should_log(path):
record_access(ip, geo, request.method, path,
status_code=403,
user_agent=request.headers.get('User-Agent', ''),
blocked=True, block_reason=ban_reason)
flush_logs_if_needed()
return render_template('blocked.html',
ip=ip,
reason=ban_reason,
expires_at=_utc_to_timestamp(expires_at) if expires_at else None,
block_type='banned'), 403
# 2. 检查是否中国IP(仅在启用中国限制时)
try:
from app.models import SystemConfig
china_only = SystemConfig.get('enable_china_only', 'true').lower() == 'true'
except Exception:
china_only = True
if china_only:
china, _ = is_china_ip(ip)
# 保守策略:geo查询失败也当作非中国IP处理(拦截未知来源)
if not china:
if _should_log(path):
record_access(ip, geo, request.method, path,
status_code=403,
user_agent=request.headers.get('User-Agent', ''),
blocked=True, block_reason='非中国IP')
flush_logs_if_needed()
return render_template('blocked.html',
ip=ip,
reason='检测到您的IP来自境外,本服务仅对中国大陆用户开放',
block_type='foreign'), 403
# 3. 正常放行,记录访问日志
if _should_log(path):
record_access(ip, geo, request.method, path,
user_agent=request.headers.get('User-Agent', ''),
blocked=False)
return None
@app.after_request
def after_ip_log(response):
"""更新日志状态码 + 定期刷新"""
flush_logs_if_needed()
return response
logger.info("[ip_middleware] IP访问控制中间件已注册")