Compare commits
10 Commits
e656487d6d
...
6066ce4169
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6066ce4169 | ||
|
|
c681560f73 | ||
|
|
d71e46ecd0 | ||
|
|
40feb92473 | ||
|
|
881188587d | ||
|
|
982925b699 | ||
|
|
c9e11c4bd1 | ||
|
|
ae208d6b39 | ||
|
|
3eb0688460 | ||
|
|
91a9be0868 |
@@ -3,46 +3,75 @@ from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_login import LoginManager
|
||||
from flask_session import Session
|
||||
from flask_wtf.csrf import CSRFProtect
|
||||
from config import config
|
||||
from flask_bootstrap import Bootstrap
|
||||
import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
import glob
|
||||
|
||||
# 初始化扩展,但此时不传入 app
|
||||
# 初始化扩展
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
login_manager = LoginManager()
|
||||
sess = Session()
|
||||
csrf = CSRFProtect()
|
||||
bootstrap = Bootstrap()
|
||||
# login_manager 的基本配置
|
||||
login_manager.login_view = 'auth.login' # 后面我们会创建一个叫 'auth' 的蓝图
|
||||
login_manager.login_view = 'auth.login'
|
||||
|
||||
def create_app(config_name='default'):
|
||||
"""
|
||||
应用工厂函数
|
||||
:param config_name: 配置名称 ('development', 'production')
|
||||
:return: Flask app instance
|
||||
"""
|
||||
"""应用工厂函数,创建并配置Flask应用实例"""
|
||||
app = Flask(__name__)
|
||||
|
||||
# 1. 加载配置
|
||||
|
||||
# 加载配置
|
||||
app.config.from_object(config[config_name])
|
||||
config[config_name].init_app(app)
|
||||
# 2. 初始化扩展
|
||||
# 配置代理转发
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
|
||||
|
||||
# 初始化扩展
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
login_manager.init_app(app)
|
||||
sess.init_app(app)
|
||||
csrf.init_app(app)
|
||||
bootstrap.init_app(app)
|
||||
|
||||
# 注册自定义过滤器
|
||||
from .filters import translate_status
|
||||
app.jinja_env.filters['translate_status'] = translate_status
|
||||
# 配置日志
|
||||
if not os.path.exists('logs'):
|
||||
os.mkdir('logs')
|
||||
|
||||
# 3. 注册蓝图 (Blueprint)
|
||||
# 后面我们会在这里添加蓝图
|
||||
# 清理过期日志
|
||||
log_retention_days = int(os.environ.get('LOG_RETENTION_DAYS', 7))
|
||||
cutoff_time = datetime.now() - timedelta(days=log_retention_days)
|
||||
for log_file in glob.glob('logs/*.log*'):
|
||||
if os.path.getmtime(log_file) < cutoff_time.timestamp():
|
||||
os.remove(log_file)
|
||||
|
||||
file_handler = RotatingFileHandler('logs/pt_blacklist.log', maxBytes=10240000, backupCount=10)
|
||||
file_handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
|
||||
))
|
||||
file_handler.setLevel(logging.INFO)
|
||||
app.logger.addHandler(file_handler)
|
||||
app.logger.setLevel(logging.INFO)
|
||||
app.logger.info('PT黑名单系统启动')
|
||||
|
||||
# 注册自定义过滤器
|
||||
from .filters import translate_status, translate_reason, translate_reasons_list, to_beijing_time
|
||||
app.jinja_env.filters['translate_status'] = translate_status
|
||||
app.jinja_env.filters['translate_reason'] = translate_reason
|
||||
app.jinja_env.filters['translate_reasons_list'] = translate_reasons_list
|
||||
app.jinja_env.filters['to_beijing_time'] = to_beijing_time
|
||||
|
||||
# 注册蓝图
|
||||
from .routes import main as main_blueprint
|
||||
app.register_blueprint(main_blueprint)
|
||||
|
||||
|
||||
from .auth import auth as auth_blueprint
|
||||
app.register_blueprint(auth_blueprint, url_prefix='/auth')
|
||||
|
||||
|
||||
return app
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from flask import render_template, redirect, url_for, flash, request
|
||||
from flask import render_template, redirect, url_for, flash, request, current_app
|
||||
from flask_login import login_user, logout_user, login_required, current_user
|
||||
from . import auth
|
||||
from .. import db
|
||||
@@ -7,6 +7,7 @@ from ..forms import LoginForm, RegistrationForm
|
||||
|
||||
@auth.route('/register', methods=['GET', 'POST'])
|
||||
def register():
|
||||
"""用户注册"""
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for('main.index'))
|
||||
form = RegistrationForm()
|
||||
@@ -18,36 +19,43 @@ def register():
|
||||
username=form.username.data,
|
||||
pt_site=form.pt_site.data,
|
||||
uid=form.uid.data,
|
||||
status='pending' # 新用户需要管理员审核
|
||||
status='pending'
|
||||
)
|
||||
user.set_password(form.password.data)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'新用户注册: {user.username} ({user.email}) - 站点: {user.pt_site}')
|
||||
flash('注册申请已提交,请等待管理员审核。', 'info')
|
||||
return redirect(url_for('auth.login'))
|
||||
return render_template('auth/register.html', form=form)
|
||||
|
||||
@auth.route('/login', methods=['GET', 'POST'])
|
||||
def login():
|
||||
"""用户登录"""
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for('main.index'))
|
||||
form = LoginForm()
|
||||
if form.validate_on_submit():
|
||||
user = User.query.filter_by(email=form.email.data).first()
|
||||
if user is None or not user.check_password(form.password.data):
|
||||
current_app.logger.warning(f'登录失败: {form.email.data} - 无效的邮箱或密码')
|
||||
flash('无效的邮箱或密码。', 'danger')
|
||||
return redirect(url_for('auth.login'))
|
||||
|
||||
|
||||
if user.status != 'active':
|
||||
current_app.logger.warning(f'登录失败: {user.username} - 账户状态: {user.status}')
|
||||
flash(f'您的账户当前状态为 "{user.status}",无法登录。请联系管理员。', 'warning')
|
||||
return redirect(url_for('auth.login'))
|
||||
login_user(user, remember=form.remember_me.data)
|
||||
current_app.logger.info(f'用户登录: {user.username} ({user.email})')
|
||||
return redirect(url_for('main.index'))
|
||||
return render_template('auth/login.html', form=form)
|
||||
|
||||
@auth.route('/logout')
|
||||
@login_required
|
||||
def logout():
|
||||
"""用户登出"""
|
||||
current_app.logger.info(f'用户登出: {current_user.username}')
|
||||
logout_user()
|
||||
flash('您已成功登出。')
|
||||
return redirect(url_for('main.index'))
|
||||
|
||||
@@ -1,27 +1,26 @@
|
||||
"""权限装饰器"""
|
||||
from functools import wraps
|
||||
from flask import abort
|
||||
from flask_login import current_user
|
||||
|
||||
def admin_required(f):
|
||||
"""仅管理员可访问"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if not current_user.is_authenticated or current_user.role != 'admin':
|
||||
abort(403) # HTTP 403 Forbidden error
|
||||
abort(403)
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
# === 修正后的通用权限装饰器 ===
|
||||
def permission_required(*roles):
|
||||
"""指定角色可访问"""
|
||||
def decorator(f):
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if not current_user.is_authenticated:
|
||||
abort(401) # Unauthorized
|
||||
abort(401)
|
||||
if current_user.role not in roles:
|
||||
abort(403) # Forbidden
|
||||
abort(403)
|
||||
return f(*args, **kwargs)
|
||||
|
||||
# 正确的返回:返回包含了权限检查逻辑的包装函数
|
||||
return decorated_function # <--- 已修正
|
||||
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
@@ -1,27 +1,54 @@
|
||||
# app/filters.py
|
||||
# 状态翻译过滤器
|
||||
"""Jinja2模板过滤器"""
|
||||
from datetime import timedelta
|
||||
|
||||
STATUS_TRANSLATIONS = {
|
||||
# 举报状态
|
||||
'pending': '待审核',
|
||||
'in_review': '审核中',
|
||||
'approved': '已批准',
|
||||
'rejected': '已驳回',
|
||||
'revoked': '已撤销',
|
||||
'overturned': '已推翻',
|
||||
|
||||
# 申诉状态
|
||||
'awaiting_admin_reply': '等待管理员回复',
|
||||
'awaiting_user_reply': '等待用户回复',
|
||||
|
||||
# 用户状态
|
||||
'active': '正常',
|
||||
'disabled': '已禁用',
|
||||
|
||||
# 黑名单状态
|
||||
'expired': '已过期'
|
||||
}
|
||||
|
||||
REASON_TRANSLATIONS = {
|
||||
'cheating': '作弊 (刷上传/下载)',
|
||||
'trading': '账号交易/共享',
|
||||
'no_data': '注册后无数据',
|
||||
'failed_assessment': '考核未通过',
|
||||
'spam': '发布垃圾/违禁信息',
|
||||
'abusive': '辱骂/人身攻击',
|
||||
'low_ratio': '分享率过低',
|
||||
'hit_and_run': 'H&R (下载不做种)',
|
||||
'fake_seeding': '假做种',
|
||||
'multiple_accounts': '多账号/小号',
|
||||
'account_sharing': '账号共享',
|
||||
'reselling': '倒卖邀请',
|
||||
'harassment': '骚扰他人',
|
||||
'scamming': '诈骗行为',
|
||||
'other': '其他 (请在描述中详述)'
|
||||
}
|
||||
|
||||
def translate_status(status):
|
||||
"""将英文状态翻译为中文"""
|
||||
"""状态翻译过滤器"""
|
||||
return STATUS_TRANSLATIONS.get(status, status)
|
||||
|
||||
def translate_reason(reason):
|
||||
"""违规原因翻译过滤器"""
|
||||
return REASON_TRANSLATIONS.get(reason, reason)
|
||||
|
||||
def translate_reasons_list(reasons):
|
||||
"""违规原因列表翻译过滤器"""
|
||||
if not reasons:
|
||||
return []
|
||||
return [REASON_TRANSLATIONS.get(r, r) for r in reasons]
|
||||
|
||||
def to_beijing_time(utc_dt):
|
||||
"""UTC时间转北京时间(UTC+8)"""
|
||||
if utc_dt is None:
|
||||
return None
|
||||
return utc_dt + timedelta(hours=8)
|
||||
|
||||
22
app/forms.py
22
app/forms.py
@@ -3,9 +3,7 @@ from wtforms import StringField, SubmitField, PasswordField, BooleanField, TextA
|
||||
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError, Optional, URL
|
||||
from .models import User
|
||||
from wtforms_sqlalchemy.fields import QuerySelectField
|
||||
|
||||
def get_active_partner_sites():
|
||||
return PartnerSite.query.filter_by(is_active=True).order_by(PartnerSite.name)
|
||||
from .filters import REASON_TRANSLATIONS
|
||||
|
||||
class SearchForm(FlaskForm):
|
||||
search_term = StringField(
|
||||
@@ -38,11 +36,6 @@ class LoginForm(FlaskForm):
|
||||
remember_me = BooleanField('记住我')
|
||||
submit = SubmitField('登录')
|
||||
class ReportForm(FlaskForm):
|
||||
# reported_pt_site = StringField(
|
||||
# '被举报用户所在的 PT 站点',
|
||||
# validators=[DataRequired(), Length(min=2, max=100)],
|
||||
# render_kw={"placeholder": "例如:some.site.com"}
|
||||
# )
|
||||
reported_pt_site = SelectField('违规站点', validators=[DataRequired()])
|
||||
reported_username = StringField(
|
||||
'被举报的用户名',
|
||||
@@ -56,14 +49,7 @@ class ReportForm(FlaskForm):
|
||||
)
|
||||
reason_category = SelectField(
|
||||
'举报原因分类',
|
||||
choices=[
|
||||
('cheating', '作弊 (刷上传/下载)'),
|
||||
('trading', '账号交易/共享'),
|
||||
('spam', '发布垃圾/违禁信息'),
|
||||
('abusive', '辱骂/人身攻击'),
|
||||
('radio', '分享率过低'),
|
||||
('other', '其他 (请在描述中详述)')
|
||||
],
|
||||
choices=[(k, v) for k, v in REASON_TRANSLATIONS.items()],
|
||||
validators=[DataRequired()]
|
||||
)
|
||||
description = TextAreaField(
|
||||
@@ -88,8 +74,8 @@ class UpdateUserForm(FlaskForm):
|
||||
], validators=[DataRequired()])
|
||||
|
||||
status = SelectField('状态', choices=[
|
||||
('active', '激活 (Active)'),
|
||||
('disabled', '禁用 (Disabled)')
|
||||
('active', '正常'),
|
||||
('disabled', '已禁用')
|
||||
], validators=[DataRequired()])
|
||||
|
||||
submit = SubmitField('更新')
|
||||
|
||||
@@ -4,6 +4,7 @@ from werkzeug.security import generate_password_hash, check_password_hash
|
||||
from app import db, login_manager
|
||||
|
||||
class PartnerSite(db.Model):
|
||||
"""合作PT站点模型"""
|
||||
__tablename__ = 'partner_sites'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
name = db.Column(db.String(100), unique=True, nullable=False, index=True)
|
||||
@@ -14,20 +15,23 @@ class PartnerSite(db.Model):
|
||||
|
||||
def __repr__(self):
|
||||
return f'<PartnerSite {self.name}>'
|
||||
|
||||
class User(UserMixin, db.Model):
|
||||
"""用户模型"""
|
||||
__tablename__ = 'users'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
username = db.Column(db.String(64), unique=True, index=True, nullable=False)
|
||||
email = db.Column(db.String(120), unique=True, index=True, nullable=False)
|
||||
password_hash = db.Column(db.String(256))
|
||||
role = db.Column(db.String(16), default='user', index=True) # 'user', 'admin', 'trust_user'
|
||||
status = db.Column(db.String(16), default='pending', index=True) # 'pending', 'active', 'disabled'
|
||||
role = db.Column(db.String(16), default='user', index=True)
|
||||
status = db.Column(db.String(16), default='pending', index=True)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
pt_site = db.Column(db.String(100)) # 注册时填写的站点
|
||||
uid = db.Column(db.String(50)) # 注册时填写的 UID
|
||||
pt_site = db.Column(db.String(100))
|
||||
uid = db.Column(db.String(50))
|
||||
reports = db.relationship('Report', backref='reporter', lazy='dynamic')
|
||||
comments = db.relationship('Comment', back_populates='author', lazy='dynamic')
|
||||
|
||||
def set_password(self, password):
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@@ -42,6 +46,7 @@ def load_user(user_id):
|
||||
return User.query.get(int(user_id))
|
||||
|
||||
class Report(db.Model):
|
||||
"""举报模型"""
|
||||
__tablename__ = 'reports'
|
||||
__table_args__ = (
|
||||
db.Index('idx_report_status_created', 'status', 'created_at'),
|
||||
@@ -52,24 +57,24 @@ class Report(db.Model):
|
||||
reported_pt_site = db.Column(db.String(100), nullable=False)
|
||||
reported_username = db.Column(db.String(50))
|
||||
reported_email = db.Column(db.String(120), index=True, nullable=False)
|
||||
reason_category = db.Column(db.String(16), nullable=False) # 'cheating', 'trading', 'spam', 'abusive', 'radio', 'other'
|
||||
reason_category = db.Column(db.String(16), nullable=False)
|
||||
description = db.Column(db.Text, nullable=False)
|
||||
status = db.Column(db.String(16), index=True, default='pending') # 'pending', 'approved', 'rejected', 'revoked', 'overturned'
|
||||
status = db.Column(db.String(16), index=True, default='pending')
|
||||
created_at = db.Column(db.DateTime, index=True, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
comments = db.relationship('Comment', backref='report', lazy='dynamic', cascade='all, delete-orphan')
|
||||
evidences = db.relationship('Evidence', backref='report', lazy='dynamic', cascade='all, delete-orphan')
|
||||
blacklist_entry = db.relationship('Blacklist', backref='report', uselist=False)
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Report {self.id}>'
|
||||
|
||||
class Evidence(db.Model):
|
||||
"""证据模型"""
|
||||
__tablename__ = 'evidences'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
report_id = db.Column(db.Integer, db.ForeignKey('reports.id', ondelete='CASCADE'), nullable=False)
|
||||
file_url = db.Column(db.String(1024), nullable=False) # 存储OSS或本地路径
|
||||
file_type = db.Column(db.String(16)) # 'image', 'zip', 'text', 'image_url'
|
||||
file_url = db.Column(db.String(1024), nullable=False)
|
||||
file_type = db.Column(db.String(16))
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
@@ -77,6 +82,7 @@ class Evidence(db.Model):
|
||||
return f'<Evidence {self.id} for Report {self.report_id}>'
|
||||
|
||||
class Blacklist(db.Model):
|
||||
"""黑名单模型"""
|
||||
__tablename__ = 'blacklist'
|
||||
__table_args__ = (
|
||||
db.Index('idx_blacklist_email_status', 'normalized_email', 'status'),
|
||||
@@ -86,18 +92,21 @@ class Blacklist(db.Model):
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
username = db.Column(db.String(64), index=True)
|
||||
email = db.Column(db.String(120), index=True)
|
||||
normalized_email = db.Column(db.String(120), index=True) # 归一化后的邮箱
|
||||
normalized_email = db.Column(db.String(120), index=True)
|
||||
pt_site = db.Column(db.String(100), index=True)
|
||||
uid = db.Column(db.String(50))
|
||||
report_id = db.Column(db.Integer, db.ForeignKey('reports.id'), unique=True) # 确保一个举报只对应一个黑名单条目
|
||||
status = db.Column(db.String(16), default='active', index=True) # 'active', 'revoked', 'expired'
|
||||
report_ids = db.Column(db.JSON, default=list, nullable=False)
|
||||
reason_categories = db.Column(db.JSON, default=list, nullable=False)
|
||||
status = db.Column(db.String(16), default='active', index=True)
|
||||
created_at = db.Column(db.DateTime, index=True, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
appeals = db.relationship('Appeal', backref='blacklist_entry', lazy='dynamic')
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Blacklist {self.normalized_email} on {self.pt_site}>'
|
||||
|
||||
class Comment(db.Model):
|
||||
"""评论模型"""
|
||||
__tablename__ = 'comments'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
body = db.Column(db.Text)
|
||||
@@ -105,26 +114,30 @@ class Comment(db.Model):
|
||||
author_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))
|
||||
report_id = db.Column(db.Integer, db.ForeignKey('reports.id', ondelete='CASCADE'))
|
||||
author = db.relationship('User', back_populates='comments')
|
||||
|
||||
class Appeal(db.Model):
|
||||
"""申诉模型"""
|
||||
__tablename__ = 'appeals'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
reason = db.Column(db.Text, nullable=False) # 用户最初的申诉理由
|
||||
status = db.Column(db.String(32), nullable=False, default='awaiting_admin_reply', index=True) # 'awaiting_admin_reply', 'awaiting_user_reply', 'approved', 'rejected'
|
||||
reason = db.Column(db.Text, nullable=False)
|
||||
status = db.Column(db.String(32), nullable=False, default='awaiting_admin_reply', index=True)
|
||||
created_at = db.Column(db.DateTime, index=True, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
appealer_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE')) # 申诉人
|
||||
blacklist_entry_id = db.Column(db.Integer, db.ForeignKey('blacklist.id', ondelete='SET NULL')) # 关联的黑名单条目
|
||||
appealer_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))
|
||||
blacklist_entry_id = db.Column(db.Integer, db.ForeignKey('blacklist.id', ondelete='SET NULL'))
|
||||
messages = db.relationship('AppealMessage', backref='appeal', lazy='dynamic', cascade='all, delete-orphan')
|
||||
appealer = db.relationship('User', backref='appeals')
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Appeal {self.id}>'
|
||||
|
||||
class AppealMessage(db.Model):
|
||||
"""申诉消息模型"""
|
||||
__tablename__ = 'appeal_messages'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
body = db.Column(db.Text, nullable=False)
|
||||
created_at = db.Column(db.DateTime, index=True, default=datetime.utcnow)
|
||||
author_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE')) # 消息发送者
|
||||
author_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))
|
||||
appeal_id = db.Column(db.Integer, db.ForeignKey('appeals.id', ondelete='CASCADE'))
|
||||
author = db.relationship('User', backref='appeal_messages')
|
||||
|
||||
|
||||
272
app/routes.py
272
app/routes.py
@@ -1,8 +1,9 @@
|
||||
from flask import abort, Blueprint, render_template, request, flash,redirect, url_for
|
||||
from flask import abort, Blueprint, render_template, request, flash, redirect, url_for, current_app
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
from flask_login import login_required, current_user
|
||||
from app import db
|
||||
from app.forms import SearchForm, ReportForm, ReportForm, UpdateUserForm, CommentForm, RevokeForm, AppealForm, AppealMessageForm, PartnerSiteForm
|
||||
from app.forms import SearchForm, ReportForm, UpdateUserForm, CommentForm, RevokeForm, AppealForm, AppealMessageForm, PartnerSiteForm
|
||||
from app.models import Blacklist, Report, Evidence, User, Comment, AppealMessage, Appeal, PartnerSite
|
||||
from app.decorators import admin_required, permission_required
|
||||
from app.services.email_normalizer import normalize_email
|
||||
@@ -11,45 +12,56 @@ main = Blueprint('main', __name__)
|
||||
|
||||
@main.route('/', methods=['GET', 'POST'])
|
||||
def index():
|
||||
"""首页 - 黑名单查询"""
|
||||
form = SearchForm()
|
||||
search_result = None
|
||||
searched = False
|
||||
if form.validate_on_submit():
|
||||
# 在处理表单之前,检查用户是否已登录
|
||||
if not current_user.is_authenticated:
|
||||
flash('请登录后才能使用查询功能。', 'warning')
|
||||
# 重定向到登录页面,或者直接返回首页
|
||||
return redirect(url_for('main.index'))
|
||||
|
||||
# 如果用户已登录,则执行以下查询逻辑
|
||||
|
||||
searched = True
|
||||
search_term = form.search_term.data
|
||||
normalized_email = normalize_email(search_term)
|
||||
|
||||
search_result = Blacklist.query.join(Report).filter(
|
||||
|
||||
search_result = Blacklist.query.filter(
|
||||
or_(
|
||||
Blacklist.normalized_email == normalized_email,
|
||||
Blacklist.username == search_term
|
||||
),
|
||||
Blacklist.status == 'active',
|
||||
Report.status == 'approved'
|
||||
Blacklist.status == 'active'
|
||||
).first()
|
||||
|
||||
|
||||
if search_result:
|
||||
current_app.logger.info(f'黑名单查询命中: {search_term} by {current_user.username}')
|
||||
flash(f'警告: 查询到与 "{search_term}" 相关的公开不良记录。详情如下。', 'warning')
|
||||
else:
|
||||
current_app.logger.info(f'黑名单查询未命中: {search_term} by {current_user.username}')
|
||||
flash(f'未查询到与 "{search_term}" 相关的公开不良记录。', 'info')
|
||||
|
||||
|
||||
return render_template('index.html', form=form, search_result=search_result, searched=searched, Appeal=Appeal)
|
||||
|
||||
@main.route('/report/new', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def create_report():
|
||||
"""创建新举报"""
|
||||
if current_user.status != 'active':
|
||||
flash('您的账户尚未激活,无法提交举报。请等待管理员审核。', 'warning')
|
||||
return redirect(url_for('main.index'))
|
||||
form = ReportForm()
|
||||
active_sites = PartnerSite.query.filter_by(is_active=True).order_by(PartnerSite.name).all()
|
||||
form.reported_pt_site.choices = [(site.name, site.name) for site in active_sites]
|
||||
if form.validate_on_submit():
|
||||
# 1. 创建 Report 对象
|
||||
existing_report = Report.query.filter_by(
|
||||
reported_email=form.reported_email.data,
|
||||
status='pending'
|
||||
).first()
|
||||
if existing_report:
|
||||
current_app.logger.warning(f'重复举报: {form.reported_email.data} by {current_user.username}')
|
||||
flash(f'该邮箱已有待审核的举报 (#{existing_report.id}),请勿重复提交。', 'warning')
|
||||
return render_template('create_report.html', form=form)
|
||||
|
||||
new_report = Report(
|
||||
reporter_id=current_user.id,
|
||||
reported_pt_site=form.reported_pt_site.data,
|
||||
@@ -60,60 +72,59 @@ def create_report():
|
||||
status='pending'
|
||||
)
|
||||
db.session.add(new_report)
|
||||
|
||||
# 2. 处理证据链接
|
||||
|
||||
urls_text = form.evidences.data
|
||||
# 按行分割,并移除空白行和首尾空格
|
||||
evidence_urls = [url.strip() for url in urls_text.strip().splitlines() if url.strip()]
|
||||
if not evidence_urls:
|
||||
flash('必须提供至少一个有效的证据链接。', 'danger')
|
||||
return render_template('create_report.html', form=form)
|
||||
# 对每个 URL 进行简单的验证和保存
|
||||
|
||||
valid_extensions = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp')
|
||||
for url in evidence_urls:
|
||||
if url.lower().startswith(('http://', 'https://')) and url.lower().endswith(valid_extensions):
|
||||
evidence = Evidence(
|
||||
file_url=url,
|
||||
file_type='image_url', # 标记类型为图片链接
|
||||
file_url=url,
|
||||
file_type='image_url',
|
||||
report=new_report
|
||||
)
|
||||
db.session.add(evidence)
|
||||
else:
|
||||
# 如果有任何一个链接格式不正确,则回滚并提示用户
|
||||
db.session.rollback()
|
||||
current_app.logger.error(f'无效证据链接: {url[:50]} by {current_user.username}')
|
||||
flash(f'链接 "{url[:50]}..." 格式不正确或不是支持的图片格式。请提供以 http/https 开头,以 .png, .jpg 等结尾的图片链接。', 'danger')
|
||||
return render_template('create_report.html', form=form)
|
||||
|
||||
# 3. 提交到数据库
|
||||
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'新举报提交: #{new_report.id} - {form.reported_email.data} by {current_user.username}')
|
||||
flash('举报提交成功,请等待管理员审核。', 'success')
|
||||
return redirect(url_for('main.index'))
|
||||
|
||||
|
||||
return render_template('create_report.html', form=form)
|
||||
|
||||
@main.route('/admin/reports')
|
||||
@login_required
|
||||
@permission_required('admin', 'trust_user')
|
||||
def report_list():
|
||||
# 获取页码,默认为第一页
|
||||
"""举报列表(管理员/信任用户)"""
|
||||
page = request.args.get('page', 1, type=int)
|
||||
# 查询举报,按创建时间倒序排列,并进行分页
|
||||
# 每页显示 20 条记录
|
||||
query = Report.query
|
||||
if current_user.role == 'trust_user':
|
||||
query = query.filter_by(status='pending')
|
||||
reports_pagination = query.order_by(Report.created_at.desc()).paginate(
|
||||
page=page, per_page=20, error_out=False
|
||||
)
|
||||
return render_template(
|
||||
'admin/report_list.html',
|
||||
reports=reports_pagination
|
||||
)
|
||||
return render_template('admin/report_list.html', reports=reports_pagination)
|
||||
@main.route('/report/<int:report_id>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@permission_required('admin', 'trust_user') # 允许 admin 和 trust_user 访问
|
||||
def report_detail(report_id):
|
||||
"""举报详情"""
|
||||
report = Report.query.get_or_404(report_id)
|
||||
|
||||
# 权限检查:管理员、信任用户、或举报提交者本人可以查看
|
||||
if current_user.role not in ['admin', 'trust_user'] and report.reporter_id != current_user.id:
|
||||
flash('您无权查看此举报。', 'warning')
|
||||
return redirect(url_for('main.index'))
|
||||
|
||||
if current_user.role == 'trust_user' and report.status != 'pending':
|
||||
flash('您无权查看已处理的举报。', 'warning')
|
||||
return redirect(url_for('main.report_list'))
|
||||
@@ -130,24 +141,29 @@ def report_detail(report_id):
|
||||
)
|
||||
db.session.add(comment)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'举报评论: #{report.id} by {current_user.username}')
|
||||
flash('你的审核建议已成功提交。', 'success')
|
||||
return redirect(url_for('main.report_detail', report_id=report.id))
|
||||
|
||||
|
||||
comments = report.comments.order_by(Comment.created_at.desc()).all()
|
||||
|
||||
related_reports = Report.query.filter(
|
||||
Report.reported_email == report.reported_email,
|
||||
Report.id != report.id
|
||||
).order_by(Report.created_at.desc()).all()
|
||||
|
||||
return render_template(
|
||||
'admin/report_detail.html',
|
||||
report=report,
|
||||
form=comment_form,
|
||||
'admin/report_detail.html',
|
||||
report=report,
|
||||
form=comment_form,
|
||||
revoke_form=revoke_form,
|
||||
comments=comments
|
||||
comments=comments,
|
||||
related_reports=related_reports
|
||||
)
|
||||
# === 独立的举报处理视图 (仅限 Admin) ===
|
||||
# 这个视图只处理动作,不渲染页面。它接收来自详情页按钮的 POST 请求。
|
||||
@main.route('/admin/report/<int:report_id>/process', methods=['POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
def process_report(report_id):
|
||||
"""处理举报(批准/驳回)"""
|
||||
report = Report.query.get_or_404(report_id)
|
||||
action = request.form.get('action')
|
||||
|
||||
@@ -157,26 +173,64 @@ def process_report(report_id):
|
||||
|
||||
if action == 'confirm':
|
||||
report.status = 'approved'
|
||||
# 检查是否已在黑名单中
|
||||
existing_blacklist = Blacklist.query.filter_by(report_id=report.id).first()
|
||||
normalized = normalize_email(report.reported_email)
|
||||
existing_blacklist = Blacklist.query.filter_by(normalized_email=normalized, status='active').first()
|
||||
|
||||
if not existing_blacklist:
|
||||
# 创建新的黑名单记录
|
||||
new_blacklist_entry = Blacklist(
|
||||
email=report.reported_email,
|
||||
normalized_email=normalize_email(report.reported_email),
|
||||
normalized_email=normalized,
|
||||
pt_site=report.reported_pt_site,
|
||||
uid=report.reported_username,
|
||||
report_id=report.id,
|
||||
report_ids=[report.id],
|
||||
reason_categories=[report.reason_category],
|
||||
username=report.reported_username or None
|
||||
)
|
||||
db.session.add(new_blacklist_entry)
|
||||
current_app.logger.info(f'举报批准: #{report.id} - {report.reported_email} by {current_user.username}')
|
||||
flash('举报已批准,并已将相关信息添加到黑名单。', 'success')
|
||||
else:
|
||||
flash('举报状态已更新为“批准”。该举报已在黑名单中,无需重复添加。', 'info')
|
||||
if report.reason_category not in existing_blacklist.reason_categories:
|
||||
existing_blacklist.reason_categories.append(report.reason_category)
|
||||
existing_blacklist.report_ids.append(report.id)
|
||||
flag_modified(existing_blacklist, 'reason_categories')
|
||||
flag_modified(existing_blacklist, 'report_ids')
|
||||
current_app.logger.info(f'举报合并: #{report.id} 合并到黑名单#{existing_blacklist.id} - 新增原因: {report.reason_category}')
|
||||
flash(f'举报已批准并合并到现有黑名单记录(新增违规原因:{report.reason_category})。', 'success')
|
||||
else:
|
||||
current_app.logger.info(f'举报批准: #{report.id} - 相同原因已存在,不合并')
|
||||
flash('举报已批准。该用户已有相同违规原因的记录,未进行合并。', 'info')
|
||||
|
||||
other_pending = Report.query.filter(
|
||||
Report.reported_email == report.reported_email,
|
||||
Report.id != report.id,
|
||||
Report.status == 'pending'
|
||||
).all()
|
||||
|
||||
merged_count = 0
|
||||
for other_report in other_pending:
|
||||
other_report.status = 'approved'
|
||||
bl = existing_blacklist or new_blacklist_entry
|
||||
if other_report.reason_category not in bl.reason_categories:
|
||||
bl.reason_categories.append(other_report.reason_category)
|
||||
bl.report_ids.append(other_report.id)
|
||||
flag_modified(bl, 'reason_categories')
|
||||
flag_modified(bl, 'report_ids')
|
||||
merged_count += 1
|
||||
comment = Comment(
|
||||
body=f'该举报已自动批准(关联举报 #{report.id} 已确认违规)',
|
||||
report=other_report,
|
||||
author=current_user._get_current_object()
|
||||
)
|
||||
db.session.add(comment)
|
||||
|
||||
if other_pending:
|
||||
current_app.logger.info(f'自动批准关联举报: {len(other_pending)}个,合并{merged_count}个不同原因')
|
||||
flash(f'同时自动处理了 {len(other_pending)} 个相关举报(其中 {merged_count} 个不同原因已合并)。', 'info')
|
||||
elif action == 'invalidate':
|
||||
report.status = 'rejected'
|
||||
flash('举报状态已更新为“无效”。', 'success')
|
||||
|
||||
current_app.logger.info(f'举报驳回: #{report.id} by {current_user.username}')
|
||||
flash('举报状态已更新为"无效"。', 'success')
|
||||
else:
|
||||
flash('无效的操作。', 'danger')
|
||||
db.session.commit()
|
||||
@@ -185,44 +239,49 @@ def process_report(report_id):
|
||||
@login_required
|
||||
@admin_required
|
||||
def revoke_report(report_id):
|
||||
"""撤销已批准的举报"""
|
||||
report = Report.query.get_or_404(report_id)
|
||||
# 只有已批准的举报才能被撤销
|
||||
if report.status != 'approved':
|
||||
flash('错误:只有已批准的举报才能被撤销。', 'danger')
|
||||
return redirect(url_for('main.report_detail', report_id=report.id))
|
||||
form = RevokeForm()
|
||||
if form.validate_on_submit():
|
||||
# 1. 从黑名单中移除
|
||||
blacklist_entry = Blacklist.query.filter_by(report_id=report.id).first()
|
||||
if blacklist_entry:
|
||||
db.session.delete(blacklist_entry)
|
||||
|
||||
# 2. 更新举报状态
|
||||
normalized = normalize_email(report.reported_email)
|
||||
blacklist_entry = Blacklist.query.filter_by(normalized_email=normalized, status='active').first()
|
||||
|
||||
if blacklist_entry and report.id in blacklist_entry.report_ids:
|
||||
blacklist_entry.report_ids.remove(report.id)
|
||||
if report.reason_category in blacklist_entry.reason_categories:
|
||||
blacklist_entry.reason_categories.remove(report.reason_category)
|
||||
flag_modified(blacklist_entry, 'report_ids')
|
||||
flag_modified(blacklist_entry, 'reason_categories')
|
||||
|
||||
if len(blacklist_entry.report_ids) == 0:
|
||||
db.session.delete(blacklist_entry)
|
||||
current_app.logger.warning(f'举报撤销: #{report.id} - 黑名单记录已删除')
|
||||
flash('举报已成功撤销,并已从黑名单中移除。', 'success')
|
||||
else:
|
||||
current_app.logger.warning(f'举报撤销: #{report.id} - 从黑名单中移除该举报')
|
||||
flash(f'举报已成功撤销,已从黑名单中移除该违规原因(剩余 {len(blacklist_entry.report_ids)} 个举报)。', 'success')
|
||||
|
||||
report.status = 'revoked'
|
||||
|
||||
# 3. 将撤销理由记录为一条特殊的评论(审计日志)
|
||||
revocation_comment = Comment(
|
||||
body=f"[系统操作:撤销批准]\n理由:{form.reason.data}",
|
||||
report=report,
|
||||
author=current_user._get_current_object()
|
||||
)
|
||||
db.session.add(revocation_comment)
|
||||
|
||||
db.session.commit()
|
||||
flash('举报已成功撤销,并已从黑名单中移除。', 'success')
|
||||
current_app.logger.warning(f'举报撤销: #{report.id} by {current_user.username} - 理由: {form.reason.data[:50]}')
|
||||
else:
|
||||
# 如果表单验证失败(例如理由为空),显示错误信息
|
||||
flash('撤销失败:' + ' '.join(form.reason.errors), 'danger')
|
||||
return redirect(url_for('main.report_detail', report_id=report.id))
|
||||
@main.route('/admin/users')
|
||||
@login_required
|
||||
@admin_required
|
||||
def manage_users():
|
||||
# 查询所有非待审核的用户
|
||||
"""用户管理"""
|
||||
users = User.query.filter(User.status != 'pending').order_by(User.created_at.desc()).all()
|
||||
|
||||
# 为每个用户创建一个预填充了当前数据的表单实例
|
||||
# 这样在模板中可以直接渲染,并且下拉框会默认选中用户的当前角色/状态
|
||||
forms = {}
|
||||
for user in users:
|
||||
forms[user.id] = UpdateUserForm(obj=user)
|
||||
@@ -231,13 +290,13 @@ def manage_users():
|
||||
@login_required
|
||||
@admin_required
|
||||
def update_user(user_id):
|
||||
"""更新用户角色和状态"""
|
||||
if user_id == 1:
|
||||
flash('错误:禁止修改初始管理员账户的角色和状态。', 'danger')
|
||||
return redirect(url_for('main.manage_users'))
|
||||
user = User.query.get_or_404(user_id)
|
||||
form = UpdateUserForm() # 创建一个空的表单来接收 POST 数据
|
||||
form = UpdateUserForm()
|
||||
if form.validate_on_submit():
|
||||
# 安全检查:防止管理员误操作禁用或降级自己
|
||||
if user == current_user:
|
||||
if form.role.data != 'admin' or form.status.data != 'active':
|
||||
flash('警告:您不能禁用或降级自己的管理员账户。', 'danger')
|
||||
@@ -245,9 +304,9 @@ def update_user(user_id):
|
||||
user.role = form.role.data
|
||||
user.status = form.status.data
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'用户更新: {user.username} - 角色:{user.role} 状态:{user.status} by {current_user.username}')
|
||||
flash(f'用户 {user.username} 的信息已成功更新。', 'success')
|
||||
else:
|
||||
# 如果表单验证失败,也给出提示
|
||||
flash('更新失败,请检查提交的数据。', 'danger')
|
||||
return redirect(url_for('main.manage_users'))
|
||||
|
||||
@@ -255,37 +314,47 @@ def update_user(user_id):
|
||||
@login_required
|
||||
@admin_required
|
||||
def pending_users():
|
||||
"""待审核用户列表"""
|
||||
users_to_review = User.query.filter_by(status='pending').order_by(User.created_at.asc()).all()
|
||||
return render_template('admin/pending_users.html', users=users_to_review)
|
||||
|
||||
@main.route('/admin/user/<int:user_id>/approve', methods=['POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
def approve_user(user_id):
|
||||
"""批准用户注册"""
|
||||
user = User.query.get_or_404(user_id)
|
||||
user.status = 'active'
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'用户注册批准: {user.username} ({user.email}) by {current_user.username}')
|
||||
flash(f'用户 {user.username} 的注册申请已被批准。', 'success')
|
||||
return redirect(url_for('main.pending_users'))
|
||||
|
||||
@main.route('/admin/user/<int:user_id>/reject', methods=['POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
def reject_user(user_id):
|
||||
"""拒绝用户注册"""
|
||||
user = User.query.get_or_404(user_id)
|
||||
username = user.username
|
||||
email = user.email
|
||||
db.session.delete(user)
|
||||
db.session.commit()
|
||||
flash(f'用户 {user.username} 的注册申请已被拒绝并删除。', 'success')
|
||||
current_app.logger.info(f'用户注册拒绝: {username} ({email}) by {current_user.username}')
|
||||
flash(f'用户 {username} 的注册申请已被拒绝并删除。', 'success')
|
||||
return redirect(url_for('main.pending_users'))
|
||||
|
||||
@main.route('/appeal/create/<int:blacklist_id>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def create_appeal(blacklist_id):
|
||||
"""创建申诉"""
|
||||
blacklist_entry = Blacklist.query.get_or_404(blacklist_id)
|
||||
|
||||
# 安全检查:确保用户只能为自己的黑名单记录申诉(邮箱匹配 或 UID+站点匹配)
|
||||
|
||||
if not (current_user.email == blacklist_entry.email or
|
||||
(current_user.uid == blacklist_entry.uid and current_user.pt_site == blacklist_entry.pt_site)):
|
||||
current_app.logger.warning(f'非法申诉尝试: 用户{current_user.username} 尝试申诉黑名单#{blacklist_id}')
|
||||
abort(403)
|
||||
# 检查是否已有进行中的申诉
|
||||
|
||||
if blacklist_entry.appeals.filter(Appeal.status.in_(['awaiting_admin_reply', 'awaiting_user_reply'])).first():
|
||||
flash('您已有一个正在进行中的申诉,请勿重复提交。', 'warning')
|
||||
return redirect(url_for('main.index'))
|
||||
@@ -298,19 +367,18 @@ def create_appeal(blacklist_id):
|
||||
)
|
||||
db.session.add(appeal)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'新申诉提交: #{appeal.id} - 黑名单#{blacklist_id} by {current_user.username}')
|
||||
flash('您的申诉已成功提交,请等待管理员审核。', 'success')
|
||||
# 提交成功后,跳转到申诉详情页
|
||||
return redirect(url_for('main.appeal_detail', appeal_id=appeal.id))
|
||||
|
||||
# 如果是 GET 请求,或表单验证失败,则渲染创建页面
|
||||
|
||||
return render_template('create_appeal.html', form=form, entry=blacklist_entry)
|
||||
@main.route('/appeal/<int:appeal_id>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def appeal_detail(appeal_id):
|
||||
"""申诉详情和对话"""
|
||||
appeal = Appeal.query.get_or_404(appeal_id)
|
||||
|
||||
# 权限检查:只有申诉人或管理员可以查看
|
||||
if appeal.appealer_id != current_user.id and not current_user.role=='admin': # 假设你有 MANAGE_REPORTS 权限
|
||||
|
||||
if appeal.appealer_id != current_user.id and not current_user.role=='admin':
|
||||
abort(403)
|
||||
form = AppealMessageForm()
|
||||
if form.validate_on_submit():
|
||||
@@ -322,7 +390,6 @@ def appeal_detail(appeal_id):
|
||||
author_id=current_user.id,
|
||||
appeal_id=appeal.id
|
||||
)
|
||||
# 更新申诉状态
|
||||
if current_user.role=='admin':
|
||||
appeal.status = 'awaiting_user_reply'
|
||||
else:
|
||||
@@ -330,16 +397,17 @@ def appeal_detail(appeal_id):
|
||||
|
||||
db.session.add(msg)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'申诉消息: #{appeal.id} by {current_user.username}')
|
||||
flash('消息已发送。', 'success')
|
||||
return redirect(url_for('main.appeal_detail', appeal_id=appeal.id))
|
||||
messages = appeal.messages.order_by(AppealMessage.created_at.asc()).all()
|
||||
return render_template('appeal_detail.html', appeal=appeal, messages=messages, form=form)
|
||||
@main.route('/admin/appeals')
|
||||
@login_required
|
||||
@permission_required('admin') # 或者你的管理权限
|
||||
@permission_required('admin')
|
||||
def appeal_list():
|
||||
"""申诉列表(管理员)"""
|
||||
page = request.args.get('page', 1, type=int)
|
||||
# 优先显示待处理的
|
||||
appeals_pagination = Appeal.query.order_by(
|
||||
db.case(
|
||||
(Appeal.status == 'awaiting_admin_reply', 0),
|
||||
@@ -348,48 +416,50 @@ def appeal_list():
|
||||
),
|
||||
Appeal.updated_at.desc()
|
||||
).paginate(page=page, per_page=20, error_out=False)
|
||||
|
||||
|
||||
return render_template('admin/appeal_list.html', appeals=appeals_pagination)
|
||||
|
||||
@main.route('/appeal/<int:appeal_id>/decide', methods=['POST'])
|
||||
@login_required
|
||||
@permission_required('admin') # 必须是管理员
|
||||
@permission_required('admin')
|
||||
def decide_appeal(appeal_id):
|
||||
"""处理申诉(批准/驳回)"""
|
||||
appeal = Appeal.query.get_or_404(appeal_id)
|
||||
if appeal.status in ['approved', 'rejected']:
|
||||
flash('该申诉已处理,无法重复操作。', 'warning')
|
||||
return redirect(url_for('main.appeal_detail', appeal_id=appeal.id))
|
||||
action = request.form.get('action')
|
||||
if action == 'approve':
|
||||
# 批准申诉:删除黑名单记录,更新申诉状态
|
||||
blacklist_entry = appeal.blacklist_entry
|
||||
blacklist_entry.status = 'revoked' # 将黑名单条目状态改为"已撤销"
|
||||
appeal.status = 'approved' # 同时更新申诉本身的状态
|
||||
if blacklist_entry.report:
|
||||
# 使用 'overturned' (已推翻) 可能比 'revoked' 更能描述 Report 的状态
|
||||
blacklist_entry.report.status = 'overturned'
|
||||
db.session.add(blacklist_entry.report)
|
||||
blacklist_entry.status = 'revoked'
|
||||
appeal.status = 'approved'
|
||||
for report_id in blacklist_entry.report_ids:
|
||||
report = Report.query.get(report_id)
|
||||
if report:
|
||||
report.status = 'overturned'
|
||||
db.session.add(report)
|
||||
db.session.add(blacklist_entry)
|
||||
db.session.add(appeal)
|
||||
db.session.commit()
|
||||
|
||||
# --- 修改结束 ---
|
||||
current_app.logger.info(f'申诉批准: #{appeal.id} by {current_user.username}')
|
||||
flash(f'申诉 #{appeal.id} 已被批准,对应的黑名单条目已撤销。', 'success')
|
||||
|
||||
|
||||
elif action == 'reject':
|
||||
# 驳回申诉:仅更新申诉状态
|
||||
appeal.status = 'rejected'
|
||||
db.session.add(appeal)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'申诉驳回: #{appeal.id} by {current_user.username}')
|
||||
flash(f'已驳回申诉 #{appeal.id}。', 'info')
|
||||
else:
|
||||
flash('无效操作。', 'danger')
|
||||
return redirect(url_for('main.appeal_list'))
|
||||
|
||||
db.session.commit()
|
||||
return redirect(url_for('main.appeal_list'))
|
||||
|
||||
@main.route('/my/reports')
|
||||
@login_required
|
||||
def my_reports():
|
||||
"""我的举报列表"""
|
||||
page = request.args.get('page', 1, type=int)
|
||||
reports_pagination = Report.query.filter_by(reporter_id=current_user.id).order_by(
|
||||
Report.created_at.desc()
|
||||
@@ -399,6 +469,7 @@ def my_reports():
|
||||
@main.route('/my/appeals')
|
||||
@login_required
|
||||
def my_appeals():
|
||||
"""我的申诉列表"""
|
||||
page = request.args.get('page', 1, type=int)
|
||||
appeals_pagination = Appeal.query.filter_by(appealer_id=current_user.id).order_by(
|
||||
Appeal.created_at.desc()
|
||||
@@ -409,9 +480,9 @@ def my_appeals():
|
||||
@login_required
|
||||
@admin_required
|
||||
def manage_sites():
|
||||
"""站点管理"""
|
||||
form = PartnerSiteForm()
|
||||
if form.validate_on_submit():
|
||||
# ... (添加站点的逻辑保持不变)
|
||||
existing_site = PartnerSite.query.filter_by(name=form.name.data).first()
|
||||
if existing_site:
|
||||
flash('该站点名称已存在。', 'danger')
|
||||
@@ -419,32 +490,39 @@ def manage_sites():
|
||||
new_site = PartnerSite(name=form.name.data, url=form.url.data)
|
||||
db.session.add(new_site)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'新站点添加: {form.name.data} by {current_user.username}')
|
||||
flash(f'合作站点 "{form.name.data}" 已成功添加。', 'success')
|
||||
return redirect(url_for('main.manage_sites'))
|
||||
|
||||
|
||||
sites = PartnerSite.query.order_by(PartnerSite.name.asc()).all()
|
||||
return render_template('admin/manage_sites.html', sites=sites, form=form)
|
||||
# 添加用于删除和切换状态的路由
|
||||
|
||||
@main.route('/admin/site/<int:site_id>/delete', methods=['POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
def delete_site(site_id):
|
||||
"""删除站点"""
|
||||
site = PartnerSite.query.get_or_404(site_id)
|
||||
user_count = User.query.filter_by(pt_site=site.name).count()
|
||||
if user_count > 0:
|
||||
flash(f'无法删除站点 "{site.name}",因为已有 {user_count} 名用户关联到该站点。请先将其禁用。', 'danger')
|
||||
else:
|
||||
site_name = site.name
|
||||
db.session.delete(site)
|
||||
db.session.commit()
|
||||
flash(f'站点 "{site.name}" 已被删除。', 'success')
|
||||
current_app.logger.info(f'站点删除: {site_name} by {current_user.username}')
|
||||
flash(f'站点 "{site_name}" 已被删除。', 'success')
|
||||
return redirect(url_for('main.manage_sites'))
|
||||
|
||||
@main.route('/admin/site/<int:site_id>/toggle_active', methods=['POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
def toggle_site_active(site_id):
|
||||
"""切换站点启用状态"""
|
||||
site = PartnerSite.query.get_or_404(site_id)
|
||||
site.is_active = not site.is_active
|
||||
db.session.commit()
|
||||
status = "启用" if site.is_active else "禁用"
|
||||
current_app.logger.info(f'站点状态切换: {site.name} - {status} by {current_user.username}')
|
||||
flash(f'站点 "{site.name}" 已被{status}。', 'success')
|
||||
return redirect(url_for('main.manage_sites'))
|
||||
@@ -34,7 +34,7 @@
|
||||
{{ appeal.status | translate_status }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ appeal.updated_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (appeal.updated_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('main.appeal_detail', appeal_id=appeal.id) }}" class="btn btn-sm btn-outline-primary">查看详情</a>
|
||||
</td>
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
<small class="text-muted">{{ user.email }}</small>
|
||||
</td>
|
||||
<td>{{ user.pt_site }} / {{ user.uid }}</td>
|
||||
<td>{{ user.created_at.strftime('%Y-%m-%d') }}</td>
|
||||
<td>{{ (user.created_at | to_beijing_time).strftime('%Y-%m-%d') }}</td>
|
||||
{% if user.id == 1 %}
|
||||
<td>
|
||||
<div>角色: <span class="badge bg-danger">{{ user.role }}</span></div>
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<td>{{ user.email }}</td>
|
||||
<td>{{ user.pt_site }}</td>
|
||||
<td>{{ user.uid }}</td>
|
||||
<td>{{ user.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (user.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>
|
||||
<form action="{{ url_for('main.approve_user', user_id=user.id) }}" method="POST" class="d-inline">
|
||||
<button type="submit" class="btn btn-sm btn-success">批准</button>
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<li class="list-group-item"><strong>被举报邮箱:</strong> {{ report.reported_email }}</li>
|
||||
<li class="list-group-item"><strong>被举报用户名:</strong> {{ report.reported_username or 'N/A' }}</li>
|
||||
<li class="list-group-item"><strong>所属站点:</strong> {{ report.reported_pt_site }}</li>
|
||||
<li class="list-group-item"><strong>举报理由:</strong> {{ report.reason_category }}</li>
|
||||
<li class="list-group-item"><strong>举报理由:</strong> {{ report.reason_category | translate_reason }}</li>
|
||||
<li class="list-group-item"><strong>举报人:</strong> {{ report.reporter.username }}</li>
|
||||
<li class="list-group-item"><strong>状态:</strong> <strong class="text-capitalize">{{ report.status | translate_status }}</strong></li>
|
||||
<li class="list-group-item"><strong>详细描述:</strong><br><span style="white-space: pre-wrap;">{{ report.description }}</span></li>
|
||||
@@ -34,34 +34,56 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if current_user.role == 'admin' %}
|
||||
{% if current_user.role in ['admin', 'trust_user'] %}
|
||||
<div class="card shadow-sm mb-4">
|
||||
<div class="card-header"><h5 class="mb-0">管理员操作</h5></div>
|
||||
<div class="card-header"><h5 class="mb-0">{% if current_user.role == 'admin' %}管理员操作{% else %}信任用户操作{% endif %}</h5></div>
|
||||
<div class="card-body d-grid gap-2">
|
||||
{% if report.status == 'pending' or report.status == 'in_review' %}
|
||||
<form action="{{ url_for('main.process_report', report_id=report.id) }}" method="POST" class="d-grid">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<input type="hidden" name="action" value="confirm">
|
||||
<button type="submit" class="btn btn-success">确认违规 (加入黑名单)</button>
|
||||
</form>
|
||||
<form action="{{ url_for('main.process_report', report_id=report.id) }}" method="POST" class="d-grid">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<input type="hidden" name="action" value="invalidate">
|
||||
<button type="submit" class="btn btn-warning">举报无效</button>
|
||||
</form>
|
||||
{% elif report.status == 'approved' %}
|
||||
<button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#revokeModal">
|
||||
撤销批准并移出黑名单
|
||||
</button>
|
||||
{% if current_user.role == 'admin' %}
|
||||
{% if report.status == 'pending' or report.status == 'in_review' %}
|
||||
<form action="{{ url_for('main.process_report', report_id=report.id) }}" method="POST" class="d-grid">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<input type="hidden" name="action" value="confirm">
|
||||
<button type="submit" class="btn btn-success">确认违规 (加入黑名单)</button>
|
||||
</form>
|
||||
<form action="{{ url_for('main.process_report', report_id=report.id) }}" method="POST" class="d-grid">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<input type="hidden" name="action" value="invalidate">
|
||||
<button type="submit" class="btn btn-warning">举报无效</button>
|
||||
</form>
|
||||
{% elif report.status == 'approved' %}
|
||||
<button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#revokeModal">
|
||||
撤销批准并移出黑名单
|
||||
</button>
|
||||
{% else %}
|
||||
<p class="text-muted mb-0">该举报已处理完毕,无更多操作。</p>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<p class="text-muted mb-0">该举报已处理完毕,无更多操作。</p>
|
||||
<p class="text-muted mb-0">您可以在下方添加审核建议。</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if current_user.role in ['admin'] and related_reports %}
|
||||
<div class="card shadow-sm mb-4">
|
||||
<div class="card-header"><h5 class="mb-0">相关举报 (同一邮箱)</h5></div>
|
||||
<div class="list-group list-group-flush">
|
||||
{% for r in related_reports %}
|
||||
<a href="{{ url_for('main.report_detail', report_id=r.id) }}" class="list-group-item list-group-item-action">
|
||||
<div class="d-flex justify-content-between">
|
||||
<span><strong>#{{ r.id }}</strong> - {{ r.reason_category | translate_reason }}</span>
|
||||
<span class="badge bg-secondary">{{ r.status | translate_status }}</span>
|
||||
</div>
|
||||
<small class="text-muted">{{ (r.created_at | to_beijing_time).strftime('%Y-%m-%d') }} | 举报人: {{ r.reporter.username }}</small>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- 右侧评论区 -->
|
||||
{% if current_user.role in ['admin', 'trust_user'] %}
|
||||
<div class="col-lg-7">
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-header"><h5 class="mb-0">审核与讨论</h5></div>
|
||||
@@ -73,7 +95,7 @@
|
||||
<div class="p-2 bg-light rounded">
|
||||
<p class="small mb-0">{{ comment.body | safe }}</p>
|
||||
</div>
|
||||
<small class="text-muted">{{ comment.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
<small class="text-muted">{{ (comment.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
@@ -98,6 +120,7 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- 撤销操作的 Modal -->
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
</td>
|
||||
<td>{{ report.reporter.username }}</td>
|
||||
<td><span class="badge bg-info text-dark">{{ report.status | translate_status }}</span></td>
|
||||
<td>{{ report.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (report.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td><a href="{{ url_for('main.report_detail', report_id=report.id) }}" class="btn btn-sm btn-outline-primary">查看详情</a></td>
|
||||
</tr>
|
||||
{% else %}
|
||||
|
||||
@@ -24,6 +24,18 @@
|
||||
{% if appeal.blacklist_entry %}
|
||||
<p class="mb-0"><strong>站点:</strong> {{ appeal.blacklist_entry.pt_site }}</p>
|
||||
<p class="mb-0"><strong>UID:</strong> {{ appeal.blacklist_entry.uid }}</p>
|
||||
<p class="mb-1"><strong>违规原因:</strong></p>
|
||||
{% if appeal.blacklist_entry.reason_categories and appeal.blacklist_entry.reason_categories|length > 0 %}
|
||||
<ul class="mb-0">
|
||||
{% for reason in appeal.blacklist_entry.reason_categories %}
|
||||
<li>{{ reason | translate_reason }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% elif appeal.blacklist_entry.report %}
|
||||
<p class="mb-0">{{ appeal.blacklist_entry.report.reason_category | translate_reason }}</p>
|
||||
{% else %}
|
||||
<p class="mb-0 text-muted">未知</p>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<p class="mb-0 text-muted">黑名单记录已删除</p>
|
||||
{% endif %}
|
||||
@@ -56,7 +68,7 @@
|
||||
<div class="message user-message mb-3">
|
||||
<div class="message-header">
|
||||
<strong>{{ appeal.appealer.username }}</strong>
|
||||
<small>{{ appeal.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
<small>{{ (appeal.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
</div>
|
||||
<div class="message-body">
|
||||
<p class="fw-bold">[初始申诉理由]</p>
|
||||
@@ -70,10 +82,10 @@
|
||||
<div class="message-header">
|
||||
{% if message.author.role == 'admin' %}
|
||||
<strong>{{ message.author.username }} (管理员)</strong>
|
||||
<small>{{ message.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
<small>{{ (message.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
{% else %}
|
||||
<strong>{{ message.author.username }}</strong>
|
||||
<small>{{ message.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
<small>{{ (message.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="message-body">
|
||||
|
||||
@@ -14,9 +14,20 @@
|
||||
<li class="list-group-item"><strong>UID:</strong> {{ entry.uid }}</li>
|
||||
<li class="list-group-item"><strong>邮箱:</strong> {{ entry.email }}</li>
|
||||
<li class="list-group-item"><strong>站点:</strong> {{ entry.pt_site }}</li>
|
||||
{% if entry.report %}
|
||||
<li class="list-group-item"><strong>违规原因:</strong> {{ entry.report.reason_category }}</li>
|
||||
{% endif %}
|
||||
<li class="list-group-item">
|
||||
<strong>违规原因:</strong>
|
||||
{% if entry.reason_categories and entry.reason_categories|length > 0 %}
|
||||
<ul class="mb-0 mt-1">
|
||||
{% for reason in entry.reason_categories %}
|
||||
<li>{{ reason | translate_reason }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% elif entry.report %}
|
||||
{{ entry.report.reason_category | translate_reason }}
|
||||
{% else %}
|
||||
未知
|
||||
{% endif %}
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<form method="POST" novalidate>
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
{{ form.evidences.label(class="form-label") }}
|
||||
{{ form.evidences(class="form-control", rows=3, placeholder="每行一个证据链接(请使用图床!)") }}
|
||||
{{ form.evidences(class="form-control", rows=3, placeholder="每行一个证据链接(请使用图床!)链接应为:png,jpg,jpeg,gif,bmp,webp结尾。") }}
|
||||
<div class="form-text">请提供所有相关证据的URL,每行一个。</div>
|
||||
{% for error in form.evidences.errors %}<div class="invalid-feedback d-block">{{ error }}</div>{% endfor %}
|
||||
</div>
|
||||
|
||||
@@ -45,10 +45,19 @@
|
||||
</div>
|
||||
<ul class="list-group list-group-flush">
|
||||
<li class="list-group-item"><strong>违规站点:</strong> {{ search_result.pt_site }}</li>
|
||||
{% if search_result.report %}
|
||||
<li class="list-group-item"><strong>违规原因:</strong> {{ search_result.report.reason_category }}</li>
|
||||
{% endif %}
|
||||
<li class="list-group-item"><strong>记录时间:</strong> {{ search_result.created_at.strftime('%Y-%m-%d') }}</li>
|
||||
<li class="list-group-item">
|
||||
<strong>违规原因:</strong>
|
||||
{% if search_result.reason_categories and search_result.reason_categories|length > 0 %}
|
||||
<ul class="mb-0 mt-1">
|
||||
{% for reason in search_result.reason_categories %}
|
||||
<li>{{ reason | translate_reason }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
未知
|
||||
{% endif %}
|
||||
</li>
|
||||
<li class="list-group-item"><strong>记录时间:</strong> {{ (search_result.created_at | to_beijing_time).strftime('%Y-%m-%d') }}</li>
|
||||
</ul>
|
||||
<p class="text-muted small mt-3">为保护隐私,仅展示必要的脱敏信息。具体违规描述不对外公开。</p>
|
||||
|
||||
|
||||
@@ -31,8 +31,8 @@
|
||||
{{ appeal.status | translate_status }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ appeal.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ appeal.updated_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (appeal.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (appeal.updated_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('main.appeal_detail', appeal_id=appeal.id) }}" class="btn btn-sm btn-outline-primary">查看详情</a>
|
||||
</td>
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<td>#{{ report.id }}</td>
|
||||
<td>{{ report.reported_pt_site }}</td>
|
||||
<td>{{ report.reported_email }}</td>
|
||||
<td>{{ report.reason_category }}</td>
|
||||
<td>{{ report.reason_category | translate_reason }}</td>
|
||||
<td>
|
||||
<span class="badge
|
||||
{% if report.status == 'approved' %} bg-success
|
||||
@@ -36,7 +36,7 @@
|
||||
{{ report.status | translate_status }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ report.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (report.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('main.report_detail', report_id=report.id) }}" class="btn btn-sm btn-outline-primary">查看详情</a>
|
||||
</td>
|
||||
|
||||
86
batch_report.py
Normal file
86
batch_report.py
Normal file
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import pymysql
|
||||
from datetime import datetime
|
||||
|
||||
# 数据库配置
|
||||
DB_CONFIG = {
|
||||
"host": "localhost",
|
||||
"user": "your_db_user",
|
||||
"password": "your_db_password",
|
||||
"database": "your_db_name",
|
||||
"charset": "utf8mb4"
|
||||
}
|
||||
|
||||
# 举报配置
|
||||
REPORT_CONFIG = {
|
||||
"reporter_id": 1, # 举报人的用户ID
|
||||
"reported_pt_site": "站点名称",
|
||||
"reason_category": "scam",
|
||||
"description": "详细情况描述",
|
||||
"evidences": [
|
||||
"https://example.com/image1.png",
|
||||
"https://example.com/image2.jpg"
|
||||
]
|
||||
}
|
||||
|
||||
def load_users(json_file):
|
||||
with open(json_file, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
|
||||
def insert_report(cursor, username, email):
|
||||
now = datetime.utcnow()
|
||||
cursor.execute(
|
||||
"INSERT INTO reports (reporter_id, reported_pt_site, reported_username, reported_email, "
|
||||
"reason_category, description, status, created_at, updated_at) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, 'pending', %s, %s)",
|
||||
(REPORT_CONFIG["reporter_id"], REPORT_CONFIG["reported_pt_site"], username, email,
|
||||
REPORT_CONFIG["reason_category"], REPORT_CONFIG["description"], now, now)
|
||||
)
|
||||
return cursor.lastrowid
|
||||
|
||||
def insert_evidences(cursor, report_id):
|
||||
now = datetime.utcnow()
|
||||
for url in REPORT_CONFIG["evidences"]:
|
||||
cursor.execute(
|
||||
"INSERT INTO evidences (report_id, file_url, file_type, created_at, updated_at) "
|
||||
"VALUES (%s, %s, 'image_url', %s, %s)",
|
||||
(report_id, url, now, now)
|
||||
)
|
||||
|
||||
def main():
|
||||
users = load_users("users.json")
|
||||
conn = pymysql.connect(**DB_CONFIG)
|
||||
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
print(f"开始批量写入,共 {len(users)} 个用户\n")
|
||||
|
||||
success_count = 0
|
||||
for idx, user in enumerate(users, 1):
|
||||
username = user.get("username")
|
||||
email = user.get("email")
|
||||
|
||||
if not email:
|
||||
print(f"[{idx}] 跳过: 缺少邮箱")
|
||||
continue
|
||||
|
||||
print(f"[{idx}] 写入: {username or '(无)'} ({email})...", end=" ")
|
||||
|
||||
try:
|
||||
report_id = insert_report(cursor, username, email)
|
||||
insert_evidences(cursor, report_id)
|
||||
conn.commit()
|
||||
print(f"✓ 成功 (ID: {report_id})")
|
||||
success_count += 1
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
print(f"✗ 失败: {e}")
|
||||
|
||||
print(f"\n完成! 成功: {success_count}/{len(users)}")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
13
config.py
13
config.py
@@ -1,17 +1,18 @@
|
||||
"""应用配置"""
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import redis
|
||||
|
||||
# 加载 .env 文件中的环境变量
|
||||
basedir = os.path.abspath(os.path.dirname(__file__))
|
||||
load_dotenv(os.path.join(basedir, '.env'))
|
||||
|
||||
class Config:
|
||||
"""基础配置类"""
|
||||
"""基础配置"""
|
||||
SECRET_KEY = os.environ.get('SECRET_KEY') or 'a-hard-to-guess-string'
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
|
||||
# Session 配置
|
||||
WTF_CSRF_ENABLED = True
|
||||
WTF_CSRF_TIME_LIMIT = None
|
||||
WTF_CSRF_CHECK_DEFAULT = False
|
||||
SESSION_TYPE = 'redis'
|
||||
SESSION_PERMANENT = False
|
||||
SESSION_USE_SIGNER = True
|
||||
@@ -24,7 +25,6 @@ class Config:
|
||||
class DevelopmentConfig(Config):
|
||||
"""开发环境配置"""
|
||||
DEBUG = True
|
||||
# 数据库 URI
|
||||
DB_USER = os.environ.get('DB_USER')
|
||||
DB_PASSWORD = os.environ.get('DB_PASSWORD')
|
||||
DB_HOST = os.environ.get('DB_HOST')
|
||||
@@ -34,15 +34,12 @@ class DevelopmentConfig(Config):
|
||||
class ProductionConfig(Config):
|
||||
"""生产环境配置"""
|
||||
DEBUG = False
|
||||
# 数据库 URI
|
||||
DB_USER = os.environ.get('DB_USER')
|
||||
DB_PASSWORD = os.environ.get('DB_PASSWORD')
|
||||
DB_HOST = os.environ.get('DB_HOST')
|
||||
DB_NAME = os.environ.get('DB_NAME')
|
||||
SQLALCHEMY_DATABASE_URI = f'mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}'
|
||||
|
||||
|
||||
# 方便地通过字典来选择配置
|
||||
config = {
|
||||
'development': DevelopmentConfig,
|
||||
'production': ProductionConfig,
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""merge multiple reports for same user
|
||||
|
||||
Revision ID: db2662009e3d
|
||||
Revises:
|
||||
Create Date: 2025-11-24 22:33:03.614231
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'db2662009e3d'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('blacklist',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.String(length=64), nullable=True),
|
||||
sa.Column('email', sa.String(length=120), nullable=True),
|
||||
sa.Column('normalized_email', sa.String(length=120), nullable=True),
|
||||
sa.Column('pt_site', sa.String(length=100), nullable=True),
|
||||
sa.Column('uid', sa.String(length=50), nullable=True),
|
||||
sa.Column('report_ids', sa.JSON(), nullable=False),
|
||||
sa.Column('reason_categories', sa.JSON(), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('blacklist', schema=None) as batch_op:
|
||||
batch_op.create_index('idx_blacklist_email_status', ['normalized_email', 'status'], unique=False)
|
||||
batch_op.create_index('idx_blacklist_username_status', ['username', 'status'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_created_at'), ['created_at'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_email'), ['email'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_normalized_email'), ['normalized_email'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_pt_site'), ['pt_site'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_status'), ['status'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_username'), ['username'], unique=False)
|
||||
|
||||
op.create_table('partner_sites',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=100), nullable=False),
|
||||
sa.Column('url', sa.String(length=255), nullable=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('partner_sites', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_partner_sites_is_active'), ['is_active'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_partner_sites_name'), ['name'], unique=True)
|
||||
|
||||
op.create_table('users',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.String(length=64), nullable=False),
|
||||
sa.Column('email', sa.String(length=120), nullable=False),
|
||||
sa.Column('password_hash', sa.String(length=256), nullable=True),
|
||||
sa.Column('role', sa.String(length=16), nullable=True),
|
||||
sa.Column('status', sa.String(length=16), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('pt_site', sa.String(length=100), nullable=True),
|
||||
sa.Column('uid', sa.String(length=50), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_users_email'), ['email'], unique=True)
|
||||
batch_op.create_index(batch_op.f('ix_users_role'), ['role'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_users_status'), ['status'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_users_username'), ['username'], unique=True)
|
||||
|
||||
op.create_table('appeals',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('reason', sa.Text(), nullable=False),
|
||||
sa.Column('status', sa.String(length=32), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('appealer_id', sa.Integer(), nullable=True),
|
||||
sa.Column('blacklist_entry_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['appealer_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['blacklist_entry_id'], ['blacklist.id'], ondelete='SET NULL'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('appeals', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_appeals_created_at'), ['created_at'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_appeals_status'), ['status'], unique=False)
|
||||
|
||||
op.create_table('reports',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('reporter_id', sa.Integer(), nullable=False),
|
||||
sa.Column('reported_pt_site', sa.String(length=100), nullable=False),
|
||||
sa.Column('reported_username', sa.String(length=50), nullable=True),
|
||||
sa.Column('reported_email', sa.String(length=120), nullable=False),
|
||||
sa.Column('reason_category', sa.String(length=16), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['reporter_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('reports', schema=None) as batch_op:
|
||||
batch_op.create_index('idx_report_status_created', ['status', 'created_at'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_reports_created_at'), ['created_at'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_reports_reported_email'), ['reported_email'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_reports_status'), ['status'], unique=False)
|
||||
|
||||
op.create_table('appeal_messages',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('body', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('author_id', sa.Integer(), nullable=True),
|
||||
sa.Column('appeal_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['appeal_id'], ['appeals.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['author_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('appeal_messages', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_appeal_messages_created_at'), ['created_at'], unique=False)
|
||||
|
||||
op.create_table('comments',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('body', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('author_id', sa.Integer(), nullable=True),
|
||||
sa.Column('report_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['author_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['report_id'], ['reports.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('comments', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_comments_created_at'), ['created_at'], unique=False)
|
||||
|
||||
op.create_table('evidences',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('report_id', sa.Integer(), nullable=False),
|
||||
sa.Column('file_url', sa.String(length=1024), nullable=False),
|
||||
sa.Column('file_type', sa.String(length=16), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['report_id'], ['reports.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('evidences')
|
||||
with op.batch_alter_table('comments', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_comments_created_at'))
|
||||
|
||||
op.drop_table('comments')
|
||||
with op.batch_alter_table('appeal_messages', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_appeal_messages_created_at'))
|
||||
|
||||
op.drop_table('appeal_messages')
|
||||
with op.batch_alter_table('reports', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_reports_status'))
|
||||
batch_op.drop_index(batch_op.f('ix_reports_reported_email'))
|
||||
batch_op.drop_index(batch_op.f('ix_reports_created_at'))
|
||||
batch_op.drop_index('idx_report_status_created')
|
||||
|
||||
op.drop_table('reports')
|
||||
with op.batch_alter_table('appeals', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_appeals_status'))
|
||||
batch_op.drop_index(batch_op.f('ix_appeals_created_at'))
|
||||
|
||||
op.drop_table('appeals')
|
||||
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_users_username'))
|
||||
batch_op.drop_index(batch_op.f('ix_users_status'))
|
||||
batch_op.drop_index(batch_op.f('ix_users_role'))
|
||||
batch_op.drop_index(batch_op.f('ix_users_email'))
|
||||
|
||||
op.drop_table('users')
|
||||
with op.batch_alter_table('partner_sites', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_partner_sites_name'))
|
||||
batch_op.drop_index(batch_op.f('ix_partner_sites_is_active'))
|
||||
|
||||
op.drop_table('partner_sites')
|
||||
with op.batch_alter_table('blacklist', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_username'))
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_status'))
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_pt_site'))
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_normalized_email'))
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_email'))
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_created_at'))
|
||||
batch_op.drop_index('idx_blacklist_username_status')
|
||||
batch_op.drop_index('idx_blacklist_email_status')
|
||||
|
||||
op.drop_table('blacklist')
|
||||
# ### end Alembic commands ###
|
||||
17
run.py
17
run.py
@@ -1,3 +1,4 @@
|
||||
"""应用启动入口"""
|
||||
import os
|
||||
import click
|
||||
from app import create_app, db
|
||||
@@ -13,23 +14,23 @@ def make_shell_context():
|
||||
@click.argument("username")
|
||||
@click.argument("email")
|
||||
@click.argument("password")
|
||||
@click.option("--admin", is_flag=True, help="Flag to create an admin user.")
|
||||
@click.option("--admin", is_flag=True, help="创建管理员用户")
|
||||
def create_user(username, email, password, admin):
|
||||
"""Creates a new user."""
|
||||
"""创建新用户"""
|
||||
if User.query.filter_by(email=email).first():
|
||||
print(f"Error: Email {email} already exists.")
|
||||
print(f"错误: 邮箱 {email} 已存在")
|
||||
return
|
||||
if User.query.filter_by(username=username).first():
|
||||
print(f"Error: Username {username} already exists.")
|
||||
print(f"错误: 用户名 {username} 已存在")
|
||||
return
|
||||
|
||||
|
||||
user = User(username=username, email=email, status='active')
|
||||
user.set_password(password)
|
||||
if admin:
|
||||
user.role = 'admin'
|
||||
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
print(f"User {username} created successfully.")
|
||||
print(f"用户 {username} 创建成功")
|
||||
if admin:
|
||||
print("Role: Admin")
|
||||
print("角色: 管理员")
|
||||
|
||||
Reference in New Issue
Block a user