feat: v2.6.1 - 简化验证码方案,所有手动请求都需验证
核心改进: - 移除复杂的IP限流逻辑,改为每次请求都需验证码 - 添加简单图片验证码生成(4位字母+数字) - 添加验证码弹窗UI,用户体验友好 - 支持回车键提交验证码,点击刷新验证码 - 验证码5分钟有效期 技术实现: - 使用Pillow生成验证码图片,带干扰线和噪点 - Session存储验证码,一次性验证后自动清除 - 前端模态框设计,支持点击外部关闭 - 代码更简洁,维护成本更低 安全性: - 每次请求都需要人工验证 - 有效防止API滥用和批量调用 - 不依赖第三方服务,稳定可靠 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
133
app.py
133
app.py
@@ -1,6 +1,9 @@
|
||||
import os
|
||||
import markdown
|
||||
from flask import Flask, render_template, redirect, url_for, request, flash, jsonify
|
||||
import random
|
||||
import string
|
||||
from io import BytesIO
|
||||
from flask import Flask, render_template, redirect, url_for, request, flash, jsonify, session, send_file
|
||||
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
|
||||
from flask_admin import Admin, AdminIndexView, expose
|
||||
from flask_admin.contrib.sqla import ModelView
|
||||
@@ -10,7 +13,7 @@ from models import db, Site, Tag, Admin as AdminModel, News, site_tags, PromptTe
|
||||
from utils.website_fetcher import WebsiteFetcher
|
||||
from utils.tag_generator import TagGenerator
|
||||
from utils.news_searcher import NewsSearcher
|
||||
from utils.rate_limiter import get_rate_limiter, get_client_ip, CaptchaVerifier
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
def create_app(config_name='default'):
|
||||
"""应用工厂函数"""
|
||||
@@ -181,64 +184,105 @@ def create_app(config_name='default'):
|
||||
|
||||
return render_template('detail_new.html', site=site, news_list=news_list, has_news=has_news, recommended_sites=recommended_sites)
|
||||
|
||||
# ========== 验证码相关 (v2.6.1优化) ==========
|
||||
def generate_captcha_image(text):
|
||||
"""生成验证码图片"""
|
||||
# 创建图片 (宽120, 高40)
|
||||
width, height = 120, 40
|
||||
image = Image.new('RGB', (width, height), color=(255, 255, 255))
|
||||
draw = ImageDraw.Draw(image)
|
||||
|
||||
# 使用默认字体
|
||||
try:
|
||||
font = ImageFont.truetype("arial.ttf", 28)
|
||||
except:
|
||||
font = ImageFont.load_default()
|
||||
|
||||
# 添加随机干扰线
|
||||
for i in range(3):
|
||||
x1 = random.randint(0, width)
|
||||
y1 = random.randint(0, height)
|
||||
x2 = random.randint(0, width)
|
||||
y2 = random.randint(0, height)
|
||||
draw.line([(x1, y1), (x2, y2)], fill=(200, 200, 200), width=1)
|
||||
|
||||
# 绘制验证码文字
|
||||
for i, char in enumerate(text):
|
||||
x = 10 + i * 25
|
||||
y = random.randint(5, 12)
|
||||
color = (random.randint(0, 100), random.randint(0, 100), random.randint(0, 100))
|
||||
draw.text((x, y), char, font=font, fill=color)
|
||||
|
||||
# 添加随机噪点
|
||||
for _ in range(100):
|
||||
x = random.randint(0, width - 1)
|
||||
y = random.randint(0, height - 1)
|
||||
draw.point((x, y), fill=(random.randint(150, 200), random.randint(150, 200), random.randint(150, 200)))
|
||||
|
||||
return image
|
||||
|
||||
@app.route('/api/captcha', methods=['GET'])
|
||||
def get_captcha():
|
||||
"""生成验证码图片"""
|
||||
# 生成4位随机验证码
|
||||
captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
|
||||
|
||||
# 存储到session
|
||||
session['captcha'] = captcha_text
|
||||
session['captcha_created'] = datetime.now().timestamp()
|
||||
|
||||
# 生成图片
|
||||
image = generate_captcha_image(captcha_text)
|
||||
|
||||
# 转换为字节流
|
||||
img_io = BytesIO()
|
||||
image.save(img_io, 'PNG')
|
||||
img_io.seek(0)
|
||||
|
||||
return send_file(img_io, mimetype='image/png')
|
||||
|
||||
# ========== 新闻相关API (v2.6优化) ==========
|
||||
@app.route('/api/fetch-news/<code>', methods=['POST'])
|
||||
def fetch_news_for_site(code):
|
||||
"""
|
||||
按需获取指定网站的新闻
|
||||
v2.6优化:添加频率限制和验证码防护,避免API被滥用
|
||||
v2.6.1优化:所有手动请求都需要验证码,防止API滥用
|
||||
"""
|
||||
try:
|
||||
# 获取客户端IP
|
||||
client_ip = get_client_ip(request)
|
||||
# 获取请求数据
|
||||
data = request.get_json() or {}
|
||||
captcha_input = data.get('captcha', '').strip().upper()
|
||||
|
||||
# 获取频率限制器
|
||||
limiter = get_rate_limiter()
|
||||
# 验证验证码
|
||||
session_captcha = session.get('captcha', '').upper()
|
||||
captcha_created = session.get('captcha_created', 0)
|
||||
|
||||
# 检查是否需要验证码
|
||||
captcha_required, captcha_reason = limiter.is_captcha_required(client_ip)
|
||||
if captcha_required:
|
||||
# 检查验证码是否存在
|
||||
if not session_captcha:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': captcha_reason,
|
||||
'require_captcha': True
|
||||
}), 429
|
||||
'error': '请先获取验证码'
|
||||
}), 400
|
||||
|
||||
# 检查频率限制(每小时3次)
|
||||
is_limited, remaining, reset_time = limiter.is_rate_limited(
|
||||
client_ip,
|
||||
action='news_fetch',
|
||||
limit=3,
|
||||
window_minutes=60
|
||||
)
|
||||
|
||||
if is_limited:
|
||||
# 触发频率限制,要求验证码
|
||||
limiter.require_captcha(client_ip, duration_minutes=30)
|
||||
# 检查验证码是否过期(5分钟)
|
||||
if datetime.now().timestamp() - captcha_created > 300:
|
||||
session.pop('captcha', None)
|
||||
session.pop('captcha_created', None)
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'请求过于频繁,请在 {reset_time.strftime("%H:%M")} 后重试',
|
||||
'require_captcha': True,
|
||||
'reset_time': reset_time.isoformat()
|
||||
}), 429
|
||||
'error': '验证码已过期,请刷新后重试'
|
||||
}), 400
|
||||
|
||||
# 检查验证码(如果提供了)
|
||||
captcha_token = request.json.get('captcha_token') if request.json else None
|
||||
if captcha_token:
|
||||
# TODO: 配置实际的验证码服务(reCAPTCHA或hCaptcha)
|
||||
verifier = CaptchaVerifier(service='simple')
|
||||
success, error = verifier.verify(captcha_token, client_ip)
|
||||
if success:
|
||||
# 验证通过,清除验证码要求
|
||||
limiter.clear_captcha_requirement(client_ip)
|
||||
else:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'验证码验证失败: {error}'
|
||||
}), 400
|
||||
# 检查验证码是否正确
|
||||
if captcha_input != session_captcha:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': '验证码错误,请重新输入'
|
||||
}), 400
|
||||
|
||||
# 记录本次请求
|
||||
limiter.record_request(client_ip, action='news_fetch')
|
||||
# 验证通过,清除验证码
|
||||
session.pop('captcha', None)
|
||||
session.pop('captcha_created', None)
|
||||
|
||||
# 查找网站
|
||||
site = Site.query.filter_by(code=code, is_active=True).first_or_404()
|
||||
@@ -310,7 +354,6 @@ def create_app(config_name='default'):
|
||||
'success': True,
|
||||
'news': news_data,
|
||||
'new_count': new_count,
|
||||
'remaining_requests': remaining - 1, # 已经消耗了一次
|
||||
'message': f'成功获取{new_count}条新资讯' if new_count > 0 else '暂无新资讯'
|
||||
})
|
||||
|
||||
|
||||
@@ -794,7 +794,7 @@
|
||||
<span>📰</span>
|
||||
相关新闻
|
||||
</h2>
|
||||
<button id="refreshNewsBtn" class="refresh-news-btn" onclick="loadNews('{{ site.code }}', false)">
|
||||
<button id="refreshNewsBtn" class="refresh-news-btn" onclick="showCaptchaModal('{{ site.code }}')">
|
||||
<span class="refresh-icon">↻</span> <span class="btn-text">{% if has_news %}获取最新资讯{% else %}加载资讯{% endif %}</span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -852,6 +852,31 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 验证码弹窗 -->
|
||||
<div id="captchaModal" class="captcha-modal" style="display: none;">
|
||||
<div class="captcha-modal-content">
|
||||
<div class="captcha-modal-header">
|
||||
<h3>安全验证</h3>
|
||||
<button class="captcha-close-btn" onclick="closeCaptchaModal()">×</button>
|
||||
</div>
|
||||
<div class="captcha-modal-body">
|
||||
<p style="color: var(--text-secondary); margin-bottom: 20px; font-size: 14px;">为防止API滥用,请完成验证</p>
|
||||
<div class="captcha-image-container">
|
||||
<img id="captchaImage" src="" alt="验证码" style="width: 120px; height: 40px; border: 1px solid var(--border-color); border-radius: 4px; cursor: pointer;" onclick="refreshCaptcha()">
|
||||
<button type="button" onclick="refreshCaptcha()" style="margin-left: 10px; padding: 8px 12px; border: 1px solid var(--border-color); background: white; border-radius: 4px; cursor: pointer;">
|
||||
<span style="font-size: 16px;">↻</span>
|
||||
</button>
|
||||
</div>
|
||||
<input type="text" id="captchaInput" placeholder="请输入验证码" maxlength="4" style="width: 100%; padding: 10px; margin-top: 15px; border: 1px solid var(--border-color); border-radius: 6px; font-size: 14px;">
|
||||
<div id="captchaError" style="color: #ef4444; font-size: 12px; margin-top: 8px; display: none;"></div>
|
||||
</div>
|
||||
<div class="captcha-modal-footer">
|
||||
<button onclick="closeCaptchaModal()" class="captcha-btn captcha-btn-cancel">取消</button>
|
||||
<button onclick="submitCaptcha()" class="captcha-btn captcha-btn-submit">确定</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 侧边栏 -->
|
||||
<div class="sidebar-column">
|
||||
<!-- Similar Recommendations -->
|
||||
@@ -938,8 +963,59 @@
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// v2.6优化:按需加载新闻,避免自动调用API
|
||||
function loadNews(siteCode, isRefresh = false) {
|
||||
// v2.6.1优化:所有手动请求都需要验证码
|
||||
let currentSiteCode = '';
|
||||
|
||||
function showCaptchaModal(siteCode) {
|
||||
currentSiteCode = siteCode;
|
||||
const modal = document.getElementById('captchaModal');
|
||||
const input = document.getElementById('captchaInput');
|
||||
const error = document.getElementById('captchaError');
|
||||
|
||||
modal.style.display = 'flex';
|
||||
input.value = '';
|
||||
error.style.display = 'none';
|
||||
|
||||
// 加载验证码
|
||||
refreshCaptcha();
|
||||
}
|
||||
|
||||
function closeCaptchaModal() {
|
||||
document.getElementById('captchaModal').style.display = 'none';
|
||||
currentSiteCode = '';
|
||||
}
|
||||
|
||||
function refreshCaptcha() {
|
||||
const img = document.getElementById('captchaImage');
|
||||
img.src = '/api/captcha?' + new Date().getTime();
|
||||
}
|
||||
|
||||
function submitCaptcha() {
|
||||
const input = document.getElementById('captchaInput');
|
||||
const captcha = input.value.trim();
|
||||
|
||||
if (!captcha) {
|
||||
showCaptchaError('请输入验证码');
|
||||
return;
|
||||
}
|
||||
|
||||
if (captcha.length !== 4) {
|
||||
showCaptchaError('验证码为4位');
|
||||
return;
|
||||
}
|
||||
|
||||
// 关闭弹窗,开始加载新闻
|
||||
closeCaptchaModal();
|
||||
loadNewsWithCaptcha(currentSiteCode, captcha);
|
||||
}
|
||||
|
||||
function showCaptchaError(message) {
|
||||
const error = document.getElementById('captchaError');
|
||||
error.textContent = message;
|
||||
error.style.display = 'block';
|
||||
}
|
||||
|
||||
function loadNewsWithCaptcha(siteCode, captcha) {
|
||||
const btn = document.getElementById('refreshNewsBtn');
|
||||
const newsContainer = document.getElementById('newsContainer');
|
||||
|
||||
@@ -956,7 +1032,8 @@ function loadNews(siteCode, isRefresh = false) {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
},
|
||||
body: JSON.stringify({ captcha: captcha })
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
@@ -1054,6 +1131,28 @@ function showMessage(message, type = 'info') {
|
||||
setTimeout(() => messageDiv.remove(), 300);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// 支持回车键提交验证码
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const captchaInput = document.getElementById('captchaInput');
|
||||
if (captchaInput) {
|
||||
captchaInput.addEventListener('keypress', function(e) {
|
||||
if (e.key === 'Enter') {
|
||||
submitCaptcha();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 点击模态框外部关闭
|
||||
const modal = document.getElementById('captchaModal');
|
||||
if (modal) {
|
||||
modal.addEventListener('click', function(e) {
|
||||
if (e.target === modal) {
|
||||
closeCaptchaModal();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@@ -1424,4 +1523,124 @@ function shareToplatform() {
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
/* 验证码弹窗样式 */
|
||||
.captcha-modal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
|
||||
.captcha-modal-content {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
width: 90%;
|
||||
max-width: 400px;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
|
||||
animation: slideUp 0.3s ease;
|
||||
}
|
||||
|
||||
.captcha-modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.captcha-modal-header h3 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.captcha-close-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 28px;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.captcha-close-btn:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.captcha-modal-body {
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.captcha-image-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.captcha-modal-footer {
|
||||
padding: 16px 24px;
|
||||
border-top: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.captcha-btn {
|
||||
padding: 10px 24px;
|
||||
border-radius: 6px;
|
||||
border: none;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.captcha-btn-cancel {
|
||||
background: #f3f4f6;
|
||||
color: #374151;
|
||||
}
|
||||
|
||||
.captcha-btn-cancel:hover {
|
||||
background: #e5e7eb;
|
||||
}
|
||||
|
||||
.captcha-btn-submit {
|
||||
background: #0ea5e9;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.captcha-btn-submit:hover {
|
||||
background: #0284c7;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from {
|
||||
transform: translateY(20px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user