初版:教务抢课系统 jwxt(从线上实例导出)
This commit is contained in:
@@ -0,0 +1,886 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
IP管理模块
|
||||
- IP地理位置查询(geoip2 本地库,HTTP API 降级)
|
||||
- 中国IP检测
|
||||
- IP封禁/解封
|
||||
- 登录频率限制
|
||||
- 访问日志记录
|
||||
- 邮件解封指令解析
|
||||
"""
|
||||
import calendar
|
||||
import ipaddress
|
||||
import logging
|
||||
import re
|
||||
import smtplib
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from email.mime.text import MIMEText
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import requests as http_requests
|
||||
from app.time_utils import now as bj_now, to_iso, BJ_TZ
|
||||
from app.settings import BASE_DIR
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Flask app 实例引用(用于后台线程的 app_context)
|
||||
_app_instance = None
|
||||
|
||||
# ── geoip2 本地库(GeoLite2)──
|
||||
# 延迟导入,避免未安装 geoip2 时整个模块无法加载
|
||||
_geoip_reader = None
|
||||
_geoip_reader_lock = threading.Lock()
|
||||
# 优先 City 库(含省市),没有则用 Country 库(仅国家,足够做中国IP判断)
|
||||
_GEOLITE_CITY_PATH = BASE_DIR / "GeoLite2-City.mmdb"
|
||||
_GEOLITE_COUNTRY_PATH = BASE_DIR / "GeoLite2-Country.mmdb"
|
||||
# 标记是否已打印过下载提示,避免每请求重复
|
||||
_geoip_warned = False
|
||||
|
||||
|
||||
def _get_geoip_reader():
|
||||
"""惰性加载 geoip2 本地库,优先 City 库,降级 Country 库,返回 reader 或 None"""
|
||||
global _geoip_reader, _geoip_warned
|
||||
if _geoip_reader is not None:
|
||||
return _geoip_reader
|
||||
with _geoip_reader_lock:
|
||||
if _geoip_reader is not None:
|
||||
return _geoip_reader
|
||||
try:
|
||||
import geoip2.database
|
||||
# 优先 City 库
|
||||
if _GEOLITE_CITY_PATH.exists():
|
||||
_geoip_reader = geoip2.database.Reader(str(_GEOLITE_CITY_PATH))
|
||||
logger.info(f"[ip_manager] GeoLite2 本地库已加载: {_GEOLITE_CITY_PATH.name}(City)")
|
||||
return _geoip_reader
|
||||
# 降级 Country 库(仅国家信息,足够做中国IP判断)
|
||||
if _GEOLITE_COUNTRY_PATH.exists():
|
||||
_geoip_reader = geoip2.database.Reader(str(_GEOLITE_COUNTRY_PATH))
|
||||
logger.info(f"[ip_manager] GeoLite2 本地库已加载: {_GEOLITE_COUNTRY_PATH.name}(Country,无省市)")
|
||||
return _geoip_reader
|
||||
# 两个库都没有
|
||||
if not _geoip_warned:
|
||||
_geoip_warned = True
|
||||
logger.warning(
|
||||
f"[ip_manager] 未找到 GeoLite2 库(City 或 Country)\n"
|
||||
f" 期望路径: {_GEOLITE_CITY_PATH} 或 {_GEOLITE_COUNTRY_PATH}\n"
|
||||
" IP 地理查询将降级到 HTTP API(延迟高、有并发瓶颈)\n"
|
||||
" 下载方式: python app/download_geolite2.py --account-id YOUR_ID --license-key YOUR_KEY"
|
||||
)
|
||||
return None
|
||||
except ImportError:
|
||||
if not _geoip_warned:
|
||||
_geoip_warned = True
|
||||
logger.warning("[ip_manager] geoip2 未安装,IP 查询降级到 HTTP API(pip install geoip2)")
|
||||
return None
|
||||
except Exception as e:
|
||||
if not _geoip_warned:
|
||||
_geoip_warned = True
|
||||
logger.warning(f"[ip_manager] GeoLite2 加载失败: {e},IP 查询降级到 HTTP API")
|
||||
return None
|
||||
|
||||
|
||||
def warmup_geoip_reader():
|
||||
"""启动时预热 GeoLite2 库(由 run.py 在 app.run 前调用)"""
|
||||
_get_geoip_reader()
|
||||
|
||||
|
||||
# geoip 本地查询结果缓存,避免重复查询
|
||||
_geo_cache: dict = {}
|
||||
_geo_cache_lock = threading.Lock()
|
||||
_GEO_CACHE_TTL = 3600 # 1小时
|
||||
|
||||
|
||||
def _utc_to_timestamp(dt: Optional[datetime]) -> Optional[int]:
|
||||
"""
|
||||
将 datetime 转为 Unix 时间戳(秒)
|
||||
支持 naive 和 aware datetime,自动识别时区
|
||||
"""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
# naive datetime,视为北京时间
|
||||
dt = dt.replace(tzinfo=BJ_TZ)
|
||||
return int(dt.timestamp())
|
||||
|
||||
|
||||
def _ensure_aware(dt: Optional[datetime]) -> Optional[datetime]:
|
||||
"""将 naive datetime 转换为 aware datetime(北京时间)"""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
return dt.replace(tzinfo=BJ_TZ)
|
||||
return dt
|
||||
|
||||
|
||||
def _set_app(app):
|
||||
"""由 ip_middleware 在 init 时调用,存储 app 引用"""
|
||||
global _app_instance
|
||||
_app_instance = app
|
||||
|
||||
|
||||
def _get_real_ip(request) -> str:
|
||||
"""从请求中获取真实IP。
|
||||
Nginx 覆盖 XFF 后由 ProxyFix(x_for=1) 写入 remote_addr,这里直接用
|
||||
remote_addr——不再信任裸 X-Forwarded-For/X-Real-IP 头(客户端可伪造,
|
||||
会被用来绕过封禁/伪造他人 IP)。"""
|
||||
return request.remote_addr or '127.0.0.1'
|
||||
|
||||
|
||||
def query_ip_geo(ip: str) -> dict:
|
||||
"""
|
||||
查询IP地理位置
|
||||
优先级:本地 geoip2 库(微秒级) → HTTP API 降级(ip-api.com/ipinfo.io/freeipapi)
|
||||
返回结构:
|
||||
{
|
||||
'country': 'CN', # 国家代码
|
||||
'country_name': '中国',
|
||||
'region': '山东',
|
||||
'city': '济南',
|
||||
'isp': 'China Unicom',
|
||||
'lat': 36.67,
|
||||
'lon': 116.99,
|
||||
'success': True
|
||||
}
|
||||
"""
|
||||
# 本地/私有IP直接返回中国
|
||||
try:
|
||||
addr = ipaddress.ip_address(ip)
|
||||
if addr.is_private or addr.is_loopback or addr.is_unspecified:
|
||||
return {
|
||||
'country': 'CN', 'country_name': '中国(本地)',
|
||||
'region': '本地', 'city': '本地',
|
||||
'isp': 'Local', 'lat': 0, 'lon': 0, 'success': True
|
||||
}
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# 查缓存
|
||||
now = time.time()
|
||||
with _geo_cache_lock:
|
||||
if ip in _geo_cache:
|
||||
entry, ts = _geo_cache[ip]
|
||||
if now - ts < _GEO_CACHE_TTL:
|
||||
return entry
|
||||
|
||||
result = {'country': '', 'country_name': '', 'region': '', 'city': '',
|
||||
'isp': '', 'lat': 0, 'lon': 0, 'success': False}
|
||||
|
||||
# 1. 优先使用本地 geoip2 库(微秒级,无网络开销)
|
||||
reader = _get_geoip_reader()
|
||||
if reader is not None:
|
||||
try:
|
||||
# City 库有 city() 方法,Country 库只有 country() 方法
|
||||
db_type = getattr(reader.metadata(), 'database_type', '')
|
||||
if 'City' in db_type:
|
||||
resp = reader.city(ip)
|
||||
result = {
|
||||
'country': resp.country.iso_code or '',
|
||||
'country_name': resp.country.name or '',
|
||||
'region': (resp.subdivisions.most_specific.name or '') if resp.subdivisions.most_specific else '',
|
||||
'city': resp.city.name or '',
|
||||
'isp': '', # City 库不含 ISP,需 ASN 库;留空
|
||||
'lat': resp.location.latitude or 0,
|
||||
'lon': resp.location.longitude or 0,
|
||||
'success': True
|
||||
}
|
||||
else:
|
||||
# Country 库只有国家信息,省市/经纬度留空(足够做中国IP判断)
|
||||
resp = reader.country(ip)
|
||||
result = {
|
||||
'country': resp.country.iso_code or '',
|
||||
'country_name': resp.country.name or '',
|
||||
'region': '', 'city': '', 'isp': '',
|
||||
'lat': 0, 'lon': 0,
|
||||
'success': True
|
||||
}
|
||||
except Exception:
|
||||
pass # 本地库查不到(如内网 IP 段),降级 HTTP
|
||||
|
||||
# 2. 本地库不可用或查不到,降级到 HTTP API
|
||||
if not result['success']:
|
||||
# 2a. ip-api.com(HTTPS + HTTP 降级)
|
||||
for scheme in ('https', 'http'):
|
||||
try:
|
||||
resp_data = http_requests.get(
|
||||
f'{scheme}://ip-api.com/json/{ip}',
|
||||
params={'lang': 'zh-CN', 'fields': 'status,country,countryCode,regionName,city,isp,lat,lon,query'},
|
||||
timeout=(2, 5)
|
||||
)
|
||||
data = resp_data.json()
|
||||
if data.get('status') == 'success':
|
||||
result = {
|
||||
'country': data.get('countryCode', ''),
|
||||
'country_name': data.get('country', ''),
|
||||
'region': data.get('regionName', ''),
|
||||
'city': data.get('city', ''),
|
||||
'isp': data.get('isp', ''),
|
||||
'lat': data.get('lat', 0),
|
||||
'lon': data.get('lon', 0),
|
||||
'success': True
|
||||
}
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 2b. ip-api 失败时,尝试备用 API(ipinfo.io)
|
||||
if not result['success']:
|
||||
for scheme in ('https', 'http'):
|
||||
try:
|
||||
resp_data = http_requests.get(
|
||||
f'{scheme}://ipinfo.io/{ip}/json',
|
||||
timeout=(2, 5)
|
||||
)
|
||||
data = resp_data.json()
|
||||
if 'country' in data:
|
||||
result = {
|
||||
'country': data.get('country', ''),
|
||||
'country_name': '',
|
||||
'region': data.get('region', ''),
|
||||
'city': data.get('city', ''),
|
||||
'isp': data.get('org', ''),
|
||||
'lat': 0,
|
||||
'lon': 0,
|
||||
'success': True
|
||||
}
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 2c. ipinfo 也失败,尝试 freeipapi
|
||||
if not result['success']:
|
||||
for scheme in ('https', 'http'):
|
||||
try:
|
||||
resp_data = http_requests.get(
|
||||
f'{scheme}://freeipapi.com/api/json/{ip}',
|
||||
timeout=(2, 5)
|
||||
)
|
||||
data = resp_data.json()
|
||||
if data.get('statusCode') == 200:
|
||||
result = {
|
||||
'country': data.get('countryCode', ''),
|
||||
'country_name': data.get('countryName', ''),
|
||||
'region': data.get('regionName', ''),
|
||||
'city': data.get('cityName', ''),
|
||||
'isp': '',
|
||||
'lat': 0,
|
||||
'lon': 0,
|
||||
'success': True
|
||||
}
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
with _geo_cache_lock:
|
||||
_geo_cache[ip] = (result, now)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def is_china_ip(ip: str) -> Tuple[bool, dict]:
|
||||
"""
|
||||
判断是否是中国IP(含港澳台)
|
||||
返回 (is_china: bool, geo_info: dict)
|
||||
"""
|
||||
geo = query_ip_geo(ip)
|
||||
# 中国大陆 + 港澳台
|
||||
china_codes = {'CN', 'HK', 'MO', 'TW'}
|
||||
return geo.get('country', '') in china_codes, geo
|
||||
|
||||
|
||||
# ==================== 封禁管理 ====================
|
||||
|
||||
def parse_ban_duration(duration_str: Optional[str]) -> Optional[datetime]:
|
||||
"""
|
||||
解析封禁时长字符串,返回到期时间(None=永久)
|
||||
支持: 1h, 1d, 1w, 1m, permanent/forever/None
|
||||
"""
|
||||
if not duration_str or duration_str.lower() in ('permanent', 'forever', 'perm', '永久'):
|
||||
return None # 永久
|
||||
|
||||
duration_str = duration_str.strip().lower()
|
||||
now = bj_now()
|
||||
|
||||
m = re.match(r'^(\d+)([hdwm])$', duration_str)
|
||||
if not m:
|
||||
return None
|
||||
|
||||
num, unit = int(m.group(1)), m.group(2)
|
||||
if unit == 'h':
|
||||
return now + timedelta(hours=num)
|
||||
elif unit == 'd':
|
||||
return now + timedelta(days=num)
|
||||
elif unit == 'w':
|
||||
return now + timedelta(weeks=num)
|
||||
elif unit == 'm':
|
||||
return now + timedelta(days=num * 30)
|
||||
return None
|
||||
|
||||
|
||||
def ban_ip(ip_or_cidr: str, reason: str = '', duration_str: Optional[str] = None,
|
||||
ban_type: str = 'ip', created_by: str = 'admin') -> dict:
|
||||
"""
|
||||
封禁一个IP/CIDR/国家代码
|
||||
duration_str: None=永久, '1h'=1小时, '1d'=1天, '1w'=1周, '1m'=1个月
|
||||
"""
|
||||
from app.models import db, IPBan
|
||||
|
||||
expires_at = parse_ban_duration(duration_str)
|
||||
is_permanent = (expires_at is None)
|
||||
|
||||
# 检查是否已存在
|
||||
existing = IPBan.query.filter_by(ban_type=ban_type, value=ip_or_cidr).first()
|
||||
if existing:
|
||||
existing.reason = reason or existing.reason
|
||||
existing.is_permanent = is_permanent
|
||||
existing.expires_at = expires_at
|
||||
existing.created_by = created_by
|
||||
existing.created_at = bj_now()
|
||||
db.session.commit()
|
||||
_invalidate_ban_cache()
|
||||
return {'success': True, 'message': f'已更新封禁: {ip_or_cidr}', 'id': existing.id}
|
||||
|
||||
ban = IPBan(
|
||||
ban_type=ban_type,
|
||||
value=ip_or_cidr,
|
||||
reason=reason,
|
||||
is_permanent=is_permanent,
|
||||
expires_at=expires_at,
|
||||
created_by=created_by
|
||||
)
|
||||
db.session.add(ban)
|
||||
db.session.commit()
|
||||
_invalidate_ban_cache()
|
||||
logger.info(f"[ip_manager] 封禁 {ban_type}:{ip_or_cidr} 原因={reason} 到期={expires_at} 操作={created_by}")
|
||||
return {'success': True, 'message': f'封禁成功: {ip_or_cidr}', 'id': ban.id}
|
||||
|
||||
|
||||
def unban_ip(ip_or_cidr: str, ban_type: str = 'ip') -> dict:
|
||||
"""解封IP/CIDR/国家代码"""
|
||||
from app.models import db, IPBan, LoginAttempt
|
||||
|
||||
bans = IPBan.query.filter_by(ban_type=ban_type, value=ip_or_cidr).all()
|
||||
if not bans:
|
||||
return {'success': False, 'message': f'未找到封禁记录: {ip_or_cidr}'}
|
||||
|
||||
for ban in bans:
|
||||
db.session.delete(ban)
|
||||
|
||||
# 解封时清除该IP的失败登录记录,防止解封后立即又被封
|
||||
LoginAttempt.query.filter_by(ip=ip_or_cidr).delete()
|
||||
|
||||
db.session.commit()
|
||||
_invalidate_ban_cache()
|
||||
logger.info(f"[ip_manager] 解封 {ban_type}:{ip_or_cidr},已清除登录失败记录")
|
||||
return {'success': True, 'message': f'解封成功: {ip_or_cidr}'}
|
||||
|
||||
|
||||
# ── is_ip_banned 内存缓存 ──
|
||||
# 缓存 (ip, country) → (is_banned, reason, expires_at, cached_ts)
|
||||
_ban_cache: dict = {}
|
||||
_ban_cache_lock = threading.Lock()
|
||||
_BAN_CACHE_TTL = 10 # 秒,封禁状态变化后最多 10 秒生效
|
||||
|
||||
|
||||
def _invalidate_ban_cache():
|
||||
"""清除全部封禁缓存(封禁/解封操作后调用)"""
|
||||
with _ban_cache_lock:
|
||||
_ban_cache.clear()
|
||||
|
||||
|
||||
def is_ip_banned(ip: str, country: str = '') -> Tuple[bool, str, Optional[datetime]]:
|
||||
"""
|
||||
检查IP是否被封禁
|
||||
返回 (is_banned: bool, reason: str, expires_at: Optional[datetime])
|
||||
带 10 秒内存缓存,封禁状态变化后最多 10 秒生效
|
||||
"""
|
||||
from app.models import IPBan
|
||||
|
||||
now = bj_now()
|
||||
cache_key = (ip, country.upper())
|
||||
|
||||
# 查缓存
|
||||
now_ts = time.time()
|
||||
with _ban_cache_lock:
|
||||
entry = _ban_cache.get(cache_key)
|
||||
if entry is not None:
|
||||
is_banned, reason, expires_at, cached_ts = entry
|
||||
if now_ts - cached_ts < _BAN_CACHE_TTL:
|
||||
return is_banned, reason, expires_at
|
||||
|
||||
# 缓存未命中,查数据库
|
||||
result_banned = False
|
||||
result_reason = ''
|
||||
result_expires = None
|
||||
|
||||
# 1. 检查精确IP封禁
|
||||
exact = IPBan.query.filter_by(ban_type='ip', value=ip).first()
|
||||
if exact and (exact.is_permanent or (exact.expires_at and _ensure_aware(exact.expires_at) > now)):
|
||||
result_banned = True
|
||||
result_reason = exact.reason or 'IP已被封禁'
|
||||
result_expires = None if exact.is_permanent else exact.expires_at
|
||||
|
||||
# 2. 检查CIDR段封禁
|
||||
if not result_banned:
|
||||
cidr_bans = IPBan.query.filter_by(ban_type='cidr').all()
|
||||
try:
|
||||
client_addr = ipaddress.ip_address(ip)
|
||||
for ban in cidr_bans:
|
||||
if not (ban.is_permanent or (ban.expires_at and _ensure_aware(ban.expires_at) > now)):
|
||||
continue
|
||||
try:
|
||||
network = ipaddress.ip_network(ban.value, strict=False)
|
||||
if client_addr in network:
|
||||
result_banned = True
|
||||
result_reason = ban.reason or f'IP段 {ban.value} 已被封禁'
|
||||
result_expires = None if ban.is_permanent else ban.expires_at
|
||||
break
|
||||
except ValueError:
|
||||
pass
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# 3. 检查国家封禁
|
||||
if not result_banned and country:
|
||||
country_ban = IPBan.query.filter_by(ban_type='country', value=country.upper()).first()
|
||||
if country_ban and (country_ban.is_permanent or (country_ban.expires_at and _ensure_aware(country_ban.expires_at) > now)):
|
||||
result_banned = True
|
||||
result_reason = country_ban.reason or f'地区 {country} 已被限制访问'
|
||||
result_expires = None if country_ban.is_permanent else country_ban.expires_at
|
||||
|
||||
# 写缓存
|
||||
with _ban_cache_lock:
|
||||
_ban_cache[cache_key] = (result_banned, result_reason, result_expires, now_ts)
|
||||
|
||||
return result_banned, result_reason, result_expires
|
||||
|
||||
|
||||
# ==================== 访问日志 ====================
|
||||
|
||||
# 异步写日志队列,避免每次请求都同步写DB
|
||||
_log_queue = []
|
||||
_log_lock = threading.Lock()
|
||||
_LOG_BATCH_SIZE = 50
|
||||
_last_flush = time.time()
|
||||
|
||||
|
||||
def record_access(ip: str, geo: dict, method: str, path: str,
|
||||
status_code: int = 0, user_agent: str = '',
|
||||
blocked: bool = False, block_reason: str = ''):
|
||||
"""记录访问日志(批量异步写入)"""
|
||||
entry = {
|
||||
'ip': ip,
|
||||
'country': geo.get('country', ''),
|
||||
'region': geo.get('region', ''),
|
||||
'city': geo.get('city', ''),
|
||||
'isp': geo.get('isp', ''),
|
||||
'method': method,
|
||||
'path': path[:500] if path else '',
|
||||
'status_code': status_code,
|
||||
'user_agent': user_agent[:500] if user_agent else '',
|
||||
'blocked': blocked,
|
||||
'block_reason': block_reason,
|
||||
'created_at': bj_now()
|
||||
}
|
||||
with _log_lock:
|
||||
_log_queue.append(entry)
|
||||
should_flush = len(_log_queue) >= _LOG_BATCH_SIZE
|
||||
|
||||
if should_flush:
|
||||
_flush_logs()
|
||||
|
||||
|
||||
def _flush_logs():
|
||||
"""将队列中的日志批量写入数据库"""
|
||||
global _last_flush
|
||||
with _log_lock:
|
||||
if not _log_queue:
|
||||
return
|
||||
batch = _log_queue[:]
|
||||
_log_queue.clear()
|
||||
_last_flush = time.time()
|
||||
|
||||
try:
|
||||
from app.models import db, IPAccessLog
|
||||
app = _app_instance
|
||||
if app is None:
|
||||
logger.warning("[ip_manager] Flask app 未初始化,跳过日志写入")
|
||||
return
|
||||
with app.app_context():
|
||||
for entry in batch:
|
||||
log = IPAccessLog(**entry)
|
||||
db.session.add(log)
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
logger.warning(f"[ip_manager] 写访问日志失败: {e}")
|
||||
|
||||
|
||||
def flush_logs_if_needed():
|
||||
"""定期刷新(在每次请求后调用)"""
|
||||
global _last_flush
|
||||
if time.time() - _last_flush > 10: # 超过10秒就刷一次
|
||||
threading.Thread(target=_flush_logs, daemon=True).start()
|
||||
|
||||
|
||||
# ==================== 登录频率限制 ====================
|
||||
|
||||
def check_login_rate_limit(ip: str, window_minutes: int = 10, max_attempts: int = 10) -> Tuple[bool, str]:
|
||||
"""
|
||||
检查登录频率限制
|
||||
window_minutes: 时间窗口(分钟)
|
||||
max_attempts: 窗口内最大失败次数
|
||||
返回 (is_limited: bool, message: str)
|
||||
"""
|
||||
from app.models import db, LoginAttempt, IPBan
|
||||
|
||||
now = bj_now()
|
||||
window_start = now - timedelta(minutes=window_minutes)
|
||||
|
||||
# 统计窗口内失败次数
|
||||
fail_count = LoginAttempt.query.filter(
|
||||
LoginAttempt.ip == ip,
|
||||
LoginAttempt.success == False,
|
||||
LoginAttempt.created_at >= window_start
|
||||
).count()
|
||||
|
||||
if fail_count >= max_attempts:
|
||||
# 自动封禁1小时
|
||||
existing = IPBan.query.filter_by(ban_type='ip', value=ip).first()
|
||||
if not existing:
|
||||
ban_ip(ip, reason=f'登录失败频率超限({window_minutes}分钟内失败{fail_count}次)',
|
||||
duration_str='1h', created_by='auto')
|
||||
logger.warning(f"[ip_manager] 自动封禁IP {ip}(登录失败{fail_count}次/{window_minutes}分钟)")
|
||||
return True, f'登录尝试过于频繁,已被临时封禁1小时'
|
||||
|
||||
return False, ''
|
||||
|
||||
|
||||
def record_login_attempt(ip: str, username: str, success: bool):
|
||||
"""记录一次登录尝试"""
|
||||
from app.models import db, LoginAttempt
|
||||
|
||||
attempt = LoginAttempt(ip=ip, username=username, success=success)
|
||||
db.session.add(attempt)
|
||||
db.session.commit()
|
||||
|
||||
# 清理7天前的记录
|
||||
cutoff = bj_now() - timedelta(days=7)
|
||||
LoginAttempt.query.filter(LoginAttempt.created_at < cutoff).delete()
|
||||
db.session.commit()
|
||||
|
||||
|
||||
# ==================== 邮件解封指令 ====================
|
||||
|
||||
def parse_unban_email_command(subject: str) -> Optional[dict]:
|
||||
"""
|
||||
解析邮件解封指令
|
||||
格式: unban [ip|all] [duration]
|
||||
例如:
|
||||
unban => 解封所有IP,1小时后重新封禁
|
||||
unban 1.2.3.4 1d => 解封IP 1.2.3.4,封禁1天后再封
|
||||
unban 1.2.3.4 => 永久解封
|
||||
unban all => 解封所有(永久)
|
||||
unban all 1h => 解封所有IP,1小时后重新封禁
|
||||
unban 1.2.3.4 1h => 短暂解封1小时(解封后1小时重新封禁)
|
||||
返回 None 或 {'ip': ..., 'duration': ...}
|
||||
"""
|
||||
subject = subject.strip()
|
||||
# 匹配 unban 后面可选的 ip/all 和 duration
|
||||
m = re.match(r'^unban(?:\s+(\S+))?(?:\s+(\S+))?$', subject, re.IGNORECASE)
|
||||
if not m:
|
||||
return None
|
||||
|
||||
ip_val = m.group(1).strip() if m.group(1) else None
|
||||
duration = m.group(2).strip() if m.group(2) else None
|
||||
|
||||
# 如果只有 unban 没有参数,默认解封所有IP 1小时
|
||||
if ip_val is None:
|
||||
return {'ip': 'all', 'duration': '1h'}
|
||||
|
||||
return {'ip': ip_val, 'duration': duration}
|
||||
|
||||
|
||||
def check_unban_emails(app, processed_ids=None, max_age_seconds=60, save_callback=None):
|
||||
"""
|
||||
检查邮箱中的解封指令(IMAP)
|
||||
在独立线程中定期调用
|
||||
Args:
|
||||
app: Flask应用实例
|
||||
processed_ids: 已处理的邮件ID集合
|
||||
max_age_seconds: 超过此秒数的邮件将被忽略
|
||||
save_callback: 保存已处理ID的回调函数
|
||||
"""
|
||||
import os
|
||||
from email.utils import parsedate_to_datetime
|
||||
|
||||
if processed_ids is None:
|
||||
processed_ids = set()
|
||||
current_time = time.time()
|
||||
newly_processed = set()
|
||||
import imaplib
|
||||
import email as email_lib
|
||||
from email.header import decode_header
|
||||
|
||||
mail = None
|
||||
try:
|
||||
email_cfg = _load_email_config()
|
||||
if not email_cfg:
|
||||
return
|
||||
smtp_server, email_addr, password = email_cfg
|
||||
# QQ邮箱IMAP服务器
|
||||
imap_server = smtp_server.replace('smtp.', 'imap.')
|
||||
|
||||
mail = imaplib.IMAP4_SSL(imap_server, timeout=20) # 无超时会挂死整轮检查
|
||||
mail.login(email_addr, password)
|
||||
mail.select('INBOX')
|
||||
|
||||
# 搜索所有邮件,主题包含 unban(已读的也要处理)
|
||||
_, msgs = mail.search(None, 'SUBJECT "unban"')
|
||||
msg_ids = msgs[0].split()
|
||||
|
||||
if not msg_ids:
|
||||
return # finally 统一 logout
|
||||
|
||||
with app.app_context():
|
||||
for msg_id in msg_ids:
|
||||
msg_id_str = msg_id.decode() if isinstance(msg_id, bytes) else msg_id
|
||||
|
||||
_, data = mail.fetch(msg_id, '(RFC822)')
|
||||
raw = data[0][1]
|
||||
msg = email_lib.message_from_bytes(raw)
|
||||
|
||||
# 去重键用 Message-ID:IMAP 序列号跨会话会漂移(删信/新信),
|
||||
# 曾导致新解封指令的序列号恰好命中历史记录而被静默跳过
|
||||
dedup_id = (msg.get('Message-ID') or '').strip() or f'seq-{msg_id_str}'
|
||||
if dedup_id in processed_ids:
|
||||
continue
|
||||
|
||||
# 检查邮件发送时间,超过60秒忽略
|
||||
date_header = msg.get('Date', '')
|
||||
try:
|
||||
if date_header:
|
||||
email_time = parsedate_to_datetime(date_header)
|
||||
email_timestamp = email_time.timestamp()
|
||||
if current_time - email_timestamp > max_age_seconds:
|
||||
logger.info(f"[ip_manager] 忽略超时邮件: {msg_id_str} ({(current_time - email_timestamp):.0f}秒前)")
|
||||
newly_processed.add(dedup_id)
|
||||
continue
|
||||
except Exception:
|
||||
pass # 无法解析时间则不跳过
|
||||
|
||||
# 解码主题
|
||||
subject_raw = msg.get('Subject', '')
|
||||
subject_parts = decode_header(subject_raw)
|
||||
subject = ''
|
||||
for part, enc in subject_parts:
|
||||
if isinstance(part, bytes):
|
||||
subject += part.decode(enc or 'utf-8', errors='replace')
|
||||
else:
|
||||
subject += part
|
||||
|
||||
# 检查发件人是否是自己(安全验证)
|
||||
sender = msg.get('From', '')
|
||||
if email_addr not in sender:
|
||||
logger.info(f"[ip_manager] 忽略非本人邮件解封指令: from={sender}")
|
||||
# 标记为已读但不处理
|
||||
mail.store(msg_id, '+FLAGS', '\\Seen')
|
||||
newly_processed.add(dedup_id)
|
||||
continue
|
||||
|
||||
cmd = parse_unban_email_command(subject)
|
||||
if not cmd:
|
||||
mail.store(msg_id, '+FLAGS', '\\Seen')
|
||||
newly_processed.add(dedup_id)
|
||||
continue
|
||||
|
||||
# 标记为已处理
|
||||
newly_processed.add(dedup_id)
|
||||
|
||||
ip_val = cmd['ip']
|
||||
duration = cmd['duration']
|
||||
|
||||
if ip_val.lower() == 'all':
|
||||
# 解封所有
|
||||
from app.models import db, IPBan
|
||||
if duration:
|
||||
# 短暂解封:将所有封禁临时推迟 duration
|
||||
expires = parse_ban_duration(duration)
|
||||
if expires is None and duration.lower() not in ('permanent', 'forever', 'perm', '永久'):
|
||||
logger.warning(f"[ip_manager] 时长 '{duration}' 无法解析,按永久解封处理")
|
||||
bans = IPBan.query.filter_by(ban_type='ip').all()
|
||||
for b in bans:
|
||||
b.expires_at = expires
|
||||
b.is_permanent = False
|
||||
db.session.commit()
|
||||
logger.info(f"[ip_manager] 邮件指令:短暂解封所有IP,{duration}后恢复")
|
||||
else:
|
||||
IPBan.query.filter_by(ban_type='ip').delete()
|
||||
db.session.commit()
|
||||
logger.info(f"[ip_manager] 邮件指令:永久解封所有IP")
|
||||
else:
|
||||
if duration:
|
||||
# 短暂解封:将该IP封禁到期时间设为 duration 后
|
||||
from app.models import db, IPBan
|
||||
expires = parse_ban_duration(duration)
|
||||
if expires is None and duration.lower() not in ('permanent', 'forever', 'perm', '永久'):
|
||||
logger.warning(f"[ip_manager] 时长 '{duration}' 无法解析,IP {ip_val} 按永久解封处理")
|
||||
unban_ip(ip_val)
|
||||
mail.store(msg_id, '+FLAGS', '\\Seen')
|
||||
continue
|
||||
ban = IPBan.query.filter_by(ban_type='ip', value=ip_val).first()
|
||||
if ban:
|
||||
ban.expires_at = expires
|
||||
ban.is_permanent = False
|
||||
db.session.commit()
|
||||
logger.info(f"[ip_manager] 邮件指令:短暂解封IP {ip_val},{duration}后恢复")
|
||||
else:
|
||||
unban_ip(ip_val)
|
||||
logger.info(f"[ip_manager] 邮件指令:永久解封IP {ip_val}")
|
||||
|
||||
mail.store(msg_id, '+FLAGS', '\\Seen')
|
||||
|
||||
# 保存已处理的邮件ID
|
||||
if save_callback and newly_processed:
|
||||
all_ids = processed_ids | newly_processed
|
||||
save_callback(all_ids)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"[ip_manager] 检查解封邮件失败: {e}")
|
||||
finally:
|
||||
if mail:
|
||||
try:
|
||||
mail.logout()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _load_email_config():
|
||||
"""读取 email.txt 配置"""
|
||||
import os
|
||||
email_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'email.txt')
|
||||
try:
|
||||
with open(email_file, encoding='utf-8') as f:
|
||||
lines = [l.strip() for l in f.readlines() if l.strip()]
|
||||
if len(lines) >= 3:
|
||||
return lines[0], lines[1], lines[2]
|
||||
except Exception as e:
|
||||
logger.warning(f"[ip_manager] 读取email.txt失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def start_email_unban_checker(app, interval_seconds: int = 60):
|
||||
"""启动邮件解封检查后台线程(每60秒检查一次)"""
|
||||
import os
|
||||
import json
|
||||
from email.utils import parsedate_to_datetime
|
||||
|
||||
# 已处理邮件ID存储文件
|
||||
processed_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'processed_unban_emails.json')
|
||||
max_age_seconds = 120 # 超过 2×轮询间隔 的邮件忽略(防 IMAP 卡顿时误丢解封指令)
|
||||
|
||||
def _load_processed():
|
||||
try:
|
||||
if os.path.exists(processed_file):
|
||||
with open(processed_file, 'r', encoding='utf-8') as f:
|
||||
return set(json.load(f))
|
||||
except:
|
||||
pass
|
||||
return set()
|
||||
|
||||
def _save_processed(ids):
|
||||
try:
|
||||
with open(processed_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(list(ids), f)
|
||||
except:
|
||||
pass
|
||||
|
||||
def _worker():
|
||||
time.sleep(10) # 延迟10秒启动
|
||||
while True:
|
||||
try:
|
||||
processed_ids = _load_processed()
|
||||
check_unban_emails(app, processed_ids, max_age_seconds, _save_processed)
|
||||
except Exception as e:
|
||||
logger.warning(f"[ip_manager] 邮件解封检查异常: {e}")
|
||||
time.sleep(interval_seconds)
|
||||
|
||||
t = threading.Thread(target=_worker, daemon=True, name='email-unban-checker')
|
||||
t.start()
|
||||
logger.info("[ip_manager] 邮件解封检查线程已启动")
|
||||
|
||||
|
||||
# ==================== 统计 ====================
|
||||
|
||||
def get_ip_stats(hours: int = 24) -> dict:
|
||||
"""获取IP访问统计"""
|
||||
from app.models import db, IPAccessLog
|
||||
from sqlalchemy import func
|
||||
|
||||
cutoff = bj_now() - timedelta(hours=hours)
|
||||
|
||||
# 总访问量
|
||||
total = IPAccessLog.query.filter(IPAccessLog.created_at >= cutoff).count()
|
||||
blocked = IPAccessLog.query.filter(
|
||||
IPAccessLog.created_at >= cutoff,
|
||||
IPAccessLog.blocked == True
|
||||
).count()
|
||||
|
||||
# 按国家分组
|
||||
by_country = db.session.query(
|
||||
IPAccessLog.country,
|
||||
func.count(IPAccessLog.id).label('count')
|
||||
).filter(
|
||||
IPAccessLog.created_at >= cutoff
|
||||
).group_by(IPAccessLog.country).order_by(func.count(IPAccessLog.id).desc()).limit(20).all()
|
||||
|
||||
# 按省份分组(中国)
|
||||
by_region = db.session.query(
|
||||
IPAccessLog.region,
|
||||
func.count(IPAccessLog.id).label('count')
|
||||
).filter(
|
||||
IPAccessLog.created_at >= cutoff,
|
||||
IPAccessLog.country == 'CN'
|
||||
).group_by(IPAccessLog.region).order_by(func.count(IPAccessLog.id).desc()).limit(20).all()
|
||||
|
||||
# Top IP
|
||||
top_ips = db.session.query(
|
||||
IPAccessLog.ip,
|
||||
IPAccessLog.country,
|
||||
IPAccessLog.region,
|
||||
IPAccessLog.city,
|
||||
func.count(IPAccessLog.id).label('count')
|
||||
).filter(
|
||||
IPAccessLog.created_at >= cutoff
|
||||
).group_by(IPAccessLog.ip).order_by(func.count(IPAccessLog.id).desc()).limit(20).all()
|
||||
|
||||
# 按小时分布(最近24h)
|
||||
by_hour = db.session.query(
|
||||
func.date_format(IPAccessLog.created_at, '%H').label('hour'),
|
||||
func.count(IPAccessLog.id).label('count')
|
||||
).filter(
|
||||
IPAccessLog.created_at >= cutoff
|
||||
).group_by(func.date_format(IPAccessLog.created_at, '%H')).all()
|
||||
|
||||
|
||||
# 活跃封禁数(在 Python 侧计算比较时间,避免 naive/aware datetime 问题)
|
||||
from app.models import IPBan
|
||||
ban_cutoff = bj_now() + timedelta(hours=8)
|
||||
active_bans = IPBan.query.filter(
|
||||
(IPBan.is_permanent == True) |
|
||||
(IPBan.expires_at.isnot(None) & (IPBan.expires_at > ban_cutoff))
|
||||
).count()
|
||||
|
||||
return {
|
||||
'total': total,
|
||||
'blocked': blocked,
|
||||
'active_bans': active_bans,
|
||||
'unique_ips': db.session.query(func.count(func.distinct(IPAccessLog.ip))).filter(
|
||||
IPAccessLog.created_at >= cutoff).scalar() or 0,
|
||||
'by_country': [{'country': r.country or '未知', 'count': r.count} for r in by_country],
|
||||
'by_region': [{'region': r.region or '未知', 'count': r.count} for r in by_region],
|
||||
'top_ips': [{'ip': r.ip, 'country': r.country, 'region': r.region,
|
||||
'city': r.city, 'count': r.count} for r in top_ips],
|
||||
'by_hour': [{'hour': r.hour, 'count': r.count} for r in by_hour],
|
||||
}
|
||||
Reference in New Issue
Block a user