- 将项目重构为前后端分离架构,前端使用Vue 3 + Element Plus,后端使用Flask - 实现基于JWT的身份认证系统,提供登录/登出和用户信息获取API - 引入基于角色的访问控制(RBAC)系统,支持角色继承和权限管理 - 添加数据隔离机制,研究员只能访问自己的数据,管理员拥有全局权限 - 实现数据时间控制功能,支持设置开始时间和永久性标记 - 创建前端管理界面,包括用户管理、角色管理、权限管理和操作日志 - 重构项目结构,分离前后端代码,更新README说明文档 - 添加数据库迁移脚本,支持RBAC相关表的创建和更新 - 集成Vue Router和Pinia状态管理,构建完整的前端应用架构 - 提供字体文件管理和静态资源缓存优化
325 lines
12 KiB
Python
325 lines
12 KiB
Python
import os
|
|
from datetime import datetime
|
|
|
|
import pandas as pd
|
|
from flask import Response, current_app, jsonify, request, send_from_directory
|
|
from flask_jwt_extended import jwt_required
|
|
from sqlalchemy import or_
|
|
from werkzeug.utils import secure_filename
|
|
|
|
from .. import db
|
|
from ..models import Attachment, DataEntry, User
|
|
from . import api
|
|
from .security import (
|
|
admin_required_jwt,
|
|
data_access_required_jwt,
|
|
get_current_user,
|
|
get_pagination_args,
|
|
permission_required_jwt,
|
|
)
|
|
|
|
|
|
@api.route("/data-entries/<int:entry_id>", methods=["GET"])
|
|
@jwt_required()
|
|
@data_access_required_jwt(DataEntry, id_param="entry_id")
|
|
def get_data_entry(entry_id):
|
|
entry = DataEntry.query.get(entry_id)
|
|
if not entry:
|
|
return jsonify({"msg": "Not found"}), 404
|
|
|
|
return (
|
|
jsonify(
|
|
{
|
|
"id": entry.id,
|
|
"title": entry.title,
|
|
"content": entry.content,
|
|
"timestamp": entry.timestamp.isoformat(),
|
|
"is_permanent": entry.is_permanent,
|
|
"start_date": entry.start_date.isoformat() if entry.start_date else None,
|
|
"expiration_date": entry.expiration_date.isoformat() if entry.expiration_date else None,
|
|
"researcher_id": entry.researcher_id,
|
|
"researcher": entry.researcher.username if entry.researcher else None,
|
|
"associated_filename": entry.associated_filename,
|
|
"visible_user_ids": [u.id for u in entry.visible_to_users],
|
|
"attachments": [
|
|
{"id": a.id, "original_name": a.original_name, "filename": a.filename, "upload_time": a.upload_time.isoformat()}
|
|
for a in entry.attachments
|
|
],
|
|
}
|
|
),
|
|
200,
|
|
)
|
|
|
|
|
|
@api.route("/attachments/<int:attachment_id>/download", methods=["GET"])
|
|
@jwt_required()
|
|
@data_access_required_jwt(Attachment, id_param="attachment_id")
|
|
def download_attachment(attachment_id):
|
|
attachment = Attachment.query.get(attachment_id)
|
|
if not attachment:
|
|
return jsonify({"msg": "Not found"}), 404
|
|
|
|
directory = current_app.config["ATTACHMENTS_FOLDER"]
|
|
return send_from_directory(directory, attachment.filename, as_attachment=True, download_name=attachment.original_name)
|
|
|
|
|
|
@api.route("/admin/data-entries", methods=["GET"])
|
|
@jwt_required()
|
|
@admin_required_jwt
|
|
@permission_required_jwt("manage_data")
|
|
def list_data_entries():
|
|
page, per_page = get_pagination_args(default_per_page=20)
|
|
q = request.args.get("q", "").strip()
|
|
researcher_id = request.args.get("researcher_id", type=int)
|
|
|
|
query = DataEntry.query
|
|
if q:
|
|
like = f"%{q}%"
|
|
query = query.filter(or_(DataEntry.title.ilike(like), DataEntry.content.ilike(like)))
|
|
if researcher_id:
|
|
query = query.filter(DataEntry.researcher_id == researcher_id)
|
|
|
|
query = query.order_by(DataEntry.timestamp.desc())
|
|
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
|
|
|
|
return (
|
|
jsonify(
|
|
{
|
|
"items": [
|
|
{
|
|
"id": e.id,
|
|
"title": e.title,
|
|
"timestamp": e.timestamp.isoformat(),
|
|
"researcher_id": e.researcher_id,
|
|
"researcher": e.researcher.username if e.researcher else None,
|
|
"is_permanent": e.is_permanent,
|
|
"start_date": e.start_date.isoformat() if e.start_date else None,
|
|
"expiration_date": e.expiration_date.isoformat() if e.expiration_date else None,
|
|
"visible_user_count": e.visible_to_users.count() if hasattr(e.visible_to_users, "count") else len(e.visible_to_users),
|
|
"attachment_count": e.attachments.count() if hasattr(e.attachments, "count") else len(e.attachments),
|
|
"associated_filename": e.associated_filename,
|
|
}
|
|
for e in pagination.items
|
|
],
|
|
"page": pagination.page,
|
|
"per_page": pagination.per_page,
|
|
"total": pagination.total,
|
|
}
|
|
),
|
|
200,
|
|
)
|
|
|
|
|
|
@api.route("/admin/data-entries", methods=["POST"])
|
|
@jwt_required()
|
|
@admin_required_jwt
|
|
@permission_required_jwt("manage_data")
|
|
def create_data_entry():
|
|
form = request.form
|
|
title = (form.get("title") or "").strip()
|
|
content = (form.get("content") or "").strip()
|
|
|
|
if not title or not content:
|
|
return jsonify({"msg": "Missing title or content"}), 400
|
|
|
|
is_permanent = (form.get("is_permanent", "true").lower() in ("true", "1", "yes", "on"))
|
|
start_date = form.get("start_date")
|
|
expiration_date = form.get("expiration_date")
|
|
researcher_id = form.get("researcher_id", type=int)
|
|
|
|
start_dt = datetime.fromisoformat(start_date) if start_date else None
|
|
exp_dt = datetime.fromisoformat(expiration_date) if expiration_date else None
|
|
|
|
csv_file = request.files.get("csv_file")
|
|
associated_filename = None
|
|
if csv_file and csv_file.filename:
|
|
associated_filename = secure_filename(csv_file.filename)
|
|
csv_path = os.path.join(current_app.config["UPLOAD_FOLDER"], associated_filename)
|
|
csv_file.save(csv_path)
|
|
|
|
entry = DataEntry(
|
|
title=title,
|
|
content=content,
|
|
associated_filename=associated_filename,
|
|
is_permanent=is_permanent,
|
|
start_date=start_dt,
|
|
expiration_date=exp_dt,
|
|
researcher_id=researcher_id if researcher_id else None,
|
|
)
|
|
|
|
visible_user_ids = form.getlist("visible_user_ids")
|
|
if visible_user_ids:
|
|
ids = [int(x) for x in visible_user_ids if str(x).isdigit()]
|
|
if ids:
|
|
users = User.query.filter(User.id.in_(ids)).all()
|
|
for u in users:
|
|
entry.visible_to_users.append(u)
|
|
|
|
attachment_files = request.files.getlist("attachments")
|
|
if attachment_files:
|
|
for f in attachment_files:
|
|
if not f or not f.filename:
|
|
continue
|
|
original_name = secure_filename(f.filename)
|
|
timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S_%f")
|
|
filename = f"{timestamp}_{original_name}"
|
|
filepath = os.path.join(current_app.config["ATTACHMENTS_FOLDER"], filename)
|
|
f.save(filepath)
|
|
|
|
attachment = Attachment(filename=filename, original_name=original_name, data_entry=entry)
|
|
db.session.add(attachment)
|
|
|
|
db.session.add(entry)
|
|
db.session.commit()
|
|
|
|
return jsonify({"id": entry.id}), 201
|
|
|
|
|
|
@api.route("/admin/data-entries/<int:entry_id>", methods=["PATCH"])
|
|
@jwt_required()
|
|
@admin_required_jwt
|
|
@permission_required_jwt("manage_data")
|
|
def update_data_entry(entry_id):
|
|
entry = DataEntry.query.get(entry_id)
|
|
if not entry:
|
|
return jsonify({"msg": "Not found"}), 404
|
|
|
|
data = request.get_json() or {}
|
|
if "title" in data:
|
|
entry.title = (data.get("title") or "").strip()
|
|
if "content" in data:
|
|
entry.content = (data.get("content") or "").strip()
|
|
if "is_permanent" in data:
|
|
entry.is_permanent = bool(data.get("is_permanent"))
|
|
if "start_date" in data:
|
|
entry.start_date = datetime.fromisoformat(data.get("start_date")) if data.get("start_date") else None
|
|
if "expiration_date" in data:
|
|
entry.expiration_date = datetime.fromisoformat(data.get("expiration_date")) if data.get("expiration_date") else None
|
|
if "researcher_id" in data:
|
|
entry.researcher_id = data.get("researcher_id") or None
|
|
|
|
if "visible_user_ids" in data:
|
|
ids = data.get("visible_user_ids") or []
|
|
users = User.query.filter(User.id.in_(ids)).all() if ids else []
|
|
entry.visible_to_users = users
|
|
|
|
db.session.commit()
|
|
return jsonify({"msg": "ok"}), 200
|
|
|
|
|
|
@api.route("/admin/data-entries/<int:entry_id>", methods=["DELETE"])
|
|
@jwt_required()
|
|
@admin_required_jwt
|
|
@permission_required_jwt("manage_data")
|
|
def delete_data_entry(entry_id):
|
|
entry = DataEntry.query.get(entry_id)
|
|
if not entry:
|
|
return jsonify({"msg": "Not found"}), 404
|
|
|
|
for attachment in entry.attachments:
|
|
try:
|
|
filepath = os.path.join(current_app.config["ATTACHMENTS_FOLDER"], attachment.filename)
|
|
if os.path.exists(filepath):
|
|
os.remove(filepath)
|
|
except Exception:
|
|
pass
|
|
|
|
if entry.associated_filename:
|
|
try:
|
|
csv_path = os.path.join(current_app.config["UPLOAD_FOLDER"], entry.associated_filename)
|
|
if os.path.exists(csv_path):
|
|
os.remove(csv_path)
|
|
except Exception:
|
|
pass
|
|
|
|
db.session.delete(entry)
|
|
db.session.commit()
|
|
return jsonify({"msg": "deleted"}), 200
|
|
|
|
|
|
@api.route("/admin/data-entries/batch-delete", methods=["POST"])
|
|
@jwt_required()
|
|
@admin_required_jwt
|
|
@permission_required_jwt("manage_data")
|
|
def batch_delete_data_entries():
|
|
data = request.get_json() or {}
|
|
ids = data.get("ids") or []
|
|
if not ids:
|
|
return jsonify({"msg": "No ids"}), 400
|
|
|
|
deleted = 0
|
|
for entry_id in ids:
|
|
entry = DataEntry.query.get(entry_id)
|
|
if not entry:
|
|
continue
|
|
|
|
for attachment in entry.attachments:
|
|
try:
|
|
filepath = os.path.join(current_app.config["ATTACHMENTS_FOLDER"], attachment.filename)
|
|
if os.path.exists(filepath):
|
|
os.remove(filepath)
|
|
except Exception:
|
|
pass
|
|
|
|
if entry.associated_filename:
|
|
try:
|
|
csv_path = os.path.join(current_app.config["UPLOAD_FOLDER"], entry.associated_filename)
|
|
if os.path.exists(csv_path):
|
|
os.remove(csv_path)
|
|
except Exception:
|
|
pass
|
|
|
|
db.session.delete(entry)
|
|
deleted += 1
|
|
|
|
db.session.commit()
|
|
return jsonify({"deleted": deleted}), 200
|
|
|
|
|
|
@api.route("/admin/data-entries/<int:entry_id>/csv", methods=["GET"])
|
|
@jwt_required()
|
|
@admin_required_jwt
|
|
@permission_required_jwt("manage_data")
|
|
def download_data_entry_csv(entry_id):
|
|
entry = DataEntry.query.get(entry_id)
|
|
if not entry:
|
|
return jsonify({"msg": "Not found"}), 404
|
|
if not entry.associated_filename:
|
|
return jsonify({"msg": "No csv"}), 404
|
|
|
|
directory = current_app.config["UPLOAD_FOLDER"]
|
|
return send_from_directory(directory, entry.associated_filename, as_attachment=True, download_name=entry.associated_filename)
|
|
|
|
|
|
@api.route("/admin/data-entries/export", methods=["GET"])
|
|
@jwt_required()
|
|
@admin_required_jwt
|
|
@permission_required_jwt("manage_data")
|
|
def export_data_entries():
|
|
data_entries = DataEntry.query.all()
|
|
data = []
|
|
for entry in data_entries:
|
|
data.append(
|
|
{
|
|
"ID": entry.id,
|
|
"Title": entry.title,
|
|
"Content": entry.content,
|
|
"Researcher": entry.researcher.username if entry.researcher else "N/A",
|
|
"Created At": entry.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
|
|
"Is Permanent": "Yes" if entry.is_permanent else "No",
|
|
"Start Date": entry.start_date.strftime("%Y-%m-%d %H:%M:%S") if entry.start_date else "N/A",
|
|
"Expiration Date": entry.expiration_date.strftime("%Y-%m-%d %H:%M:%S") if entry.expiration_date else "N/A",
|
|
"Visible To Users": ", ".join([u.username for u in entry.visible_to_users]),
|
|
}
|
|
)
|
|
|
|
df = pd.DataFrame(data)
|
|
output = df.to_csv(index=False, encoding="utf-8-sig")
|
|
|
|
filename = f"data_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.csv"
|
|
return Response(
|
|
output,
|
|
mimetype="text/csv",
|
|
headers={"Content-disposition": f"attachment; filename={filename}"},
|
|
)
|