chore: initialize GSREA website project

This commit is contained in:
zlwu committed 2026-10-30 11:05:55 +08:00
commit d3c5461de5
1842 files changed
+246140

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
# 复制为 .env 后填写。不要把真实口令写入仓库。
# 开发测试环境的实际值见 docs/理解/个人对需求的理解.md,不要抄进本文件。
JWT_SECRET=
JWT_EXPIRE_MINUTES=120
JWT_MEMBER_EXPIRE_MINUTES=10080
API_PAYLOAD_ENCRYPT=false
API_PAYLOAD_AES_KEY=
API_IP_BLACKLIST=
CORS_ORIGINS=http://127.0.0.1:13000,http://localhost:13000,http://127.0.0.1:13006,http://localhost:13006
DATABASE_URL=mysql+pymysql://USER:PASSWORD@HOST:3306/gsfdc
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_DB=0
REDIS_PASSWORD=
REDIS_TIMEOUT_SEC=30
REDIS_SSL_ENABLED=false
STORAGE_TYPE=minio
MINIO_ENDPOINT=127.0.0.1:9000
MINIO_ACCESS_KEY=
MINIO_SECRET_KEY=
MINIO_BUCKET_PUBLIC=gsfdc-public
MINIO_BUCKET_PRIVATE=gsfdc-private
MINIO_SECURE=false
MINIO_BASE_URL=http://127.0.0.1:9000/gsfdc-public
# 手机号、身份证字段加密。与 API_PAYLOAD_AES_KEY 不是同一把钥匙。32 字节密钥的 Base64。
FIELD_AES_KEY=
# 一次性创建超级管理员时由命令读取,不要写进源码。命令结束后可以清掉。
BOOTSTRAP_ADMIN_USERNAME=
BOOTSTRAP_ADMIN_PASSWORD=
# 高德 JS API。浏览器可见,靠控制台域名白名单约束。不要把真实值写入仓库。
GAODE_KEY=
GAODE_SECURITY_JS_CODE=
# 邮箱验证码发信(测试可用 126)。授权码不是登录密码;真实值只放 .env。
SMTP_HOST=
SMTP_PORT=465
SMTP_USER=
SMTP_PASSWORD=
SMTP_SENDER=
SMTP_USE_SSL=true
+52
View File
@@ -0,0 +1,52 @@
# 服务端 AGENTS.md
本目录是门户和管理后台共用的唯一业务后端。不要再为 `portal/` 或 `admin/` 各建一套 Python 工程或各接一个数据库。教育平台若最终不采用 PlayEdu,课程与进度也放在这里;若采用 PlayEdu,它自带服务,账号标识仍与本服务对齐。仓库根目录 `AGENTS.md` 同时有效。
## 职责
- REST API。没有明确调用方时不做第二套 RPC。
- 账号、角色、菜单与按钮资源、强密码、账号注销。
- 敏感字段加密存储(AES-256 或 SM4)和接口脱敏。
- 附件:公开对象与私有对象分开。私有对象用鉴权或短期链接。上传大小可配置,禁止不限制大小。
- 全量接口访问日志。不记录密码、验证码、身份证号、完整手机号。
- 管理端接口必须登录,且只接受工作人员令牌。会员数据接口只允许本人,只接受会员令牌。两种令牌不能混用。公开接口与登录接口在 `/api/site` 下分开注册。
- 业务接口只有两个前缀:门户 `/api/site`,管理后台 `/api/admin`。不允许在这两个前缀之外新增业务接口。
- JSON 体支持应用层加解密,由环境变量开关控制,门户、管理端和本服务必须使用同一开关和同一算法。默认关闭,便于联调。生产是否开启在部署时同时打开。文件上传和下载不加密。算法用 AES-GCM。密钥放环境变量,不写进源码。这项不代替 HTTPS,也不代替登录鉴权。
- 内容审核与敏感词:未发布数据不能被门户读到。富文本来自 wangEditor-next,保存时按白名单过滤 HTML,去掉脚本、事件属性和非本站图片地址。
- IP 黑名单。
应用层 JSON 加解密按上一节的开关执行。传输加密始终使用 HTTPS。数据库里的身份证、手机号仍然用 AES-256 或 SM4 加密存储,与接口加解密无关。
## 数据
- MySQL、Redis、MinIO。
- 连接信息只放环境变量。提交 `.env.example` 时使用占位符,不要从 `docs/理解/个人对需求的理解.md` 抄真实口令。
- 开发测试库不是生产库。生产在天翼云,规格见根目录 `AGENTS.md`。
## 目录约定
栏目专篇未写完时,只允许公共能力进入代码,不按十一项栏目建业务包。
```text
server/
AGENTS.md
.env.example
app/
api/
site/ # 前缀 /api/site,其下再分 public 与 member
admin/ # 前缀 /api/admin,全部要求工作人员登录
core/ # 配置、鉴权、加解密、日志、脱敏
models/
services/
```
机构名录不要单独造一套与会员无关的机构主数据。报告查询只对照报告备案,不要做文件验真、核验码或报告审核的保存接口,见 `docs/adr/0010-report-query-is-filing-lookup.md`。数据挖掘、智能估价、中房学和住建厅的数据对接,不要建客户端或同步任务。
投诉时限、专家回复时限放配置,不写死。行业自律的投诉、警示案例、诚信档案和结果公示见 `docs/adr/0012-industry-discipline-articles-and-complaint-code.md`。
## 接口约定
- 路径与 JSON 字段使用英文,文档用中文说明业务含义。
- 脱敏在返回前完成,不依赖前端遮盖。需要脱敏的字段在模型或序列化处集中声明。
- 错误响应不回传 SQL、堆栈或内部路径。
- 批量导出和查看敏感数据要写审计日志。
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+90
View File
@@ -0,0 +1,90 @@
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.about import (
admin_about_page,
admin_experts,
create_expert,
delete_expert,
save_about_page,
update_expert,
)
from app.models.home import admin_column_articles
router = APIRouter(dependencies=[Depends(require_staff)])
class AboutPageWrite(BaseModel):
published: bool = False
bodyHtml: str = ""
attachmentFileIds: list[int] = Field(default_factory=list)
class ExpertWrite(BaseModel):
name: str
bodyHtml: str = ""
sortOrder: int = 0
published: bool = False
attachmentFileIds: list[int] = Field(default_factory=list)
@router.get("/about/pages/{page_key}")
def read_about_page(page_key: str, db: Session = Depends(get_db)) -> dict:
body = admin_about_page(db, page_key)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="单篇页键不正确")
return body
@router.put("/about/pages/{page_key}")
def write_about_page(page_key: str, body: AboutPageWrite, db: Session = Depends(get_db)) -> dict:
try:
save_about_page(db, page_key, body.model_dump())
except ValueError as exc:
code = status.HTTP_404_NOT_FOUND if "不正确" in str(exc) else status.HTTP_400_BAD_REQUEST
raise HTTPException(status_code=code, detail=str(exc)) from exc
return {"ok": True}
@router.get("/about/articles/{category}")
def list_column_articles(category: str, db: Session = Depends(get_db)) -> dict:
body = admin_column_articles(db, category)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="文章类别不正确")
return body
@router.get("/about/experts")
def list_experts(db: Session = Depends(get_db)) -> dict:
return admin_experts(db)
@router.post("/about/experts")
def write_expert(body: ExpertWrite, db: Session = Depends(get_db)) -> dict:
try:
expert_id = create_expert(db, body.model_dump())
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"id": expert_id}
@router.put("/about/experts/{expert_id}")
def revise_expert(expert_id: int, body: ExpertWrite, db: Session = Depends(get_db)) -> dict:
try:
update_expert(db, expert_id, body.model_dump())
except ValueError as exc:
code = status.HTTP_404_NOT_FOUND if str(exc) == "专家委员会不存在" else status.HTTP_400_BAD_REQUEST
raise HTTPException(status_code=code, detail=str(exc)) from exc
return {"ok": True}
@router.delete("/about/experts/{expert_id}")
def remove_expert(expert_id: int, db: Session = Depends(get_db)) -> dict:
try:
delete_expert(db, expert_id)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
return {"ok": True}
+353
View File
@@ -0,0 +1,353 @@
import json
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile, status
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.content import (
SETTING_KEYS,
AdminFile,
SensitiveWord,
read_upload_limit,
save_settings,
settings_view,
)
from app.services.html_filter import is_javascript_url, preview_filter
from app.services.storage import (
make_object_key,
private_object_url,
public_object_url,
remove_stored_object,
safe_filename,
upload_object,
)
router = APIRouter(dependencies=[Depends(require_staff)])
_TEXT_KEYS = {"site_name", "icp_text", "police_text", "link_cirea", "link_housing"}
_LINK_KEYS = {"link_cirea", "link_housing"}
_POSITIVE = {
"upload_max_bytes": "上传大小上限必须是正整数",
"login_max_failures": "登录锁定参数必须是正整数",
"login_lock_minutes": "登录锁定参数必须是正整数",
}
_WORKDAYS = {"complaint_workdays", "expert_reply_workdays"}
_INT_MAX = 2147483647
class WordIn(BaseModel):
word: str = ""
class PreviewIn(BaseModel):
html: str = ""
def _bad(detail: str) -> None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)
def _actor_id(principal: dict) -> int | None:
try:
return int(principal["sub"])
except (KeyError, TypeError, ValueError):
return None
def _content_type(value: str | None) -> str:
raw = (value or "").split(";", 1)[0].strip().lower()
return raw.replace("\r", "").replace("\n", "")[:128]
def _read_limited(upload: UploadFile, limit: int) -> bytes:
chunks = bytearray()
while True:
piece = upload.file.read(65536)
if not piece:
break
if len(chunks) + len(piece) > limit:
_bad("文件超过大小上限")
chunks.extend(piece)
return bytes(chunks)
def _text_setting(key: str, value) -> str:
if not isinstance(value, str):
_bad("配置项格式不正确")
text = value.strip()
if key in _LINK_KEYS and is_javascript_url(text):
_bad("链接地址不正确")
return text
def _logo_id(value) -> str:
if value is None:
return ""
if isinstance(value, str) and not value.strip():
return ""
if isinstance(value, bool) or not isinstance(value, (int, str)):
_bad("logo_file_id 必须是附件编号")
text = str(value).strip()
if not text.isdigit() or int(text) <= 0:
_bad("logo_file_id 必须是附件编号")
return str(int(text))
def _banner_ids(value) -> str:
if not isinstance(value, list):
_bad("banner_file_ids 必须是数组")
numbers: list[int] = []
for item in value:
if isinstance(item, bool) or not isinstance(item, (int, str)):
_bad("banner_file_ids 必须是附件编号")
text = str(item).strip()
if not text.isdigit() or int(text) <= 0:
_bad("banner_file_ids 必须是附件编号")
numbers.append(int(text))
return json.dumps(numbers, separators=(",", ":"))
def _friend_links(value) -> str:
if not isinstance(value, list):
_bad("friend_links 必须是数组")
cleaned: list[dict[str, str]] = []
for item in value:
if not isinstance(item, dict):
_bad("相关链接必须包含名称和地址")
name = item.get("name")
url = item.get("url")
if not isinstance(name, str) or not isinstance(url, str):
_bad("相关链接必须包含名称和地址")
name = name.strip()
url = url.strip()
if not name or not url:
_bad("相关链接必须包含名称和地址")
if is_javascript_url(url):
_bad("链接地址不正确")
cleaned.append({"name": name, "url": url})
return json.dumps(cleaned, ensure_ascii=False, separators=(",", ":"))
def _positive(value, message: str) -> str:
if isinstance(value, bool) or not isinstance(value, int) or value <= 0 or value > _INT_MAX:
_bad(message)
return str(value)
def _workdays(value) -> str:
if value is None or value == "":
return ""
if isinstance(value, bool) or not isinstance(value, int) or value < 0 or value > _INT_MAX:
_bad("时限必须是非负整数")
return str(value)
def _normalize_settings(payload: dict) -> dict[str, str]:
if any(key not in SETTING_KEYS for key in payload):
_bad("未知的配置项")
stored: dict[str, str] = {}
for key, value in payload.items():
if key in _TEXT_KEYS:
stored[key] = _text_setting(key, value)
elif key == "logo_file_id":
stored[key] = _logo_id(value)
elif key == "banner_file_ids":
stored[key] = _banner_ids(value)
elif key == "friend_links":
stored[key] = _friend_links(value)
elif key in _POSITIVE:
stored[key] = _positive(value, _POSITIVE[key])
elif key in _WORKDAYS:
stored[key] = _workdays(value)
return stored
def _file_link(row: AdminFile) -> tuple[str, str | None]:
if row.bucket == "public":
return public_object_url(row.object_key), None
if row.bucket == "private":
url, expires_at = private_object_url(row.object_key)
return url, expires_at.isoformat()
_bad("附件存储位置不正确")
return "", None
def _file_body(row: AdminFile, *, with_meta: bool) -> dict:
url, expires_at = _file_link(row)
body = {
"id": row.id,
"bucket": row.bucket,
"filename": row.filename,
"contentType": row.content_type,
"size": row.size,
"url": url,
"expiresAt": expires_at,
}
if with_meta:
body["createdBy"] = row.created_by
body["createdAt"] = row.created_at.isoformat() if row.created_at else None
return body
def _word_body(row: SensitiveWord) -> dict:
return {
"id": row.id,
"word": row.word,
"createdAt": row.created_at.isoformat() if row.created_at else None,
}
@router.post("/files")
def upload_file(
file: UploadFile = File(...),
bucket: str | None = Form(default=None),
db: Session = Depends(get_db),
principal: dict = Depends(require_staff),
):
if bucket not in {"public", "private"}:
_bad("bucket 只能是 public 或 private")
limit = read_upload_limit(db)
if limit is None:
_bad("未配置上传大小上限")
data = _read_limited(file, limit)
filename = safe_filename(file.filename)
content_type = _content_type(file.content_type)
object_key = make_object_key(filename)
upload_object(bucket, object_key, data, content_type)
row = AdminFile(
bucket=bucket,
object_key=object_key,
filename=filename,
content_type=content_type,
size=len(data),
created_by=_actor_id(principal),
)
db.add(row)
try:
db.commit()
db.refresh(row)
except Exception:
db.rollback()
try:
remove_stored_object(bucket, object_key)
except HTTPException:
pass
raise
return _file_body(row, with_meta=False)
def _like_contains(value: str) -> str:
escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
return f"%{escaped}%"
@router.get("/files")
def list_files(
current: int = Query(default=1, ge=1),
size: int = Query(default=10, ge=1, le=100),
bucket: str | None = Query(default=None),
q: str | None = Query(default=None),
db: Session = Depends(get_db),
):
if bucket is not None and bucket not in {"public", "private"}:
_bad("bucket 只能是 public 或 private")
count_stmt = select(func.count()).select_from(AdminFile)
stmt = select(AdminFile).order_by(AdminFile.id.desc())
if bucket is not None:
count_stmt = count_stmt.where(AdminFile.bucket == bucket)
stmt = stmt.where(AdminFile.bucket == bucket)
keyword = (q or "").strip()[:100]
if keyword:
needle = _like_contains(keyword)
count_stmt = count_stmt.where(AdminFile.filename.like(needle, escape="\\"))
stmt = stmt.where(AdminFile.filename.like(needle, escape="\\"))
total = int(db.scalar(count_stmt) or 0)
rows = db.scalars(stmt.offset((current - 1) * size).limit(size)).all()
return {
"records": [_file_body(row, with_meta=True) for row in rows],
"current": current,
"size": size,
"total": total,
}
@router.get("/files/{file_id}")
def read_file(file_id: int, db: Session = Depends(get_db)):
row = db.get(AdminFile, file_id)
if row is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
return _file_body(row, with_meta=True)
@router.delete("/files/{file_id}")
def delete_file(file_id: int, db: Session = Depends(get_db)):
row = db.get(AdminFile, file_id)
if row is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
remove_stored_object(row.bucket, row.object_key)
db.delete(row)
db.commit()
return {"id": file_id}
@router.get("/site-settings")
def read_site_settings(db: Session = Depends(get_db)):
return settings_view(db)
@router.put("/site-settings")
async def update_site_settings(request: Request, db: Session = Depends(get_db)):
try:
payload = await request.json()
except Exception:
_bad("配置项格式不正确")
if not isinstance(payload, dict):
_bad("配置项格式不正确")
save_settings(db, _normalize_settings(payload))
return settings_view(db)
@router.get("/sensitive-words")
def list_words(db: Session = Depends(get_db)):
rows = db.scalars(select(SensitiveWord).order_by(SensitiveWord.id.asc())).all()
return [_word_body(row) for row in rows]
@router.post("/sensitive-words")
def create_word(body: WordIn, db: Session = Depends(get_db)):
word = body.word.strip()
if not word:
_bad("敏感词不能为空")
if len(word) > 64:
_bad("敏感词不能超过 64 个字符")
exists = db.scalar(select(SensitiveWord.id).where(SensitiveWord.word == word))
if exists is not None:
_bad("敏感词已存在")
row = SensitiveWord(word=word)
db.add(row)
try:
db.commit()
db.refresh(row)
except IntegrityError:
db.rollback()
_bad("敏感词已存在")
return _word_body(row)
@router.delete("/sensitive-words/{word_id}")
def delete_word(word_id: int, db: Session = Depends(get_db)):
row = db.get(SensitiveWord, word_id)
if row is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="敏感词不存在")
db.delete(row)
db.commit()
return {"id": word_id}
@router.post("/content/preview-filter")
def preview_content(body: PreviewIn, db: Session = Depends(get_db)):
return preview_filter(body.html, db)
+76
View File
@@ -0,0 +1,76 @@
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.discipline import (
admin_complaint,
admin_complaints,
admin_notice,
mark_processed,
save_notice,
)
router = APIRouter(dependencies=[Depends(require_staff)])
class NoticeWrite(BaseModel):
phone: str = ""
email: str = ""
scopeHtml: str = ""
processHtml: str = ""
def _staff_id(principal: dict) -> int:
try:
return int(principal["sub"])
except (TypeError, ValueError, KeyError) as exc:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="请先登录") from exc
@router.get("/discipline/notice")
def read_notice(db: Session = Depends(get_db)) -> dict:
return admin_notice(db)
@router.put("/discipline/notice")
def write_notice(body: NoticeWrite, db: Session = Depends(get_db)) -> dict:
try:
save_notice(db, body.model_dump())
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return admin_notice(db)
@router.get("/discipline/complaints")
def list_complaints(
status_filter: str | None = Query(None, alias="status"),
db: Session = Depends(get_db),
) -> dict:
try:
return admin_complaints(db, status=status_filter)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
@router.get("/discipline/complaints/{complaint_id}")
def read_complaint(complaint_id: int, db: Session = Depends(get_db)) -> dict:
body = admin_complaint(db, complaint_id)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="投诉不存在")
return body
@router.post("/discipline/complaints/{complaint_id}/process")
def process_complaint(
complaint_id: int,
principal: dict = Depends(require_staff),
db: Session = Depends(get_db),
) -> dict:
try:
mark_processed(db, complaint_id, staff_id=_staff_id(principal))
except ValueError as exc:
code = status.HTTP_404_NOT_FOUND if str(exc) == "投诉不存在" else status.HTTP_400_BAD_REQUEST
raise HTTPException(status_code=code, detail=str(exc)) from exc
return {"ok": True}
+34
View File
@@ -0,0 +1,34 @@
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.home import admin_edu_platforms, save_edu_platforms
router = APIRouter(dependencies=[Depends(require_staff)])
class EduPlatformWrite(BaseModel):
name: str = ""
url: str = ""
imageFileId: int | None = None
sortOrder: int = 0
class EduPlatformsWrite(BaseModel):
items: list[EduPlatformWrite] = Field(default_factory=list)
@router.get("/edu/platforms")
def list_edu_platforms(db: Session = Depends(get_db)) -> dict:
return admin_edu_platforms(db)
@router.put("/edu/platforms")
def write_edu_platforms(body: EduPlatformsWrite, db: Session = Depends(get_db)) -> dict:
try:
save_edu_platforms(db, [item.model_dump() for item in body.items])
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
+63
View File
@@ -0,0 +1,63 @@
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.expert import admin_question, admin_questions, pending_count, reply_question
router = APIRouter(dependencies=[Depends(require_staff)])
class ReplyWrite(BaseModel):
bodyHtml: str = ""
attachmentFileIds: list[int] = Field(default_factory=list)
def _staff_id(principal: dict) -> int:
try:
return int(principal["sub"])
except (TypeError, ValueError, KeyError) as exc:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="请先登录") from exc
@router.get("/expert-questions/pending-count")
def read_pending_count(db: Session = Depends(get_db)) -> dict:
return {"count": pending_count(db)}
@router.get("/expert-questions")
def list_questions(
status_filter: str | None = Query(None, alias="status"),
db: Session = Depends(get_db),
) -> dict:
return admin_questions(db, status=status_filter)
@router.get("/expert-questions/{question_id}")
def read_question(question_id: int, db: Session = Depends(get_db)) -> dict:
body = admin_question(db, question_id)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="提问不存在")
return body
@router.post("/expert-questions/{question_id}/reply")
def write_reply(
question_id: int,
body: ReplyWrite,
principal: dict = Depends(require_staff),
db: Session = Depends(get_db),
) -> dict:
try:
reply_question(
db,
question_id=question_id,
staff_id=_staff_id(principal),
body_html=body.bodyHtml,
attachment_file_ids=body.attachmentFileIds,
)
except ValueError as exc:
code = status.HTTP_404_NOT_FOUND if str(exc) == "提问不存在" else status.HTTP_400_BAD_REQUEST
raise HTTPException(status_code=code, detail=str(exc)) from exc
return {"ok": True}
+323
View File
@@ -0,0 +1,323 @@
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.home import (
admin_home_view,
create_article,
create_slide,
delete_article,
delete_slide,
update_slide,
save_audiences,
save_compliance,
save_contact,
save_home,
save_honors,
save_hot_links,
save_members,
save_menu,
save_related_links,
set_article_display,
update_article,
)
router = APIRouter(dependencies=[Depends(require_staff)])
class TemplateWrite(BaseModel):
name: str
slogan: str = ""
valueProposition: str = ""
class HomeWrite(BaseModel):
activeTemplate: str
templates: list[TemplateWrite] = Field(min_length=2, max_length=2)
class ArticleDisplayWrite(BaseModel):
news: int | None = None
notices: int | None = None
policies: int | None = None
dashboard: int | None = None
class ArticleWrite(BaseModel):
category: str
title: str = ""
publishedAt: str | None = None
published: bool = False
bodyHtml: str = ""
imageFileId: int | None = None
attachmentFileIds: list[int] = Field(default_factory=list)
kind: str | None = None
class AudienceLinkWrite(BaseModel):
label: str
url: str = ""
visible: bool = True
sortOrder: int = 0
class AudienceCategoryWrite(BaseModel):
name: str
links: list[AudienceLinkWrite] = Field(default_factory=list)
class AudienceWrite(BaseModel):
categories: list[AudienceCategoryWrite] = Field(min_length=3, max_length=3)
class HotLinkWrite(BaseModel):
key: str
label: str
url: str = ""
visible: bool = True
sortOrder: int = 0
class HotLinksWrite(BaseModel):
links: list[HotLinkWrite] = Field(default_factory=list)
class ContactWrite(BaseModel):
name: str
address: str = ""
phone: str = ""
email: str = ""
latitude: float | None = None
longitude: float | None = None
class ContactBatchWrite(BaseModel):
templates: list[ContactWrite] = Field(min_length=2, max_length=2)
class RelatedLinkWrite(BaseModel):
label: str
url: str = ""
visible: bool = True
sortOrder: int = 0
class RelatedCategoryWrite(BaseModel):
name: str
links: list[RelatedLinkWrite] = Field(default_factory=list)
class RelatedLinksWrite(BaseModel):
templateName: str
categories: list[RelatedCategoryWrite] = Field(min_length=3, max_length=3)
class ComplianceWrite(BaseModel):
templateName: str
links: list[RelatedLinkWrite] = Field(default_factory=list)
class HonorItemWrite(BaseModel):
imageFileId: int
sortOrder: int = 0
class HonorWrite(BaseModel):
intervalSeconds: int = Field(gt=0)
items: list[HonorItemWrite] = Field(default_factory=list)
class MemberItemWrite(BaseModel):
name: str
url: str = ""
imageFileId: int
sortOrder: int = 0
class MemberWrite(BaseModel):
intervalSeconds: int = Field(gt=0)
items: list[MemberItemWrite] = Field(default_factory=list)
class MenuItemWrite(BaseModel):
key: str
label: str
url: str = ""
visible: bool = False
sortOrder: int = 0
class MenuWrite(BaseModel):
items: list[MenuItemWrite] = Field(default_factory=list)
class SlideWrite(BaseModel):
title: str = ""
imageFileId: int
sortOrder: int = 0
enabled: bool = True
intervalSeconds: int = Field(gt=0)
published: bool = False
bodyHtml: str = ""
attachmentFileIds: list[int] = Field(default_factory=list)
@router.get("/home")
def read_home(db: Session = Depends(get_db)) -> dict:
return admin_home_view(db)
@router.put("/home")
def write_home(body: HomeWrite, db: Session = Depends(get_db)) -> dict:
try:
save_home(
db,
body.activeTemplate,
[item.model_dump() for item in body.templates],
)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
@router.put("/home/audiences")
def write_audiences(body: AudienceWrite, db: Session = Depends(get_db)) -> dict:
try:
save_audiences(db, [item.model_dump() for item in body.categories])
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
@router.put("/home/hot-links")
def write_hot_links(body: HotLinksWrite, db: Session = Depends(get_db)) -> dict:
try:
save_hot_links(db, [item.model_dump() for item in body.links])
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
@router.put("/home/contact")
def write_contact(body: ContactBatchWrite, db: Session = Depends(get_db)) -> dict:
try:
save_contact(db, [item.model_dump() for item in body.templates])
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
@router.put("/home/related-links")
def write_related_links(body: RelatedLinksWrite, db: Session = Depends(get_db)) -> dict:
try:
save_related_links(
db,
body.templateName,
[item.model_dump() for item in body.categories],
)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
@router.put("/home/compliance")
def write_compliance(body: ComplianceWrite, db: Session = Depends(get_db)) -> dict:
try:
save_compliance(db, body.templateName, [item.model_dump() for item in body.links])
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
@router.put("/home/honors")
def write_honors(body: HonorWrite, db: Session = Depends(get_db)) -> dict:
try:
save_honors(db, body.intervalSeconds, [item.model_dump() for item in body.items])
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
@router.put("/home/members")
def write_members(body: MemberWrite, db: Session = Depends(get_db)) -> dict:
try:
save_members(db, body.intervalSeconds, [item.model_dump() for item in body.items])
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
@router.put("/home/menu")
def write_menu(body: MenuWrite, db: Session = Depends(get_db)) -> dict:
try:
save_menu(db, [item.model_dump() for item in body.items])
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
@router.put("/home/articles/display")
def write_article_display(body: ArticleDisplayWrite, db: Session = Depends(get_db)) -> dict:
try:
set_article_display(db, body.model_dump(exclude_unset=True))
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"ok": True}
@router.post("/home/articles")
def write_article(body: ArticleWrite, db: Session = Depends(get_db)) -> dict:
try:
article_id = create_article(db, body.model_dump())
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"id": article_id}
@router.put("/home/articles/{article_id}")
def revise_article(article_id: int, body: ArticleWrite, db: Session = Depends(get_db)) -> dict:
try:
update_article(db, article_id, body.model_dump())
except ValueError as exc:
code = status.HTTP_404_NOT_FOUND if str(exc) == "文章不存在" else status.HTTP_400_BAD_REQUEST
raise HTTPException(status_code=code, detail=str(exc)) from exc
return {"ok": True}
@router.delete("/home/articles/{article_id}")
def remove_article(article_id: int, db: Session = Depends(get_db)) -> dict:
try:
delete_article(db, article_id)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
return {"ok": True}
@router.post("/home/slides")
def write_slide(body: SlideWrite, db: Session = Depends(get_db)) -> dict:
try:
slide_id = create_slide(db, body.model_dump())
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"id": slide_id}
@router.put("/home/slides/{slide_id}")
def revise_slide(slide_id: int, body: SlideWrite, db: Session = Depends(get_db)) -> dict:
try:
update_slide(db, slide_id, body.model_dump())
except ValueError as exc:
code = status.HTTP_404_NOT_FOUND if str(exc) == "轮播不存在" else status.HTTP_400_BAD_REQUEST
raise HTTPException(status_code=code, detail=str(exc)) from exc
return {"ok": True}
@router.delete("/home/slides/{slide_id}")
def remove_slide(slide_id: int, db: Session = Depends(get_db)) -> dict:
try:
delete_slide(db, slide_id)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
return {"ok": True}
+42
View File
@@ -0,0 +1,42 @@
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.legal import LEGAL_PAGE_KEYS, LEGAL_PAGE_TITLES, admin_legal_page, save_legal_page
router = APIRouter(dependencies=[Depends(require_staff)])
class LegalPageWrite(BaseModel):
published: bool = False
bodyHtml: str = ""
@router.get("/legal")
def list_legal_pages(db: Session = Depends(get_db)) -> dict:
items = []
for key in LEGAL_PAGE_KEYS:
body = admin_legal_page(db, key)
if body is not None:
items.append(body)
return {"items": items}
@router.get("/legal/{page_key}")
def read_legal_page(page_key: str, db: Session = Depends(get_db)) -> dict:
body = admin_legal_page(db, page_key)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="合规页键不正确")
return body
@router.put("/legal/{page_key}")
def write_legal_page(page_key: str, body: LegalPageWrite, db: Session = Depends(get_db)) -> dict:
try:
save_legal_page(db, page_key, body.model_dump())
except ValueError as exc:
code = status.HTTP_404_NOT_FOUND if "不正确" in str(exc) else status.HTTP_400_BAD_REQUEST
raise HTTPException(status_code=code, detail=str(exc)) from exc
return {"ok": True, "title": LEGAL_PAGE_TITLES.get(page_key, page_key)}
+232
View File
@@ -0,0 +1,232 @@
from fastapi import APIRouter, Depends, Query, Request
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.services import rbac as rbac_service
public_router = APIRouter()
router = APIRouter(dependencies=[Depends(require_staff)])
class LoginIn(BaseModel):
username: str
password: str
captchaId: str = ""
captchaCode: str = ""
class OwnPasswordIn(BaseModel):
oldPassword: str
newPassword: str
class UserCreateIn(BaseModel):
username: str
password: str
displayName: str
mobile: str | None = None
roleIds: list[int] = []
class UserUpdateIn(BaseModel):
displayName: str
mobile: str | None = None
status: str
roleIds: list[int] = []
class ResetPasswordIn(BaseModel):
password: str | None = None
newPassword: str | None = None
class RoleCreateIn(BaseModel):
code: str
name: str
description: str | None = None
class RoleUpdateIn(BaseModel):
name: str
description: str | None = None
status: str
class RoleResourcesIn(BaseModel):
resourceIds: list[int] = []
class ResourceIn(BaseModel):
parentId: int | None = None
type: str
name: str
title: str
path: str | None = ""
component: str | None = ""
icon: str | None = ""
permission: str | None = ""
sort: int = 0
visible: bool = True
status: str = "active"
def _actor_id(principal: dict = Depends(require_staff)) -> int:
try:
return int(principal["sub"])
except (TypeError, ValueError):
from fastapi import HTTPException
raise HTTPException(status_code=401, detail="登录已失效")
def _resource_payload(body: ResourceIn) -> dict:
return {
"parent_id": body.parentId,
"type": body.type,
"name": body.name,
"title": body.title,
"path": body.path,
"component": body.component,
"icon": body.icon,
"permission": body.permission,
"sort": body.sort,
"visible": body.visible,
"status": body.status,
}
@public_router.post("/auth/login")
def login(body: LoginIn, request: Request, db: Session = Depends(get_db)) -> dict:
request.state.audit_username = (body.username or "").strip()[:64]
return rbac_service.authenticate(db, body.username, body.password, body.captchaId, body.captchaCode)
@router.post("/auth/password")
def change_password(
body: OwnPasswordIn,
actor_id: int = Depends(_actor_id),
db: Session = Depends(get_db),
) -> dict:
return rbac_service.change_own_password(db, actor_id, body.oldPassword, body.newPassword)
@router.get("/users")
def list_users(
current: int = Query(1, ge=1),
size: int = Query(10, ge=1, le=200),
username: str | None = None,
displayName: str | None = None,
status: str | None = None,
db: Session = Depends(get_db),
) -> dict:
return rbac_service.query_users(
db,
current=current,
size=size,
username=username,
display_name=displayName,
status_value=status,
)
@router.post("/users")
def create_user(body: UserCreateIn, db: Session = Depends(get_db)) -> dict:
return rbac_service.create_user(
db,
username=body.username,
password=body.password,
display_name=body.displayName,
mobile=body.mobile,
role_ids=body.roleIds,
)
@router.put("/users/{user_id}")
def update_user(
user_id: int,
body: UserUpdateIn,
actor_id: int = Depends(_actor_id),
db: Session = Depends(get_db),
) -> dict:
return rbac_service.update_user(
db,
user_id,
actor_id,
display_name=body.displayName,
status_value=body.status,
role_ids=body.roleIds,
mobile=body.mobile,
mobile_provided="mobile" in body.model_fields_set,
)
@router.post("/users/{user_id}/password")
def reset_password(user_id: int, body: ResetPasswordIn, db: Session = Depends(get_db)) -> dict:
plain = body.password if body.password is not None else body.newPassword
if plain is None:
from fastapi import HTTPException
raise HTTPException(status_code=400, detail="请填写密码")
return rbac_service.reset_user_password(db, user_id, plain)
@router.get("/roles")
def list_roles(
current: int = Query(1, ge=1),
size: int = Query(10, ge=1, le=200),
name: str | None = None,
code: str | None = None,
status: str | None = None,
db: Session = Depends(get_db),
) -> dict:
return rbac_service.query_roles(
db,
current=current,
size=size,
name=name,
code=code,
status_value=status,
)
@router.post("/roles")
def create_role(body: RoleCreateIn, db: Session = Depends(get_db)) -> dict:
return rbac_service.create_role(db, code=body.code, name=body.name, description=body.description)
@router.put("/roles/{role_id}")
def update_role(role_id: int, body: RoleUpdateIn, db: Session = Depends(get_db)) -> dict:
return rbac_service.update_role(
db,
role_id,
name=body.name,
description=body.description,
status_value=body.status,
)
@router.put("/roles/{role_id}/resources")
def replace_role_resources(role_id: int, body: RoleResourcesIn, db: Session = Depends(get_db)) -> dict:
return rbac_service.replace_role_resources(db, role_id, body.resourceIds)
@router.get("/resources")
def list_resources(db: Session = Depends(get_db)) -> list[dict]:
return rbac_service.list_resources(db)
@router.post("/resources")
def create_resource(body: ResourceIn, db: Session = Depends(get_db)) -> dict:
return rbac_service.create_resource(db, _resource_payload(body))
@router.put("/resources/{resource_id}")
def update_resource(resource_id: int, body: ResourceIn, db: Session = Depends(get_db)) -> dict:
return rbac_service.update_resource(db, resource_id, _resource_payload(body))
@router.delete("/resources/{resource_id}")
def delete_resource(resource_id: int, db: Session = Depends(get_db)) -> dict:
return rbac_service.delete_resource(db, resource_id)
+66
View File
@@ -0,0 +1,66 @@
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.report_filing import create_filing, delete_filing, list_filings, update_filing
router = APIRouter(dependencies=[Depends(require_staff)])
class FilingWrite(BaseModel):
institutionName: str
reportNumber: str
issuedOn: str
published: bool = False
def _raise(exc: ValueError) -> None:
code = status.HTTP_404_NOT_FOUND if str(exc) == "备案不存在" else status.HTTP_400_BAD_REQUEST
raise HTTPException(status_code=code, detail=str(exc)) from exc
@router.get("/reports")
def read_reports(db: Session = Depends(get_db)) -> dict:
return list_filings(db)
@router.post("/reports")
def write_report(body: FilingWrite, db: Session = Depends(get_db)) -> dict:
try:
filing_id = create_filing(
db,
institution_name=body.institutionName,
report_number=body.reportNumber,
issued_on=body.issuedOn,
published=body.published,
)
except ValueError as exc:
_raise(exc)
return {"id": filing_id}
@router.put("/reports/{filing_id}")
def replace_report(filing_id: int, body: FilingWrite, db: Session = Depends(get_db)) -> dict:
try:
update_filing(
db,
filing_id,
institution_name=body.institutionName,
report_number=body.reportNumber,
issued_on=body.issuedOn,
published=body.published,
)
except ValueError as exc:
_raise(exc)
return {"ok": True}
@router.delete("/reports/{filing_id}")
def remove_report(filing_id: int, db: Session = Depends(get_db)) -> dict:
try:
delete_filing(db, filing_id)
except ValueError as exc:
_raise(exc)
return {"ok": True}
+10
View File
@@ -0,0 +1,10 @@
from fastapi import APIRouter, Depends
from app.core.deps import require_staff
router = APIRouter(dependencies=[Depends(require_staff)])
@router.get("/health")
def admin_health(principal: dict = Depends(require_staff)) -> dict:
return {"status": "ok", "scope": "admin", "subject": principal["sub"]}
+177
View File
@@ -0,0 +1,177 @@
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, ConfigDict
from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.content import SiteSetting
from app.models.security import AdminAuditLog, AdminIpBlacklist
from app.services.captcha import issue_captcha
from app.services.login_guard import (
LOGIN_LOCK_MINUTES_KEY,
LOGIN_MAX_FAILURES_KEY,
read_login_policy,
)
public_router = APIRouter()
router = APIRouter(dependencies=[Depends(require_staff)])
class LoginSecurityBody(BaseModel):
model_config = ConfigDict(strict=True)
loginMaxFailures: int
loginLockMinutes: int
class IpBlacklistBody(BaseModel):
model_config = ConfigDict(strict=True)
ip: str
remark: str = ""
def _naive(value: datetime) -> datetime:
if value.tzinfo is None:
return value
return value.astimezone(timezone.utc).replace(tzinfo=None)
def _iso(value: datetime | None) -> str | None:
if value is None:
return None
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def _save_setting(db: Session, key: str, value: int) -> None:
row = db.scalar(select(SiteSetting).where(SiteSetting.key == key))
text = str(value)
if row is None:
db.add(SiteSetting(key=key, value=text))
else:
row.value = text
def _ip_item(row: AdminIpBlacklist) -> dict:
return {"id": row.id, "ip": row.ip, "remark": row.remark, "createdAt": _iso(row.created_at)}
def _audit_item(row: AdminAuditLog) -> dict:
return {
"id": row.id,
"userId": row.user_id,
"username": row.username,
"method": row.method,
"path": row.path,
"statusCode": row.status_code,
"ip": row.ip,
"createdAt": _iso(row.created_at),
}
@public_router.get("/auth/captcha")
def get_captcha() -> dict:
return issue_captcha()
@router.get("/login-security")
def get_login_security(db: Session = Depends(get_db)) -> dict:
failures, minutes = read_login_policy(db)
return {"loginMaxFailures": failures, "loginLockMinutes": minutes}
@router.put("/login-security")
def update_login_security(body: LoginSecurityBody, db: Session = Depends(get_db)) -> dict:
if body.loginMaxFailures <= 0 or body.loginLockMinutes <= 0:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="必须是正整数")
_save_setting(db, LOGIN_MAX_FAILURES_KEY, body.loginMaxFailures)
_save_setting(db, LOGIN_LOCK_MINUTES_KEY, body.loginLockMinutes)
try:
db.commit()
except IntegrityError:
db.rollback()
_save_setting(db, LOGIN_MAX_FAILURES_KEY, body.loginMaxFailures)
_save_setting(db, LOGIN_LOCK_MINUTES_KEY, body.loginLockMinutes)
db.commit()
failures, minutes = read_login_policy(db)
return {"loginMaxFailures": failures, "loginLockMinutes": minutes}
@router.get("/ip-blacklist")
def list_ip_blacklist(db: Session = Depends(get_db)) -> list[dict]:
rows = db.scalars(select(AdminIpBlacklist).order_by(AdminIpBlacklist.id.asc())).all()
return [_ip_item(row) for row in rows]
@router.post("/ip-blacklist")
def create_ip_blacklist(body: IpBlacklistBody, db: Session = Depends(get_db)) -> dict:
ip = body.ip.strip()
remark = body.remark.strip()
if not ip or len(ip) > 64 or any(char.isspace() for char in ip):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="IP 无效")
if len(remark) > 255:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="备注过长")
if db.scalar(select(AdminIpBlacklist.id).where(AdminIpBlacklist.ip == ip)) is not None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="IP 已存在")
row = AdminIpBlacklist(ip=ip, remark=remark)
db.add(row)
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="IP 已存在")
db.refresh(row)
return _ip_item(row)
@router.delete("/ip-blacklist/{id}")
def delete_ip_blacklist(id: int, db: Session = Depends(get_db)) -> dict:
row = db.get(AdminIpBlacklist, id)
if row is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="记录不存在")
db.delete(row)
db.commit()
return {"id": id}
@router.get("/audit-logs")
def list_audit_logs(
current: int = Query(1, ge=1),
size: int = Query(20, ge=1, le=200),
username: str | None = None,
startTime: datetime | None = None,
endTime: datetime | None = None,
db: Session = Depends(get_db),
) -> dict:
filters = []
if username and username.strip():
escaped = username.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
filters.append(AdminAuditLog.username.like(f"%{escaped}%", escape="\\"))
if startTime is not None:
filters.append(AdminAuditLog.created_at >= _naive(startTime))
if endTime is not None:
filters.append(AdminAuditLog.created_at <= _naive(endTime))
count_stmt = select(func.count()).select_from(AdminAuditLog)
list_stmt = select(AdminAuditLog)
if filters:
count_stmt = count_stmt.where(*filters)
list_stmt = list_stmt.where(*filters)
total = int(db.scalar(count_stmt) or 0)
rows = db.scalars(
list_stmt.order_by(AdminAuditLog.created_at.desc(), AdminAuditLog.id.desc())
.offset((current - 1) * size)
.limit(size)
).all()
return {
"records": [_audit_item(row) for row in rows],
"current": current,
"size": size,
"total": total,
}
+30
View File
@@ -0,0 +1,30 @@
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from app.core.deps import require_staff
from app.db import get_db
from app.models.uploaded_case import list_uploaded_cases, uploaded_case_detail
router = APIRouter(dependencies=[Depends(require_staff)])
@router.get("/uploaded-cases")
def read_uploaded_cases(
kind: str = Query("residential"),
current: int = Query(1),
size: int = Query(10),
q: str = Query(""),
db: Session = Depends(get_db),
) -> dict:
body = list_uploaded_cases(db, kind=kind, current=current, size=size, q=q)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="案例种类不正确")
return body
@router.get("/uploaded-cases/{case_id}")
def read_uploaded_case(case_id: int, db: Session = Depends(get_db)) -> dict:
body = uploaded_case_detail(db, case_id)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="上传案例不存在")
return body
+52
View File
@@ -0,0 +1,52 @@
from fastapi import APIRouter
from app.api.admin.about import router as admin_about_router
from app.api.admin.discipline import router as admin_discipline_router
from app.api.admin.edu import router as admin_edu_router
from app.api.admin.content import router as content_router
from app.api.admin.expert import router as admin_expert_router
from app.api.admin.uploaded_cases import router as admin_uploaded_cases_router
from app.api.admin.home import router as admin_home_router
from app.api.admin.reports import router as admin_reports_router
from app.api.admin.legal import router as admin_legal_router
from app.api.admin.rbac import public_router as rbac_public_router
from app.api.admin.rbac import router as rbac_router
from app.api.admin.routes import router as admin_router
from app.api.admin.security import public_router as security_public_router
from app.api.admin.security import router as security_router
from app.api.site.about import router as site_about_router
from app.api.site.discipline import router as site_discipline_router
from app.api.site.edu import router as site_edu_router
from app.api.site.auth import router as site_auth_router
from app.api.site.legal import router as site_legal_router
from app.api.site.member import router as member_router
from app.api.site.home import router as site_home_router
from app.api.site.public import router as site_public_router
from app.api.site.reports import router as site_reports_router
from app.api.site.settings import router as site_settings_router
api_router = APIRouter()
api_router.include_router(site_public_router, prefix="/api/site")
api_router.include_router(site_settings_router, prefix="/api/site")
api_router.include_router(site_home_router, prefix="/api/site")
api_router.include_router(site_reports_router, prefix="/api/site")
api_router.include_router(site_about_router, prefix="/api/site")
api_router.include_router(site_discipline_router, prefix="/api/site")
api_router.include_router(site_edu_router, prefix="/api/site")
api_router.include_router(site_legal_router, prefix="/api/site")
api_router.include_router(site_auth_router, prefix="/api/site")
api_router.include_router(member_router, prefix="/api/site/member")
api_router.include_router(rbac_public_router, prefix="/api/admin")
api_router.include_router(security_public_router, prefix="/api/admin")
api_router.include_router(rbac_router, prefix="/api/admin")
api_router.include_router(security_router, prefix="/api/admin")
api_router.include_router(content_router, prefix="/api/admin")
api_router.include_router(admin_home_router, prefix="/api/admin")
api_router.include_router(admin_reports_router, prefix="/api/admin")
api_router.include_router(admin_about_router, prefix="/api/admin")
api_router.include_router(admin_discipline_router, prefix="/api/admin")
api_router.include_router(admin_edu_router, prefix="/api/admin")
api_router.include_router(admin_legal_router, prefix="/api/admin")
api_router.include_router(admin_expert_router, prefix="/api/admin")
api_router.include_router(admin_uploaded_cases_router, prefix="/api/admin")
api_router.include_router(admin_router, prefix="/api/admin")
View File
Whitespace-only changes.
+44
View File
@@ -0,0 +1,44 @@
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from app.db import get_db
from app.models.about import public_about_page, public_expert, public_experts
from app.models.home import DEFAULT_COLUMN_PAGE_SIZE, public_column_articles
router = APIRouter()
@router.get("/about/pages/{page_key}")
def read_public_about_page(page_key: str, db: Session = Depends(get_db)) -> dict:
body = public_about_page(db, page_key)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="单篇页键不正确")
return body
@router.get("/about/articles/{category}")
def read_public_column_articles(
category: str,
current: int = Query(1, ge=1),
size: int = Query(DEFAULT_COLUMN_PAGE_SIZE, ge=1, le=100),
kind: str | None = Query(None),
q: str | None = Query(None),
db: Session = Depends(get_db),
) -> dict:
body = public_column_articles(db, category, current=current, size=size, kind=kind, q=q)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="文章类别不正确")
return body
@router.get("/about/experts")
def read_public_experts(db: Session = Depends(get_db)) -> dict:
return public_experts(db)
@router.get("/about/experts/{expert_id}")
def read_public_expert(expert_id: int, db: Session = Depends(get_db)) -> dict:
body = public_expert(db, expert_id)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="专家委员会不存在")
return body
+124
View File
@@ -0,0 +1,124 @@
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.core.security import create_access_token
from app.db import get_db
from app.models.member import create_member, get_member_by_email, set_member_password
from app.services.email_code import (
consume_email_code,
is_valid_email,
issue_email_code,
normalize_email,
)
from app.services.password import hash_password, validate_password, verify_password
router = APIRouter()
class EmailCodeRequest(BaseModel):
email: str
purpose: str
class RegisterRequest(BaseModel):
email: str
code: str
password: str
privacyAccepted: bool = False
class LoginRequest(BaseModel):
email: str
password: str
code: str | None = None
class ResetPasswordRequest(BaseModel):
email: str
code: str
password: str
def _bad(detail: str) -> None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)
@router.post("/auth/email-code")
def send_email_code(body: EmailCodeRequest, db: Session = Depends(get_db)) -> dict:
purpose = (body.purpose or "").strip()
email = normalize_email(body.email)
if purpose not in {"register", "login", "reset"}:
_bad("验证码用途不正确")
if not is_valid_email(email):
_bad("邮箱格式不正确")
existing = get_member_by_email(db, email)
if purpose == "register" and existing is not None:
_bad("该邮箱已注册")
if purpose in {"login", "reset"} and existing is None:
_bad("该邮箱尚未注册")
if purpose in {"login", "reset"} and existing is not None and existing.status != "active":
_bad("账号不可用")
try:
issue_email_code(email=email, purpose=purpose)
except ValueError as exc:
_bad(str(exc))
return {"ok": True}
@router.post("/auth/register")
def register(body: RegisterRequest, db: Session = Depends(get_db)) -> dict:
email = normalize_email(body.email)
if not is_valid_email(email):
_bad("邮箱格式不正确")
if not body.privacyAccepted:
_bad("请先阅读并同意隐私政策")
if get_member_by_email(db, email) is not None:
_bad("该邮箱已注册")
# 先校验密码,避免弱密码拒收时已消费验证码,用户改密后无法再用同一码。
validate_password(body.password)
if not consume_email_code(email=email, purpose="register", code=body.code):
_bad("验证码不正确或已过期")
member = create_member(
db,
email=email,
password_hash=hash_password(body.password),
privacy_accepted_at=datetime.now(timezone.utc).replace(tzinfo=None),
)
token = create_access_token(str(member.id), "member")
return {"accessToken": token, "tokenType": "member", "email": member.email}
@router.post("/auth/login")
def login(body: LoginRequest, db: Session = Depends(get_db)) -> dict:
email = normalize_email(body.email)
if not is_valid_email(email):
_bad("邮箱格式不正确")
member = get_member_by_email(db, email)
if member is None or member.status != "active":
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="邮箱或密码不正确")
if body.code is not None and str(body.code).strip():
if not consume_email_code(email=email, purpose="login", code=body.code):
_bad("验证码不正确或已过期")
if not verify_password(body.password, member.password_hash):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="邮箱或密码不正确")
token = create_access_token(str(member.id), "member")
return {"accessToken": token, "tokenType": "member", "email": member.email}
@router.post("/auth/reset-password")
def reset_password(body: ResetPasswordRequest, db: Session = Depends(get_db)) -> dict:
email = normalize_email(body.email)
if not is_valid_email(email):
_bad("邮箱格式不正确")
member = get_member_by_email(db, email)
if member is None or member.status != "active":
_bad("该邮箱尚未注册")
validate_password(body.password)
if not consume_email_code(email=email, purpose="reset", code=body.code):
_bad("验证码不正确或已过期")
set_member_password(db, member, hash_password(body.password))
token = create_access_token(str(member.id), "member")
return {"accessToken": token, "tokenType": "member", "email": member.email}
+72
View File
@@ -0,0 +1,72 @@
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status
from sqlalchemy.orm import Session
from app.db import get_db
from app.models.content import read_upload_limit
from app.models.discipline import create_complaint, public_complaint_status, public_notice
router = APIRouter()
def _content_type(value: str | None) -> str:
raw = (value or "").split(";", 1)[0].strip().lower()
return raw.replace("\r", "").replace("\n", "")[:128]
def _read_limited(upload: UploadFile, limit: int) -> bytes:
chunks = bytearray()
while True:
piece = upload.file.read(65536)
if not piece:
break
if len(chunks) + len(piece) > limit:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件超过大小上限")
chunks.extend(piece)
return bytes(chunks)
@router.get("/discipline/notice")
def read_notice(db: Session = Depends(get_db)) -> dict:
return public_notice(db)
@router.post("/discipline/complaints")
def submit_complaint(
title: str = Form(""),
subject: str = Form(""),
body: str = Form(""),
contactName: str = Form(""),
mobile: str = Form(""),
email: str = Form(""),
evidence: list[UploadFile] | None = File(default=None),
db: Session = Depends(get_db),
):
limit = read_upload_limit(db)
if limit is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="未配置上传大小上限")
files: list[tuple[str, str, bytes]] = []
for upload in evidence or []:
if upload is None or not getattr(upload, "filename", None):
continue
files.append((upload.filename, _content_type(upload.content_type), _read_limited(upload, limit)))
try:
return create_complaint(
db,
title=title,
subject=subject,
body=body,
contact_name=contactName,
mobile=mobile,
email=email,
files=files,
)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
@router.get("/discipline/complaints/{code}")
def read_complaint_status(code: str, db: Session = Depends(get_db)) -> dict:
body = public_complaint_status(db, code)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="未找到该查询码")
return body
+12
View File
@@ -0,0 +1,12 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.db import get_db
from app.models.home import public_edu_platforms
router = APIRouter()
@router.get("/edu/platforms")
def read_edu_platforms(db: Session = Depends(get_db)) -> dict:
return public_edu_platforms(db)
+28
View File
@@ -0,0 +1,28 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db import get_db
from app.models.home import public_article, public_home, public_slide
router = APIRouter()
@router.get("/home")
def read_public_home(db: Session = Depends(get_db)) -> dict:
return public_home(db)
@router.get("/home/articles/{article_id}")
def read_public_article(article_id: int, db: Session = Depends(get_db)) -> dict:
body = public_article(db, article_id)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="文章不存在")
return body
@router.get("/home/slides/{slide_id}")
def read_public_slide(slide_id: int, db: Session = Depends(get_db)) -> dict:
body = public_slide(db, slide_id)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="轮播不存在")
return body
+15
View File
@@ -0,0 +1,15 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db import get_db
from app.models.legal import public_legal_page
router = APIRouter()
@router.get("/legal/{page_key}")
def read_public_legal_page(page_key: str, db: Session = Depends(get_db)) -> dict:
body = public_legal_page(db, page_key)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="合规页键不正确")
return body
+171
View File
@@ -0,0 +1,171 @@
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from app.core.deps import require_member
from app.db import get_db
from app.models.content import AdminFile, read_upload_limit
from app.models.expert import create_question, member_question, member_questions
from app.models.member import get_member_by_id
from app.models.uploaded_case import create_uploaded_case
from app.services.storage import (
make_object_key,
private_object_url,
remove_stored_object,
safe_filename,
upload_object,
)
router = APIRouter(dependencies=[Depends(require_member)])
class QuestionWrite(BaseModel):
title: str = ""
body: str = ""
attachmentFileIds: list[int] = Field(default_factory=list)
def _member_id(principal: dict) -> int:
try:
return int(principal["sub"])
except (TypeError, ValueError, KeyError) as exc:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效") from exc
def _active_member(db: Session, principal: dict):
member = get_member_by_id(db, _member_id(principal))
if member is None or member.status != "active":
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效")
return member
def _content_type(value: str | None) -> str:
raw = (value or "").split(";", 1)[0].strip().lower()
return raw.replace("\r", "").replace("\n", "")[:128]
def _read_limited(upload: UploadFile, limit: int) -> bytes:
chunks = bytearray()
while True:
piece = upload.file.read(65536)
if not piece:
break
if len(chunks) + len(piece) > limit:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件超过大小上限")
chunks.extend(piece)
return bytes(chunks)
@router.get("/me")
def member_me(
principal: dict = Depends(require_member),
db: Session = Depends(get_db),
) -> dict:
member = _active_member(db, principal)
return {
"id": member.id,
"email": member.email,
"tokenType": principal["typ"],
}
@router.post("/files")
def upload_private_file(
file: UploadFile = File(...),
principal: dict = Depends(require_member),
db: Session = Depends(get_db),
):
member = _active_member(db, principal)
limit = read_upload_limit(db)
if limit is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="未配置上传大小上限")
data = _read_limited(file, limit)
filename = safe_filename(file.filename)
content_type = _content_type(file.content_type)
object_key = make_object_key(filename)
upload_object("private", object_key, data, content_type)
row = AdminFile(
bucket="private",
object_key=object_key,
filename=filename,
content_type=content_type,
size=len(data),
created_by=member.id,
)
db.add(row)
try:
db.commit()
db.refresh(row)
except Exception:
db.rollback()
try:
remove_stored_object("private", object_key)
except HTTPException:
pass
raise
url, expires_at = private_object_url(row.object_key)
return {
"id": row.id,
"bucket": row.bucket,
"filename": row.filename,
"contentType": row.content_type,
"size": row.size,
"url": url,
"expiresAt": expires_at.isoformat(),
}
@router.get("/expert-questions")
def list_my_questions(
principal: dict = Depends(require_member),
db: Session = Depends(get_db),
) -> dict:
member = _active_member(db, principal)
return member_questions(db, member.id)
@router.get("/expert-questions/{question_id}")
def read_my_question(
question_id: int,
principal: dict = Depends(require_member),
db: Session = Depends(get_db),
) -> dict:
member = _active_member(db, principal)
body = member_question(db, member.id, question_id)
if body is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="提问不存在")
return body
@router.post("/expert-questions")
def ask_question(
body: QuestionWrite,
principal: dict = Depends(require_member),
db: Session = Depends(get_db),
) -> dict:
member = _active_member(db, principal)
try:
question_id = create_question(
db,
member_id=member.id,
title=body.title,
body=body.body,
attachment_file_ids=body.attachmentFileIds,
)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"id": question_id}
@router.post("/uploaded-cases")
def submit_uploaded_case(
body: dict,
principal: dict = Depends(require_member),
db: Session = Depends(get_db),
) -> dict:
member = _active_member(db, principal)
try:
row = create_uploaded_case(db, member, body)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return {"id": row.id, "message": "提交成功"}
+31
View File
@@ -0,0 +1,31 @@
from fastapi import APIRouter
from app.models.uploaded_case import (
KIND_LABELS,
OPEN_KINDS,
commercial_options,
office_options,
regions,
residential_options,
industrial_options,
)
router = APIRouter()
@router.get("/health")
def site_health() -> dict:
return {"status": "ok", "scope": "site"}
@router.get("/uploaded-case-options")
def uploaded_case_options() -> dict:
return {
"kinds": [{"key": key, "label": label} for key, label in KIND_LABELS.items()],
"openKinds": [key for key in KIND_LABELS if key in OPEN_KINDS],
"regions": regions(),
"residential": residential_options(),
"commercial": commercial_options(),
"office": office_options(),
"industrial": industrial_options(),
}
+15
View File
@@ -0,0 +1,15 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db import get_db
from app.models.report_filing import query_filing
router = APIRouter()
@router.get("/reports/query")
def read_report_query(number: str = "", db: Session = Depends(get_db)) -> dict:
try:
return query_filing(db, number)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
+23
View File
@@ -0,0 +1,23 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.db import get_db
from app.models.content import settings_view
router = APIRouter()
@router.get("/settings")
def read_public_settings(db: Session = Depends(get_db)) -> dict:
# 只返回门户展示字段。上传上限和登录锁定参数留在管理端。
data = settings_view(db)
return {
"siteName": data["site_name"],
"logoUrl": data["logoUrl"],
"bannerUrls": data["bannerUrls"],
"icpText": data["icp_text"],
"policeText": data["police_text"],
"friendLinks": data["friend_links"],
"linkCirea": data["link_cirea"],
"linkHousing": data["link_housing"],
}
+1
View File
@@ -0,0 +1 @@
"""管理命令。"""
+990
View File
@@ -0,0 +1,990 @@
import os
import sys
from fastapi import HTTPException
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.db import Base, SessionLocal, get_engine
from app.models.rbac import AdminResource, AdminRole, AdminRoleResource, AdminUser, AdminUserRole, utcnow
from app.services.password import hash_password, validate_password
SUPER_CODE = "R_SUPER"
SUPER_NAME = "超级管理员"
PAGES = [
{
"name": "User",
"title": "用户管理",
"path": "/system/user",
"component": "/system/user",
"sort": 1,
"buttons": [
("user:add", "新增"),
("user:edit", "编辑"),
("user:reset-password", "重置密码"),
("user:disable", "停用"),
("user:cancel", "注销"),
],
},
{
"name": "Role",
"title": "角色管理",
"path": "/system/role",
"component": "/system/role",
"sort": 2,
"buttons": [
("role:add", "新增"),
("role:edit", "编辑"),
("role:disable", "停用"),
("role:grant", "授权"),
],
},
{
"name": "Menu",
"title": "菜单管理",
"path": "/system/menu",
"component": "/system/menu",
"sort": 3,
"buttons": [
("menu:add", "新增"),
("menu:edit", "编辑"),
("menu:delete", "删除"),
],
},
{
"name": "AuditLog",
"title": "操作日志",
"path": "/system/audit-log",
"component": "/system/audit-log",
"sort": 4,
"buttons": [],
},
{
"name": "LoginSecurity",
"title": "登录安全",
"path": "/system/login-security",
"component": "/system/login-security",
"sort": 5,
"buttons": [("security:edit", "编辑")],
},
{
"name": "File",
"title": "附件",
"path": "/system/file",
"component": "/system/file",
"sort": 6,
"buttons": [("file:upload", "上传"), ("file:delete", "删除")],
},
{
"name": "Site",
"title": "站点配置",
"path": "/system/site",
"component": "/system/site",
"sort": 7,
"buttons": [("site:edit", "编辑")],
},
{
"name": "SensitiveWord",
"title": "敏感词",
"path": "/system/sensitive-word",
"component": "/system/sensitive-word",
"sort": 8,
"buttons": [("word:add", "新增"), ("word:delete", "删除"), ("word:preview", "预览")],
},
]
def _find_resource(db: Session, parent_id: int | None, name: str) -> AdminResource | None:
stmt = select(AdminResource).where(AdminResource.name == name)
if parent_id is None:
stmt = stmt.where(AdminResource.parent_id.is_(None))
else:
stmt = stmt.where(AdminResource.parent_id == parent_id)
return db.scalars(stmt.order_by(AdminResource.id.asc())).first()
def _ensure_resource(
db: Session,
*,
parent_id: int | None,
resource_type: str,
name: str,
title: str,
path: str,
component: str,
icon: str,
permission: str,
sort: int,
visible: bool,
) -> AdminResource:
row = _find_resource(db, parent_id, name)
if row is None:
row = AdminResource(
parent_id=parent_id,
type=resource_type,
name=name,
title=title,
path=path,
component=component,
icon=icon,
permission=permission,
sort=sort,
visible=visible,
status="active",
)
db.add(row)
db.flush()
return row
row.parent_id = parent_id
row.type = resource_type
row.title = title
row.path = path
row.component = component
row.icon = icon
row.permission = permission
row.sort = sort
row.visible = visible
row.status = "active"
return row
HOME_MENUS = (
("HomeTemplate", "模板", "/home/template", "ri:layout-2-line", 1),
("HomeSlides", "轮播", "/home/slides", "ri:slideshow-3-line", 2),
("HomeArticles", "文章", "/home/articles", "ri:article-line", 3),
("HomeEntries", "入口与菜单", "/home/entries", "ri:apps-2-line", 4),
("HomeMarquees", "荣誉与会员", "/home/marquees", "ri:award-line", 5),
("HomeFooter", "页脚", "/home/footer", "ri:layout-bottom-line", 6),
)
ABOUT_ORG_MENUS = (
("AboutIntro", "协会简介", "/about/intro", "ri:building-line", 1),
("AboutOrg", "组织机构", "/about/org", "ri:node-tree", 2),
("AboutExperts", "专家委员会", "/about/experts", "ri:team-line", 3),
("AboutReports", "年度报告/工作计划", "/about/reports", "ri:file-list-3-line", 4),
("AboutBriefs", "工作简报", "/about/briefs", "ri:newspaper-line", 5),
)
def ensure_home_menu(db: Session) -> None:
directory = _ensure_resource(
db,
parent_id=None,
resource_type="directory",
name="Home",
title="首页配置",
path="/home",
component="",
icon="ri:home-4-line",
permission="",
sort=2,
visible=True,
)
legacy = _find_resource(db, directory.id, "HomeConfig")
if legacy is not None and _find_resource(db, directory.id, "HomeTemplate") is None:
legacy.name = "HomeTemplate"
db.flush()
pages = [
_ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name=name,
title=title,
path=path,
component=path,
icon=icon,
permission="",
sort=sort,
visible=True,
)
for name, title, path, icon, sort in HOME_MENUS
]
button = _ensure_resource(
db,
parent_id=pages[0].id,
resource_type="button",
name="home:edit",
title="保存",
path="",
component="",
icon="",
permission="home:edit",
sort=1,
visible=False,
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
).all()
)
for resource_id in (directory.id, button.id, *(page.id for page in pages)):
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def ensure_party_menu(db: Session) -> None:
party = _ensure_resource(
db,
parent_id=None,
resource_type="menu",
name="PartyBuilding",
title="行业党建",
path="/party",
component="/party",
icon="iconoven:national-emblem",
permission="",
sort=5,
visible=True,
)
button = _ensure_resource(
db,
parent_id=party.id,
resource_type="button",
name="party:edit",
title="保存",
path="",
component="",
icon="",
permission="party:edit",
sort=1,
visible=False,
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
).all()
)
for resource_id in (party.id, button.id):
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def ensure_expert_menu(db: Session) -> None:
directory = _ensure_resource(
db,
parent_id=None,
resource_type="directory",
name="ExpertService",
title="专家服务",
path="/expert",
component="",
icon="ri:customer-service-2-line",
permission="",
sort=6,
visible=True,
)
guides = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="ExpertGuides",
title="估价指南",
path="/expert/guides",
component="/expert/guides",
icon="ri:book-open-line",
permission="",
sort=1,
visible=True,
)
qa = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="ExpertQa",
title="专家答疑",
path="/expert/qa",
component="/expert/qa",
icon="ri:question-answer-line",
permission="",
sort=2,
visible=True,
)
edit_button = _ensure_resource(
db,
parent_id=guides.id,
resource_type="button",
name="expert:edit",
title="保存",
path="",
component="",
icon="",
permission="expert:edit",
sort=1,
visible=False,
)
reply_button = _ensure_resource(
db,
parent_id=qa.id,
resource_type="button",
name="expert:reply",
title="回复",
path="",
component="",
icon="",
permission="expert:reply",
sort=1,
visible=False,
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
).all()
)
for resource_id in (directory.id, guides.id, qa.id, edit_button.id, reply_button.id):
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def ensure_directory_menu(db: Session) -> None:
directory = _ensure_resource(
db,
parent_id=None,
resource_type="menu",
name="InstitutionDirectory",
title="机构名录",
path="/institutions",
component="/institutions",
icon="ri:building-2-line",
permission="",
sort=8,
visible=True,
)
button = _ensure_resource(
db,
parent_id=directory.id,
resource_type="button",
name="directory:edit",
title="保存",
path="",
component="",
icon="",
permission="directory:edit",
sort=1,
visible=False,
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
).all()
)
for resource_id in (directory.id, button.id):
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def ensure_library_menu(db: Session) -> None:
directory = _ensure_resource(
db,
parent_id=None,
resource_type="directory",
name="Library",
title="资料库",
path="/library",
component="",
icon="ri:folder-open-line",
permission="",
sort=9,
visible=True,
)
policies = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="LibraryPolicies",
title="政策分析",
path="/library/policies",
component="/library/policies",
icon="ri:file-text-line",
permission="",
sort=1,
visible=True,
)
cases = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="LibraryCases",
title="案例库",
path="/library/cases",
component="/library/cases",
icon="ri:archive-line",
permission="",
sort=2,
visible=True,
)
policy_button = _ensure_resource(
db,
parent_id=policies.id,
resource_type="button",
name="library:edit",
title="保存",
path="",
component="",
icon="",
permission="library:edit",
sort=1,
visible=False,
)
case_button = _ensure_resource(
db,
parent_id=cases.id,
resource_type="button",
name="library:edit",
title="保存",
path="",
component="",
icon="",
permission="library:edit",
sort=1,
visible=False,
)
uploads = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="LibraryUploads",
title="上传的案例库",
path="/library/uploads",
component="/library/uploads",
icon="ri:upload-2-line",
permission="",
sort=3,
visible=True,
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
).all()
)
for resource_id in (directory.id, policies.id, cases.id, uploads.id, policy_button.id, case_button.id):
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def ensure_report_menu(db: Session) -> None:
menu = _ensure_resource(
db,
parent_id=None,
resource_type="menu",
name="ReportCenter",
title="报告中心",
path="/reports",
component="/reports",
icon="ri:file-list-3-line",
permission="",
sort=10,
visible=True,
)
button = _ensure_resource(
db,
parent_id=menu.id,
resource_type="button",
name="report:edit",
title="保存",
path="",
component="",
icon="",
permission="report:edit",
sort=1,
visible=False,
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)).all()
)
for resource_id in (menu.id, button.id):
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def ensure_discipline_menu(db: Session) -> None:
directory = _ensure_resource(
db,
parent_id=None,
resource_type="directory",
name="IndustryDiscipline",
title="行业自律",
path="/discipline",
component="",
icon="ri:shield-check-line",
permission="",
sort=11,
visible=True,
)
complaints = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="DisciplineComplaints",
title="投诉举报",
path="/discipline/complaints",
component="/discipline/complaints",
icon="ri:feedback-line",
permission="",
sort=1,
visible=True,
)
warnings = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="DisciplineWarnings",
title="警示案例",
path="/discipline/warnings",
component="/discipline/warnings",
icon="ri:alarm-warning-line",
permission="",
sort=2,
visible=True,
)
integrity = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="DisciplineIntegrity",
title="诚信档案",
path="/discipline/integrity",
component="/discipline/integrity",
icon="ri:medal-line",
permission="",
sort=3,
visible=True,
)
results = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name="DisciplineResults",
title="结果公示",
path="/discipline/results",
component="/discipline/results",
icon="ri:megaphone-line",
permission="",
sort=4,
visible=True,
)
handle_button = _ensure_resource(
db,
parent_id=complaints.id,
resource_type="button",
name="discipline:handle",
title="处理",
path="",
component="",
icon="",
permission="discipline:handle",
sort=1,
visible=False,
)
edit_buttons = []
for parent in (warnings, integrity, results):
edit_buttons.append(
_ensure_resource(
db,
parent_id=parent.id,
resource_type="button",
name="discipline:edit",
title="保存",
path="",
component="",
icon="",
permission="discipline:edit",
sort=1,
visible=False,
)
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
).all()
)
resource_ids = [
directory.id,
complaints.id,
warnings.id,
integrity.id,
results.id,
handle_button.id,
*(button.id for button in edit_buttons),
]
for resource_id in resource_ids:
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def ensure_edu_menu(db: Session) -> None:
menu = _ensure_resource(
db,
parent_id=None,
resource_type="menu",
name="ContinuingEducation",
title="继续教育",
path="/edu",
component="/edu",
icon="ri:graduation-cap-line",
permission="",
sort=4,
visible=True,
)
button = _ensure_resource(
db,
parent_id=menu.id,
resource_type="button",
name="edu:edit",
title="保存",
path="",
component="",
icon="",
permission="edu:edit",
sort=1,
visible=False,
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
).all()
)
for resource_id in (menu.id, button.id):
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def ensure_tech_menu(db: Session) -> None:
tech = _ensure_resource(
db,
parent_id=None,
resource_type="menu",
name="TechExchange",
title="技术交流",
path="/tech",
component="/tech",
icon="ri:discuss-line",
permission="",
sort=7,
visible=True,
)
button = _ensure_resource(
db,
parent_id=tech.id,
resource_type="button",
name="tech:edit",
title="保存",
path="",
component="",
icon="",
permission="tech:edit",
sort=1,
visible=False,
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
).all()
)
for resource_id in (tech.id, button.id):
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def ensure_about_menu(db: Session) -> None:
org_dir = _ensure_resource(
db,
parent_id=None,
resource_type="directory",
name="AboutOrgDir",
title="组织概况",
path="/about",
component="",
icon="ri:building-4-line",
permission="",
sort=3,
visible=True,
)
org_pages = [
_ensure_resource(
db,
parent_id=org_dir.id,
resource_type="menu",
name=name,
title=title,
path=path,
component=path,
icon=icon,
permission="",
sort=sort,
visible=True,
)
for name, title, path, icon, sort in ABOUT_ORG_MENUS
]
qualifications = _ensure_resource(
db,
parent_id=None,
resource_type="menu",
name="AboutQualifications",
title="资质荣誉",
path="/about/qualifications",
component="/about/qualifications",
icon="ri:medal-line",
permission="",
sort=4,
visible=True,
)
contact = _ensure_resource(
db,
parent_id=None,
resource_type="menu",
name="AboutContact",
title="联系合作",
path="/about/contact",
component="/about/contact",
icon="ri:contacts-line",
permission="",
sort=6,
visible=True,
)
button = _ensure_resource(
db,
parent_id=org_pages[0].id,
resource_type="button",
name="about:edit",
title="保存",
path="",
component="",
icon="",
permission="about:edit",
sort=1,
visible=False,
)
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
db.flush()
return
linked = set(
db.scalars(
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
).all()
)
resource_ids = (
org_dir.id,
button.id,
qualifications.id,
contact.id,
*(page.id for page in org_pages),
)
for resource_id in resource_ids:
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.flush()
def seed_superuser(db: Session, username: str, password: str) -> None:
username = username.strip()
if not username:
raise HTTPException(status_code=400, detail="请填写用户名")
if len(username) > 64:
raise HTTPException(status_code=400, detail="用户名过长")
validate_password(password)
now = utcnow()
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
if role is None:
role = AdminRole(
code=SUPER_CODE,
name=SUPER_NAME,
description="系统内置角色",
status="active",
created_at=now,
updated_at=now,
)
db.add(role)
db.flush()
else:
role.name = SUPER_NAME
role.status = "active"
if not role.description:
role.description = "系统内置角色"
role.updated_at = now
directory = _ensure_resource(
db,
parent_id=None,
resource_type="directory",
name="System",
title="系统管理",
path="/system",
component="",
icon="ri:settings-3-line",
permission="",
sort=1,
visible=True,
)
resource_ids = [directory.id]
for page in PAGES:
menu = _ensure_resource(
db,
parent_id=directory.id,
resource_type="menu",
name=page["name"],
title=page["title"],
path=page["path"],
component=page["component"],
icon="",
permission="",
sort=page["sort"],
visible=True,
)
resource_ids.append(menu.id)
for index, (code, title) in enumerate(page["buttons"], start=1):
button = _ensure_resource(
db,
parent_id=menu.id,
resource_type="button",
name=code,
title=title,
path="",
component="",
icon="",
permission=code,
sort=index,
visible=False,
)
resource_ids.append(button.id)
linked = set(
db.scalars(select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)).all()
)
for resource_id in resource_ids:
if resource_id not in linked:
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
user = db.scalar(select(AdminUser).where(AdminUser.username == username))
password_hash = hash_password(password)
if user is None:
user = AdminUser(
username=username,
password_hash=password_hash,
display_name=username,
mobile_mask="",
status="active",
failed_login_count=0,
locked_until=None,
created_at=now,
updated_at=now,
)
db.add(user)
db.flush()
else:
user.password_hash = password_hash
user.status = "active"
user.failed_login_count = 0
user.locked_until = None
if not user.display_name:
user.display_name = username
user.updated_at = now
if db.get(AdminUserRole, (user.id, role.id)) is None:
db.add(AdminUserRole(user_id=user.id, role_id=role.id))
db.flush()
ensure_home_menu(db)
def main() -> int:
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
username = os.environ.get("BOOTSTRAP_ADMIN_USERNAME", "").strip()
password = os.environ.get("BOOTSTRAP_ADMIN_PASSWORD", "")
if username == "" or password == "":
print("缺少环境变量 BOOTSTRAP_ADMIN_USERNAME 或 BOOTSTRAP_ADMIN_PASSWORD", file=sys.stderr)
return 1
try:
validate_password(password)
except HTTPException as exc:
print(exc.detail, file=sys.stderr)
return 1
db: Session | None = None
try:
import app.models.content # noqa: F401
import app.models.security # noqa: F401
from app.models.content import ensure_site_defaults
from app.services.ip_guard import seed_ip_blacklist
engine = get_engine()
Base.metadata.create_all(bind=engine)
SessionLocal.configure(bind=engine)
db = SessionLocal()
ensure_site_defaults(db)
seed_ip_blacklist(db)
seed_superuser(db, username, password)
db.commit()
except RuntimeError as exc:
print(str(exc), file=sys.stderr)
return 1
except HTTPException as exc:
if db is not None:
db.rollback()
print(exc.detail, file=sys.stderr)
return 1
except Exception:
if db is not None:
db.rollback()
print("创建超级管理员失败", file=sys.stderr)
return 1
finally:
if db is not None:
db.close()
print(f"超级管理员已就绪:{username}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,67 @@
"""把现站机构备案整栏一次性写入机构名录。
样例已保存在本命令旁的 fixtures 中。重复执行按标题更新同一条,不新增重复标题。
口令只从环境变量读取。测试不访问现站。
"""
from __future__ import annotations
import gzip
import json
from pathlib import Path
from sqlalchemy import select
from app.db import Base, SessionLocal, get_engine
from app.models.home import HomeArticle, create_article, ensure_article_body_capacity, update_article
FIXTURE = Path(__file__).resolve().parent / "fixtures" / "institution_directories.json.gz"
CATEGORY = "institution_directories"
def load_fixture(path: Path | None = None) -> list[dict]:
payload = gzip.decompress((path or FIXTURE).read_bytes())
raw = json.loads(payload.decode("utf-8"))
if not isinstance(raw, list) or len(raw) != 16:
raise ValueError("机构名录样例必须是 16 条")
return raw
def import_institution_directories(db, items: list[dict] | None = None) -> None:
records = items if items is not None else load_fixture()
for record in records:
title = record["title"]
payload = {
"category": CATEGORY,
"title": title,
"publishedAt": record["publishedAt"],
"published": True,
"bodyHtml": record["bodyHtml"],
"attachmentFileIds": [],
}
existing = db.scalar(
select(HomeArticle.id).where(
HomeArticle.category == CATEGORY,
HomeArticle.title == title,
)
)
if existing is None:
create_article(db, payload)
else:
update_article(db, existing, payload)
def main() -> None:
engine = get_engine()
Base.metadata.create_all(bind=engine)
SessionLocal.configure(bind=engine)
db = SessionLocal()
try:
ensure_article_body_capacity(db)
import_institution_directories(db)
finally:
db.close()
if __name__ == "__main__":
main()
+358
View File
@@ -0,0 +1,358 @@
"""把现站公开摘录写入「关于协会」相关模块,供测试环境查看。
数据来自仓库 docs/参考/现站/基础数据。重复执行会清掉关于协会单篇、专家委员会
与三类栏目文章后重写。口令只从环境变量读取。
"""
from __future__ import annotations
from html import escape, unescape
from pathlib import Path
from sqlalchemy import delete, select
from app.db import Base, SessionLocal, get_engine
from app.models.about import (
AboutExpert,
AboutExpertAttachment,
AboutPage,
AboutPageAttachment,
create_expert,
save_about_page,
)
from app.models.content import AdminFile
from app.models.home import (
HomeArticle,
HomeArticleAttachment,
create_article,
)
ABOUT_COLUMN_CATEGORIES = ("annual_reports", "work_briefs", "qualifications")
from app.services.storage import ensure_buckets, make_object_key, upload_object
ROOT = Path(__file__).resolve().parents[3]
SOURCE = ROOT / "docs" / "参考" / "现站" / "基础数据"
ABOUT_DIR = SOURCE / "协会介绍"
NEWS = SOURCE / "新闻动态"
CONTACT = SOURCE / "联系我们" / "contact.json"
def _paragraphs_from_lines(lines: list[str]) -> str:
parts = []
for line in lines:
line = line.strip()
if not line:
continue
parts.append(f"<p>{escape(line)}</p>")
return "".join(parts)
def _paragraphs(path: Path) -> str:
text = unescape(path.read_text(encoding="utf-8"))
return _paragraphs_from_lines(text.splitlines())
def _content_type(path: Path) -> str:
suffix = path.suffix.lower()
if suffix == ".png":
return "image/png"
if suffix == ".webp":
return "image/webp"
if suffix == ".gif":
return "image/gif"
if suffix == ".pdf":
return "application/pdf"
return "image/jpeg"
def _store_public(db, path: Path, filename: str | None = None) -> AdminFile:
name = filename or f"about-sample-{path.name}"
row = db.scalar(
select(AdminFile).where(AdminFile.bucket == "public", AdminFile.filename == name)
)
if row is not None:
return row
data = path.read_bytes()
key = make_object_key(name)
upload_object("public", key, data, _content_type(path))
row = AdminFile(
bucket="public",
object_key=key,
filename=name,
content_type=_content_type(path),
size=len(data),
created_by=None,
)
db.add(row)
db.commit()
db.refresh(row)
return row
def _clear_about(db) -> None:
article_ids = list(
db.scalars(
select(HomeArticle.id).where(HomeArticle.category.in_(ABOUT_COLUMN_CATEGORIES))
).all()
)
if article_ids:
db.execute(
delete(HomeArticleAttachment).where(HomeArticleAttachment.article_id.in_(article_ids))
)
db.execute(delete(HomeArticle).where(HomeArticle.id.in_(article_ids)))
db.execute(delete(AboutExpertAttachment))
db.execute(delete(AboutExpert))
db.execute(delete(AboutPageAttachment))
db.execute(delete(AboutPage))
db.commit()
def _intro_html() -> str:
page = (ABOUT_DIR / "栏目页.txt").read_text(encoding="utf-8")
lines = []
for line in page.splitlines():
line = line.strip()
if not line:
continue
if line.startswith("来源:") or line in {
"计时中",
"首页",
"协会介绍",
"新闻中心",
"通知公告",
"新闻动态",
"政策法规",
"执业注册",
"继续教育",
"机构备案",
"会员服务",
"案例中心",
"联系我们",
"关于我们",
"当前位置 :",
"地址:",
"电话:",
"手机:",
"邮箱:",
"版权所有:",
"甘肃省房地产价格评估行业协会",
}:
continue
if line.startswith("|||") or line in {"넳", "넲", "끠", "搜索"}:
continue
if line.startswith("首页 ") or "甘肃省兰州市" in line and len(line) < 40:
if line.startswith("甘肃省兰州市") or line.startswith("0931") or "@" in line:
continue
continue
if line.startswith("甘肃省房地产价格评估行业协会(以下简称我会)"):
lines.append(line)
elif line.startswith("我会"):
lines.append(line)
lines.append("整理自现站公开页面:http://www.gsrea.org.cn/xhjs")
return _paragraphs_from_lines(lines)
def _org_html() -> str:
lines = [
"我会日常办事机构为协会秘书处,秘书处下设综合办公室,在理事会领导下负责处理日常事务。",
"理事会共有理事若干人,会员单位若干家(以现站公开信息为准)。",
"协会下设五个专业委员会:",
"一、专家委员会:负责重大疑难估价技术咨询与行业标准解读。",
"二、自律委员会:围绕投诉争议、执业风险提示与行业诚信建设开展工作。",
"三、技术委员会:组织估价技术研讨、典型案例交流与报告质量提升。",
"四、培训交流委员会:衔接继续教育、培训计划与对外交流。",
"五、信息化建设委员会:推进行业信息化与资料库、案例库建设。",
"整理自现站协会介绍:http://www.gsrea.org.cn/xhjs",
]
return _paragraphs_from_lines(lines)
def _contact_html() -> str:
import json
contact = json.loads(CONTACT.read_text(encoding="utf-8")) if CONTACT.is_file() else {}
address = contact.get("address") or "甘肃省兰州市城关区张掖路63号"
phone = contact.get("phone") or "0931-8126195"
email = contact.get("email") or "gsrea2018@163.com"
lines = [
"来访路线 / 电话联系方式",
f"办公地址:{address}",
f"电话:{phone}",
f"邮箱:{email}",
"来访请先电话预约。公交与停车指引可现场或电话咨询秘书处。",
"合作洽谈",
"结构合作、学术合作、商务合作意向,请将单位介绍与合作方向发送至协会邮箱,秘书处将协调对接。",
"加入协会指南",
"我会的会员分为个人会员和单位会员。个人会员分为房地产估价师执业会员、房地产价格评估经纪人执业会员;单位会员分为团体会员、理事单位会员和会长(秘书长)单位会员。",
"凡承认《甘肃省房地产价格评估行业协会章程》、具备会员条件的个人和单位均可申请入会。入会一般程序:提交入会申请书 → 理事会讨论通过 → 颁发会员证。",
"会费标准与管理办法以协会现行文件为准,正式文本可在会员服务栏目或向秘书处索取。",
f"整理自现站联系我们:{contact.get('url') or 'http://www.gsrea.org.cn/lxwm'}",
]
return _paragraphs_from_lines(lines)
def _news_article(article_id: int) -> tuple[str, str]:
folder = NEWS / "文章" / str(article_id)
meta = __import__("json").loads((folder / "meta.json").read_text(encoding="utf-8"))
body = _paragraphs(folder / "content.txt")
body += f"<p>整理自现站公开页面:{escape(meta.get('url') or '')}</p>"
return meta.get("title") or str(article_id), body
def seed() -> None:
import app.models.about # noqa: F401
import app.models.content # noqa: F401
import app.models.home # noqa: F401
ensure_buckets()
engine = get_engine()
Base.metadata.create_all(bind=engine)
db = SessionLocal()
try:
_clear_about(db)
save_about_page(
db,
"intro",
{"published": True, "bodyHtml": _intro_html(), "attachmentFileIds": []},
)
save_about_page(
db,
"org",
{"published": True, "bodyHtml": _org_html(), "attachmentFileIds": []},
)
save_about_page(
db,
"contact",
{"published": True, "bodyHtml": _contact_html(), "attachmentFileIds": []},
)
committees = [
("专家委员会", "负责重大疑难估价技术咨询与行业标准解读,服务会员机构与估价师。", 1),
("自律委员会", "围绕投诉争议、执业风险提示与行业诚信建设,推动自律公约落地。", 2),
("技术委员会", "组织估价技术研讨、典型案例交流与报告质量提升活动。", 3),
("培训交流委员会", "衔接继续教育、培训计划与对外交流,提升从业人员专业水平。", 4),
("信息化建设委员会", "推进行业信息化、交易案例库与资料库建设。", 5),
]
for name, blurb, order in committees:
create_expert(
db,
{
"name": name,
"bodyHtml": _paragraphs_from_lines(
[
blurb,
"成员名单与正式任命以协会最新公示为准。",
"整理自现站协会介绍公开信息。",
]
),
"sortOrder": order,
"published": True,
"attachmentFileIds": [],
},
)
# 年度报告 / 工作计划:理事会工作报告相关现站新闻
report_title, report_body = _news_article(8560786)
create_article(
db,
{
"category": "annual_reports",
"title": report_title[:200],
"publishedAt": "2025-07-24T16:00:00",
"published": True,
"bodyHtml": report_body,
"imageFileId": None,
"attachmentFileIds": [],
},
)
create_article(
db,
{
"category": "annual_reports",
"title": "2018年度工作报告及2019年工作计划(会议公开摘要)",
"publishedAt": "2019-04-26T16:00:00",
"published": True,
"bodyHtml": _paragraphs(
ABOUT_DIR / "文章" / "1209332" / "content.txt"
)
+ "<p>整理自现站:http://www.gsrea.org.cn/newsinfo/1209332.html</p>",
"imageFileId": None,
"attachmentFileIds": [],
},
)
# 工作简报:用现站新闻形态条目
for article_id, published_at in (
(8560786, "2025-07-24T16:00:00"),
(7911765, "2024-12-31T10:00:00"),
):
title, body = _news_article(article_id)
create_article(
db,
{
"category": "work_briefs",
"title": f"工作简报 · {title[:180]}",
"publishedAt": published_at,
"published": True,
"bodyHtml": body,
"imageFileId": None,
"attachmentFileIds": [],
},
)
# 资质荣誉:喜报 + 表彰图片
honor_title, honor_body = _news_article(7911765)
honor_images = []
for picture in sorted((ABOUT_DIR / "文章" / "1209332" / "images").glob("*.jpg"))[:2]:
honor_images.append(_store_public(db, picture, f"about-honor-{picture.name}").id)
image_tags = "".join(
f'<p><img src="{escape(_public_url(db, file_id))}" alt="协会荣誉示意"></p>'
for file_id in honor_images
)
create_article(
db,
{
"category": "qualifications",
"title": honor_title[:200],
"publishedAt": "2024-12-31T10:00:00",
"published": True,
"bodyHtml": honor_body + image_tags,
"imageFileId": honor_images[0] if honor_images else None,
"attachmentFileIds": honor_images[1:] if len(honor_images) > 1 else [],
},
)
create_article(
db,
{
"category": "qualifications",
"title": "优秀报告评选表彰与行业交流(公开纪要)",
"publishedAt": "2019-04-26T12:00:00",
"published": True,
"bodyHtml": _paragraphs(ABOUT_DIR / "文章" / "1209332" / "content.txt")
+ "<p>整理自现站表彰会议公开报道。</p>",
"imageFileId": honor_images[0] if honor_images else None,
"attachmentFileIds": [],
},
)
print(
"关于协会测试数据已写入:协会简介/组织机构/联系合作各 1 篇,"
f"专家委员会 {len(committees)} 条,"
"年度报告/工作计划 2 条,工作简报 2 条,资质荣誉 2 条。"
)
finally:
db.close()
def _public_url(db, file_id: int) -> str:
from app.services.storage import public_object_url
row = db.get(AdminFile, file_id)
if row is None or not row.object_key:
return ""
return public_object_url(row.object_key)
if __name__ == "__main__":
seed()
@@ -0,0 +1,216 @@
"""写入行业自律演示数据:投诉说明、举报记录,以及警示案例、诚信档案、结果公示。
重复执行不会覆盖工作人员已填写的说明,也不会重复插入同标题的记录。
口令只从环境变量读取。
"""
from __future__ import annotations
import sys
from datetime import datetime, timedelta, timezone
from sqlalchemy import select
from app.db import Base, SessionLocal, get_engine
from app.models.discipline import (
DisciplineComplaint,
admin_notice,
create_complaint,
mark_processed,
save_notice,
)
from app.models.home import HomeArticle, create_article
from app.models.rbac import AdminUser
from app.services.storage import ensure_buckets
NOTICE = {
"phone": "0931-8126195",
"email": "gsrea2018@163.com",
"scopeHtml": (
"<p>受理会员机构、注册房地产估价师在估价执业中的下列情形:</p>"
"<ul>"
"<li>出具与现场查勘情况明显不符的估价报告;</li>"
"<li>比较案例选取明显不当,或遗漏影响价值的重要因素;</li>"
"<li>收费未按公示标准,或存在不正当竞争;</li>"
"<li>泄露委托人商业秘密或个人隐私。</li>"
"</ul>"
"<p>司法诉讼、已经行政机关立案的案件,以及与估价执业无关的消费纠纷,不由本会受理。</p>"
),
"processHtml": (
"<p>1. 登记。核对材料是否齐全,并生成内部查询码。</p>"
"<p>2. 核查。秘书处转相关专业委员会,必要时向被举报对象核实。</p>"
"<p>3. 处理。形成处理意见,按情节给予约谈、通报,或建议行政主管部门处理。</p>"
"<p>4. 反馈。在承诺时限内答复举报人,并将可公开的结果发布到结果公示。</p>"
),
}
EVIDENCE = (
"证据说明.txt",
"text/plain",
"演示材料:现场查勘记录与报告摘录对照说明,仅供界面查看。".encode(),
)
COMPLAINTS = [
{
"title": "比较案例选取明显不当",
"subject": "兰州示例房地产估价有限公司",
"body": "委托人对住宅估价报告提出异议,认为三宗比较案例均位于不同板块,且未说明修正理由。",
"contact_name": "周宁",
"mobile": "13800001001",
"email": "zhou.ning@example.com",
"days_ago": 6,
"processed": False,
},
{
"title": "收费未按公示标准执行",
"subject": "天水示例评估事务所",
"body": "机构公示收费标准与实际收取金额不一致,举报人已附收费单据说明。",
"contact_name": "李强",
"mobile": "13900002002",
"email": "",
"days_ago": 45,
"processed": False,
},
{
"title": "报告署名与现场查勘人不一致",
"subject": "嘉峪关示例估价有限公司",
"body": "报告签字估价师未参与现场查勘。协会已约谈机构并要求补正内部复核记录。",
"contact_name": "张华",
"mobile": "13700003003",
"email": "zhang.hua@example.com",
"days_ago": 20,
"processed": True,
},
]
ARTICLES = [
(
"warning_cases",
"比较案例选取不当的执业警示",
"2025-06-12T09:00:00",
"<p>某会员机构在住宅估价中选用跨板块案例,且未披露修正依据。本会予以通报,要求整改作业指引。</p>",
),
(
"warning_cases",
"现场查勘记录缺失的执业警示",
"2025-03-18T09:00:00",
"<p>报告未附现场查勘照片与记录。本会约谈签字估价师,并要求机构补齐内部复核。</p>",
),
(
"integrity_records",
"2024 年度会员机构诚信档案(摘录)",
"2025-02-20T09:00:00",
"<p>摘录会员机构年度执业情况、继续教育完成情况和受到的行业处理。正式名录由工作人员维护。</p>",
),
(
"integrity_records",
"注册房地产估价师执业记录说明",
"2024-12-06T09:00:00",
"<p>说明诚信档案公开的范围:执业登记、继续教育、行业处理。不公开身份证号和联系电话。</p>",
),
(
"discipline_results",
"关于对示例机构通报批评的处理结果",
"2025-07-08T09:00:00",
"<p>经核查,比较案例选取明显不当。决定对该机构通报批评,并责令一个月内提交整改报告。</p>",
),
(
"discipline_results",
"收费标准执行情况的核查结果",
"2025-04-02T09:00:00",
"<p>核查未发现与公示标准不符的收费。本案办结,不再另行处理。</p>",
),
]
def _seed_notice(db) -> str:
current = admin_notice(db)
if (current.get("phone") or "").strip() or (current.get("scopeHtml") or "").strip():
return "说明已有内容,未覆盖"
save_notice(db, NOTICE)
return "已写入投诉举报说明"
def _seed_complaints(db) -> int:
staff_id = db.scalar(select(AdminUser.id).order_by(AdminUser.id.asc()))
added = 0
for item in COMPLAINTS:
exists = db.scalar(
select(DisciplineComplaint.id).where(DisciplineComplaint.title == item["title"])
)
if exists is not None:
continue
create_complaint(
db,
title=item["title"],
subject=item["subject"],
body=item["body"],
contact_name=item["contact_name"],
mobile=item["mobile"],
email=item["email"],
files=[EVIDENCE],
)
row = db.scalar(
select(DisciplineComplaint).where(DisciplineComplaint.title == item["title"])
)
row.created_at = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(
days=item["days_ago"]
)
db.commit()
if item["processed"]:
mark_processed(db, row.id, staff_id=int(staff_id or 1))
added += 1
return added
def _seed_articles(db) -> int:
added = 0
for category, title, published_at, body in ARTICLES:
exists = db.scalar(
select(HomeArticle.id).where(
HomeArticle.category == category, HomeArticle.title == title
)
)
if exists is not None:
continue
create_article(
db,
{
"category": category,
"title": title,
"publishedAt": published_at,
"published": True,
"bodyHtml": body,
"attachmentFileIds": [],
},
)
added += 1
return added
def seed() -> None:
import app.models.content # noqa: F401
import app.models.discipline # noqa: F401
import app.models.home # noqa: F401
import app.models.rbac # noqa: F401
ensure_buckets()
engine = get_engine()
Base.metadata.create_all(bind=engine)
SessionLocal.configure(bind=engine)
db = SessionLocal()
try:
notice = _seed_notice(db)
complaints = _seed_complaints(db)
articles = _seed_articles(db)
print(f"行业自律演示数据:{notice};新增举报 {complaints} 条;新增文章 {articles} 条。")
finally:
db.close()
if __name__ == "__main__":
try:
seed()
except Exception as exc:
print(str(exc), file=sys.stderr)
raise
@@ -0,0 +1,154 @@
"""写入继续教育「教育公告」演示条目。
同标题已存在则跳过,不覆盖工作人员后来改过的正文。
口令只从环境变量读取。
"""
from __future__ import annotations
from html import escape, unescape
from pathlib import Path
from sqlalchemy import select
from app.db import Base, SessionLocal, get_engine
from app.models.content import AdminFile
from app.models.home import HomeArticle, create_article
from app.services.storage import ensure_buckets, make_object_key, upload_object
ROOT = Path(__file__).resolve().parents[3]
SOURCE = ROOT / "docs" / "参考" / "现站" / "基础数据"
COURSE = SOURCE / "继续教育" / "文章" / "557316" / "content.txt"
CAROUSEL = SOURCE / "首页轮播"
CATEGORY = "edu_notices"
def _paragraphs_from_lines(lines: list[str]) -> str:
return "".join(f"<p>{escape(line)}</p>" for line in lines if line.strip())
def _course_html() -> str:
if not COURSE.is_file():
return _paragraphs_from_lines(["2020 年线上继续教育课程安排整理中。"])
text = unescape(COURSE.read_text(encoding="utf-8"))
lines = [line.strip() for line in text.splitlines() if line.strip()]
body = _paragraphs_from_lines(lines)
body += "<p>整理自现站公开页面:http://www.gsrea.org.cn/newsinfo/557316.html</p>"
return body
def _content_type(path: Path) -> str:
suffix = path.suffix.lower()
if suffix == ".png":
return "image/png"
if suffix == ".webp":
return "image/webp"
if suffix == ".gif":
return "image/gif"
return "image/jpeg"
def _store_public(db, path: Path, filename: str) -> AdminFile | None:
if not path.is_file():
return None
row = db.scalar(
select(AdminFile).where(AdminFile.bucket == "public", AdminFile.filename == filename)
)
if row is not None:
return row
data = path.read_bytes()
key = make_object_key(filename)
upload_object("public", key, data, _content_type(path))
row = AdminFile(
bucket="public",
object_key=key,
filename=filename,
content_type=_content_type(path),
size=len(data),
created_by=None,
)
db.add(row)
db.commit()
db.refresh(row)
return row
def _samples(cover_id: int | None) -> list[dict]:
return [
{
"title": "2026年度房地产估价师继续教育培训安排",
"publishedAt": "2026-03-02T08:00:00",
"imageFileId": cover_id,
"bodyHtml": _paragraphs_from_lines(
[
"本条为演示库样例,正式安排以协会最新通知为准。",
"培训对象:本会注册房地产估价师及从业人员。",
"时间安排:2026年4月至11月,线上课程与兰州集中面授结合。",
"学时要求:完成规定学时并通过学习记录核验后,计入当年度继续教育。",
"报名与缴费仍通过现有甘肃省继续教育系统办理,本站只发布计划与公告。",
]
),
},
{
"title": "关于开展2025年估价师继续教育补学的通知",
"publishedAt": "2025-09-18T08:00:00",
"imageFileId": cover_id,
"bodyHtml": _paragraphs_from_lines(
[
"本条为演示库样例。",
"尚未完成2025年度规定学时的会员,可于10月31日前通过继续教育系统补学。",
"补学课程包括估价报告常见问题、城市更新估价要点与行业诚信要求。",
"咨询电话:0931-8126195。",
]
),
},
{
"title": "2020年豫甘两会线上估价师继续教育课程安排",
"publishedAt": "2020-07-03T08:00:00",
"imageFileId": None,
"bodyHtml": _course_html(),
},
]
def seed() -> None:
import app.models.content # noqa: F401
import app.models.home # noqa: F401
ensure_buckets()
engine = get_engine()
Base.metadata.create_all(bind=engine)
SessionLocal.configure(bind=engine)
db = SessionLocal()
try:
cover = _store_public(db, CAROUSEL / "8488214.jpg", "edu-notice-cover.jpg")
added = 0
for item in _samples(cover.id if cover else None):
exists = db.scalar(
select(HomeArticle.id).where(
HomeArticle.category == CATEGORY,
HomeArticle.title == item["title"],
)
)
if exists is not None:
continue
create_article(
db,
{
"category": CATEGORY,
"title": item["title"],
"publishedAt": item["publishedAt"],
"published": True,
"bodyHtml": item["bodyHtml"],
"imageFileId": item["imageFileId"],
"attachmentFileIds": [],
},
)
added += 1
print(f"教育公告演示数据:新增 {added} 条。")
finally:
db.close()
if __name__ == "__main__":
seed()
@@ -0,0 +1,82 @@
"""写入专项估价指南样例(四类各至少一条)。"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
def main() -> int:
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
from app.core.config import get_settings
from app.db import Base, SessionLocal, get_engine
from app.models.home import create_article
settings = get_settings()
if not settings.database_url.strip():
print("DATABASE_URL 为空", file=sys.stderr)
return 1
import app.models.expert # noqa: F401
import app.models.home # noqa: F401
import app.models.member # noqa: F401
engine = get_engine()
Base.metadata.create_all(bind=engine)
SessionLocal.configure(bind=engine)
db = SessionLocal()
samples = [
("residential", "住宅估价业务指引", "<p>住宅估价受理、查勘、比较法选用与报告出具要点。</p>"),
("commercial", "商业地产估价流程指引", "<p>收益法参数、租约核查与市场调查注意事项。</p>"),
("industrial", "工业房地产估价指引", "<p>工业用途、构筑物与设备附着物边界说明。</p>"),
("specialty", "特色地产(文旅/养老)估价指引", "<p>特色业态可比案例稀缺时的路径与披露要求。</p>"),
]
try:
from sqlalchemy import select
from app.models.home import HomeArticle, HomeArticleKind
existing = {
row.kind
for row in db.scalars(
select(HomeArticleKind).where(
HomeArticleKind.article_id.in_(
select(HomeArticle.id).where(HomeArticle.category == "appraisal_guides")
)
)
).all()
}
created = 0
for kind, title, html in samples:
if kind in existing:
continue
create_article(
db,
{
"category": "appraisal_guides",
"kind": kind,
"title": title,
"publishedAt": "2025-09-01T08:00:00",
"published": True,
"bodyHtml": html,
"attachmentFileIds": [],
},
)
created += 1
print(f"appraisal_guides seeded: +{created}")
return 0
finally:
db.close()
if __name__ == "__main__":
raise SystemExit(main())
+436
View File
@@ -0,0 +1,436 @@
"""把现站公开摘录写入首页各模块,供本地查看。
数据来自仓库 docs/参考/现站/基础数据。重复执行会清掉首页模块后按同一批摘录重写,
不改站点备案号,也不改当前启用的模板。口令只从环境变量读取。
"""
from __future__ import annotations
import json
import tempfile
from html import escape, unescape
from pathlib import Path
from sqlalchemy import delete, select
from app.db import Base, SessionLocal, get_engine
from app.models.content import AdminFile, SiteSetting, ensure_site_defaults, save_settings
from app.models.home import (
BRAND,
TECH,
HomeArticle,
HomeArticleAttachment,
HomeAudienceLink,
HomeComplianceLink,
HomeContact,
HomeHonor,
HomeHotLink,
HomeMarquee,
HomeMember,
HomeMenuItem,
HomeRelatedLink,
HomeSlide,
HomeSlideAttachment,
HomeTemplate,
create_article,
create_slide,
ensure_home_templates,
save_audiences,
save_compliance,
save_contact,
save_honors,
save_hot_links,
save_members,
save_menu,
save_related_links,
set_article_display,
)
from app.services.storage import ensure_buckets, make_object_key, public_object_url, upload_object
ROOT = Path(__file__).resolve().parents[3]
SOURCE = ROOT / "docs" / "参考" / "现站" / "基础数据"
CAROUSEL = SOURCE / "首页轮播"
NEWS = SOURCE / "新闻动态"
NOTICES = SOURCE / "通知公告"
POLICIES = SOURCE / "政策法规"
SLOGAN = "服务政府、服务行业、服务会员"
VALUE = "独立、客观、公正执业"
# 现站轮播图对应的新闻编号,见首页解码 HTML。
SLIDES = [
("58612080.jpg", 8560786),
("52398194.png", 7519867),
("50933127.jpg", 7282421),
("49922210.jpg", 7108127),
("45355362.png", 6272136),
]
# 有正文、且不与前 6 条新闻重复的市场类转载,用作数据看板文章。
DASHBOARD_IDS = (7544540, 7519901, 6888657)
# 张掖路 63 号所在城关区的大致坐标,只用于地图测试。
LATITUDE = 36.0609
LONGITUDE = 103.8234
def _load_index(folder: Path) -> list[dict]:
return json.loads((folder / "index.json").read_text(encoding="utf-8"))
def _article_dir(folder: Path, article_id: int) -> Path:
return folder / "文章" / str(article_id)
def _paragraphs(path: Path) -> str:
text = unescape(path.read_text(encoding="utf-8"))
parts = []
for line in text.splitlines():
line = line.strip()
if not line:
continue
parts.append(f"<p>{escape(line)}</p>")
return "".join(parts)
def _content_type(path: Path) -> str:
suffix = path.suffix.lower()
if suffix == ".png":
return "image/png"
if suffix == ".webp":
return "image/webp"
if suffix == ".gif":
return "image/gif"
return "image/jpeg"
def _store_public(db, path: Path, filename: str | None = None) -> AdminFile:
name = filename or f"home-sample-{path.name}"
row = db.scalar(
select(AdminFile).where(AdminFile.bucket == "public", AdminFile.filename == name)
)
if row is not None:
return row
data = path.read_bytes()
key = make_object_key(name)
upload_object("public", key, data, _content_type(path))
row = AdminFile(
bucket="public",
object_key=key,
filename=name,
content_type=_content_type(path),
size=len(data),
created_by=None,
)
db.add(row)
db.commit()
db.refresh(row)
return row
def _nameplate(name: str, dest: Path) -> None:
from PIL import Image, ImageDraw, ImageFont
image = Image.new("RGB", (360, 120), (15, 76, 129))
draw = ImageDraw.Draw(image)
font_path = "/System/Library/Fonts/Hiragino Sans GB.ttc"
font = ImageFont.truetype(font_path, 22)
# 两行排开,避免会员名称超出标志宽度。
midpoint = max(8, len(name) // 2)
split = name.rfind("有限", 0, midpoint + 6)
if split < 4:
split = midpoint
lines = [name[:split], name[split:]]
draw.multiline_text((18, 28), "\n".join(lines), fill=(255, 255, 255), font=font, spacing=6)
dest.parent.mkdir(parents=True, exist_ok=True)
image.save(dest, "PNG")
def _clear_home(db) -> None:
for model in (
HomeSlideAttachment,
HomeSlide,
HomeArticleAttachment,
HomeArticle,
HomeAudienceLink,
HomeHotLink,
HomeHonor,
HomeMember,
HomeRelatedLink,
HomeComplianceLink,
HomeContact,
HomeMarquee,
):
db.execute(delete(model))
db.execute(delete(HomeMenuItem))
db.commit()
def _import_articles(
db, folder: Path, category: str, limit: int, skip: set[int], only: set[int] | None = None
) -> dict[int, int]:
created: dict[int, int] = {}
count = 0
for item in _load_index(folder):
article_id = int(item["id"])
if only is not None and article_id not in only:
continue
if article_id in skip or not item.get("bodySaved"):
continue
body_path = _article_dir(folder, article_id) / "content.txt"
if not body_path.is_file():
continue
image_id = None
meta_path = _article_dir(folder, article_id) / "meta.json"
if meta_path.is_file():
meta = json.loads(meta_path.read_text(encoding="utf-8"))
images = meta.get("images") or []
if images:
picture = _article_dir(folder, article_id) / images[0]["file"]
if picture.is_file():
image_id = _store_public(db, picture).id
html = _paragraphs(body_path)
html += f"<p>整理自现站公开页面:{escape(item['url'])}</p>"
created[article_id] = create_article(
db,
{
"category": category,
"title": item["title"][:200],
"bodyHtml": html,
"imageFileId": image_id,
"published": True,
"publishedAt": f"{item['date']}T08:00:00",
"attachmentFileIds": [],
},
)
count += 1
if count >= limit:
break
return created
def _related(name: str) -> list[dict]:
groups = {
"主管部门": [
("甘肃省住房和城乡建设厅", "http://www.gsjs.gansu.gov.cn/?tabid=1"),
("中华人民共和国住房和城乡建设部", "https://www.mohurd.gov.cn/"),
],
"相关部门": [
("甘肃省人力资源和社会保障厅", "http://www.rst.gansu.gov.cn/"),
("国家税务总局甘肃省税务局", "http://www.gstax.gov.cn/"),
],
"合作协会": [
("中国房地产估价师与房地产经纪人学会", "http://www.cirea.org.cn/"),
("英国皇家特许测量师学会(RICS)", "https://www.rics.org/cn/"),
("香港测量师学会(HKIS)", "https://www.hkis.org.hk/en/index.html"),
],
}
return [
{"label": label, "url": url, "visible": True, "sortOrder": index}
for index, (label, url) in enumerate(groups[name])
]
def seed() -> None:
if not SOURCE.is_dir():
raise SystemExit(f"找不到现站摘录:{SOURCE}")
engine = get_engine()
Base.metadata.create_all(bind=engine)
SessionLocal.configure(bind=engine)
db = SessionLocal()
try:
ensure_buckets()
ensure_site_defaults(db)
ensure_home_templates(db)
news_index = {int(item["id"]): item for item in _load_index(NEWS)}
logo = SOURCE / "logo" / "logo.jpg"
if logo.is_file():
logo_row = _store_public(db, logo, "home-sample-logo.jpg")
current = db.scalar(select(SiteSetting).where(SiteSetting.key == "logo_file_id"))
if current is None or not str(current.value).strip():
save_settings(db, {"logo_file_id": str(logo_row.id)})
_clear_home(db)
active = db.scalar(select(HomeTemplate.name).where(HomeTemplate.is_active.is_(True))) or TECH
for row in db.scalars(select(HomeTemplate)).all():
row.slogan = SLOGAN
row.value_proposition = VALUE
row.is_active = row.name == active
db.commit()
for index, (filename, source_id) in enumerate(SLIDES):
picture = CAROUSEL / filename
meta = news_index.get(source_id, {})
title = meta.get("title") or "协会活动"
body_path = _article_dir(NEWS, source_id) / "content.txt"
html = _paragraphs(body_path) if body_path.is_file() else f"<p>{escape(title)}</p>"
if meta.get("url"):
html += f"<p>整理自现站公开页面:{escape(meta['url'])}</p>"
image = _store_public(db, picture)
create_slide(
db,
{
"title": title[:200],
"imageFileId": image.id,
"sortOrder": index,
"enabled": True,
"intervalSeconds": 6,
"published": True,
"bodyHtml": html,
"attachmentFileIds": [],
},
)
set_article_display(db, {"news": 6, "notices": 6, "policies": 6, "dashboard": 6})
_import_articles(db, NEWS, "news", 6, set(DASHBOARD_IDS))
_import_articles(db, NOTICES, "notices", 6, set())
policy_ids = _import_articles(db, POLICIES, "policies", 6, set())
policy_ids.update(_import_articles(db, POLICIES, "policies", 1, set(), only={1209303}))
dashboard_ids = _import_articles(db, NEWS, "dashboard", 3, set(), only=set(DASHBOARD_IDS))
privacy_id = create_article(
db,
{
"category": "policies",
"title": "隐私政策(测试占位)",
"bodyHtml": (
"<p>现站没有单独发布隐私政策。本条只用于首页合规链接测试,正式文本以协会后续发布为准。</p>"
"<p>协会公开介绍写明,协会遵守法律、法规和国家政策。</p>"
),
"published": True,
"publishedAt": "2019-01-01T08:00:00",
"attachmentFileIds": [],
},
)
charter = db.scalar(select(HomeArticle).where(HomeArticle.title.contains("章程")))
covenant = db.scalar(select(HomeArticle).where(HomeArticle.title.contains("自律公约")))
compliance = [
{"label": "隐私政策", "url": f"/articles/{privacy_id}", "visible": True, "sortOrder": 0},
{
"label": "使用条款",
"url": f"/articles/{covenant.id}" if covenant else f"/articles/{privacy_id}",
"visible": True,
"sortOrder": 1,
},
{
"label": "网站声明",
"url": f"/articles/{charter.id}" if charter else f"/articles/{privacy_id}",
"visible": True,
"sortOrder": 2,
},
]
save_audiences(
db,
[
{
"name": "估价师",
"links": [
{"label": "估价师查询", "url": "http://xhzhglxt.cirea.org.cn/website/gjs_Iframe.asp", "visible": True, "sortOrder": 0},
{"label": "注册系统", "url": "http://gjszcxt.cirea.org.cn/", "visible": True, "sortOrder": 1},
{"label": "信用档案", "url": "http://gjxydaxt.cirea.org.cn/", "visible": True, "sortOrder": 2},
],
},
{
"name": "估价机构",
"links": [
{"label": "估价机构查询", "url": "http://xhzhglxt.cirea.org.cn/website/gjjg_iframe.asp", "visible": True, "sortOrder": 0},
{"label": "备案系统", "url": "http://gjjgzzxt.cirea.org.cn/", "visible": True, "sortOrder": 1},
],
},
{
"name": "公众",
"links": [
{"label": "联系我们", "url": "/contact", "visible": True, "sortOrder": 0},
{"label": "机构名录", "url": "/institutions", "visible": True, "sortOrder": 1},
{"label": "投诉举报", "url": "/discipline", "visible": True, "sortOrder": 2},
],
},
],
)
save_hot_links(
db,
[
{"key": "reportQuery", "label": "报告查询", "url": "/reports/query", "visible": True, "sortOrder": 0},
{"key": "reportReview", "label": "报告审核", "url": "/reports/review", "visible": True, "sortOrder": 1},
{"key": "complaint", "label": "投诉举报", "url": "/discipline", "visible": True, "sortOrder": 2},
],
)
save_menu(
db,
[
{"key": "member", "label": "会员服务", "url": "http://www.gsrea.org.cn/hyfw", "visible": True, "sortOrder": 1},
],
)
honor_dir = _article_dir(NEWS, 7911765)
honor_meta = json.loads((honor_dir / "meta.json").read_text(encoding="utf-8"))
honor_items = []
for index, image in enumerate(honor_meta.get("images") or []):
picture = honor_dir / image["file"]
if not picture.is_file():
continue
honor_items.append({"imageFileId": _store_public(db, picture).id, "sortOrder": index})
if len(honor_items) >= 4:
break
save_honors(db, 8, honor_items)
# 现站首页滚动的单位,网址来自首页外链;没有网址的保持空链接。
members = [
("甘肃中瑞房地产资产评估有限公司", "http://www.lzzr.org.cn"),
("甘肃信诺房地产土地资产评估有限公司", ""),
("兰州三信房地产评估有限公司", ""),
("甘肃华澳房地产估价有限公司", ""),
("甘肃宏信房地资产评估有限公司", ""),
("天水中恒房地产土地资产评估咨询有限公司", ""),
("兰州中信房地产土地评估事务有限公司", "http://www.8479514.com"),
("甘肃方家房地产评估有限公司", "http://www.gstdpg.com"),
("甘肃智信房地产咨询评估有限公司", "http://www.gansuzhixin.com"),
]
member_items = []
plate_dir = Path(tempfile.gettempdir()) / "gsrea-member-plates"
for index, (name, url) in enumerate(members):
plate = plate_dir / f"{index}.png"
_nameplate(name, plate)
member_items.append(
{
"name": name,
"url": url,
"imageFileId": _store_public(db, plate, f"home-sample-member-{index}.png").id,
"sortOrder": index,
}
)
save_members(db, 8, member_items)
contact = {
"address": "甘肃省兰州市城关区张掖路63号",
"phone": "0931-8126195",
"email": "gsrea2018@163.com",
"latitude": LATITUDE,
"longitude": LONGITUDE,
}
save_contact(db, [{"name": TECH, **contact}, {"name": BRAND, **contact}])
for template in (TECH, BRAND):
save_related_links(
db,
template,
[
{"name": "主管部门", "links": _related("主管部门")},
{"name": "相关部门", "links": _related("相关部门")},
{"name": "合作协会", "links": _related("合作协会")},
],
)
save_compliance(db, template, compliance)
print(
"首页测试数据已写入:"
f"轮播 {len(SLIDES)},新闻 6,通知 6,政策 {len(policy_ids)},"
f"数据看板 {len(dashboard_ids)},荣誉 {len(honor_items)},会员 {len(member_items)}"
)
finally:
db.close()
if __name__ == "__main__":
seed()
@@ -0,0 +1,182 @@
"""写入行业党建演示数据:支部介绍单篇 + 党建活动列表。
重复执行会清掉 party_activities 并重写 party_branch。口令只从环境变量读取。
"""
from __future__ import annotations
from html import escape, unescape
from pathlib import Path
from sqlalchemy import delete, select
from app.db import Base, SessionLocal, get_engine
from app.models.about import save_about_page
from app.models.content import AdminFile
from app.models.home import HomeArticle, HomeArticleAttachment, create_article
from app.services.storage import ensure_buckets, make_object_key, upload_object
ROOT = Path(__file__).resolve().parents[3]
SOURCE = ROOT / "docs" / "参考" / "现站" / "基础数据"
NEWS = SOURCE / "新闻动态"
CAROUSEL = SOURCE / "首页轮播"
PARTY_CATEGORY = "party_activities"
def _paragraphs(path: Path) -> str:
text = unescape(path.read_text(encoding="utf-8"))
parts = []
for line in text.splitlines():
line = line.strip()
if not line:
continue
parts.append(f"<p>{escape(line)}</p>")
return "".join(parts)
def _paragraphs_from_lines(lines: list[str]) -> str:
return "".join(f"<p>{escape(line)}</p>" for line in lines if line.strip())
def _content_type(path: Path) -> str:
suffix = path.suffix.lower()
if suffix == ".png":
return "image/png"
if suffix == ".webp":
return "image/webp"
if suffix == ".gif":
return "image/gif"
return "image/jpeg"
def _store_public(db, path: Path, filename: str | None = None) -> AdminFile | None:
if not path.is_file():
return None
name = filename or f"party-sample-{path.name}"
row = db.scalar(
select(AdminFile).where(AdminFile.bucket == "public", AdminFile.filename == name)
)
if row is not None:
return row
data = path.read_bytes()
key = make_object_key(name)
upload_object("public", key, data, _content_type(path))
row = AdminFile(
bucket="public",
object_key=key,
filename=name,
content_type=_content_type(path),
size=len(data),
created_by=None,
)
db.add(row)
db.commit()
db.refresh(row)
return row
def _clear_party(db) -> None:
article_ids = list(
db.scalars(select(HomeArticle.id).where(HomeArticle.category == PARTY_CATEGORY)).all()
)
if article_ids:
db.execute(
delete(HomeArticleAttachment).where(HomeArticleAttachment.article_id.in_(article_ids))
)
db.execute(delete(HomeArticle).where(HomeArticle.id.in_(article_ids)))
db.commit()
def seed() -> None:
import app.models.about # noqa: F401
import app.models.content # noqa: F401
import app.models.home # noqa: F401
ensure_buckets()
engine = get_engine()
Base.metadata.create_all(bind=engine)
SessionLocal.configure(bind=engine)
db = SessionLocal()
try:
_clear_party(db)
save_about_page(
db,
"party_branch",
{
"published": True,
"bodyHtml": _paragraphs_from_lines(
[
"甘肃省房地产价格评估行业协会党支部坚持以党建引领行业发展,团结引导广大会员机构与估价师坚定理想信念、依法依规执业。",
"职能定位:宣传贯彻党的路线方针政策,落实上级党组织部署;加强支部自身建设与党员教育管理;推动党建与估价行业自律、继续教育、技术交流等工作同向发力。",
"组织生活:定期开展主题党日、集中学习与谈心谈话;组织党员参加志愿服务、公益估价与行业文化建设;指导、展示会员机构党建活动成果。",
"正式章程、成员名单与近期活动由工作人员在管理端维护。本条为演示库样例。",
]
),
"attachmentFileIds": [],
},
)
cover_a = _store_public(db, CAROUSEL / "58612080.jpg", "party-cover-a.jpg")
cover_b = _store_public(db, CAROUSEL / "50933127.jpg", "party-cover-b.jpg")
council = NEWS / "文章" / "8560786"
award = NEWS / "文章" / "7911765"
create_article(
db,
{
"category": PARTY_CATEGORY,
"title": "主题党日:学习估价行业诚信自律要求(兰州中信估价党支部)",
"publishedAt": "2025-10-12T08:00:00",
"published": True,
"bodyHtml": (
_paragraphs(council / "content.txt")
if (council / "content.txt").is_file()
else "<p>围绕行业诚信与执业风险提示开展主题党日学习。</p>"
)
+ "<p>整理自现站公开报道,属会员机构党建活动公示示意。</p>",
"imageFileId": cover_a.id if cover_a else None,
"attachmentFileIds": [],
},
)
create_article(
db,
{
"category": PARTY_CATEGORY,
"title": "走访慰问与公益估价服务日(兰州中瑞估价党支部)",
"publishedAt": "2025-07-01T08:00:00",
"published": True,
"bodyHtml": (
_paragraphs(award / "content.txt")
if (award / "content.txt").is_file()
else "<p>结合纪念日开展走访慰问与公益估价咨询。</p>"
)
+ "<p>示意会员机构党建与业务融合活动。</p>",
"imageFileId": cover_b.id if cover_b else None,
"attachmentFileIds": [],
},
)
create_article(
db,
{
"category": PARTY_CATEGORY,
"title": "支部联建:估价报告质量交叉评阅(示意,无封面)",
"publishedAt": "2025-05-18T08:00:00",
"published": True,
"bodyHtml": "<p>本条无封面,示意无配图时列表仅显示标题。联建双方交叉评阅典型报告。</p>",
"imageFileId": None,
"attachmentFileIds": [],
},
)
print(
"行业党建测试数据已写入:支部介绍 1 篇,党建活动 3 条。"
" 执行:python -m app.commands.seed_party_building_sample"
)
finally:
db.close()
if __name__ == "__main__":
seed()
@@ -0,0 +1,203 @@
"""把现站相关公开摘录写入技术研讨 / 技术交流(模块),供演示库非空。
数据来自 docs/参考/现站。重复执行会清掉 tech_seminars / tech_exchange 后重写。
口令只从环境变量读取。
"""
from __future__ import annotations
from html import escape, unescape
from pathlib import Path
from sqlalchemy import delete, select
from app.db import Base, SessionLocal, get_engine
from app.models.content import AdminFile
from app.models.home import HomeArticle, HomeArticleAttachment, create_article
from app.services.storage import ensure_buckets, make_object_key, upload_object
ROOT = Path(__file__).resolve().parents[3]
SOURCE = ROOT / "docs" / "参考" / "现站" / "基础数据"
ABOUT = SOURCE / "协会介绍"
NEWS = SOURCE / "新闻动态"
CAROUSEL = SOURCE / "首页轮播"
TECH_CATEGORIES = ("tech_seminars", "tech_exchange")
def _paragraphs(path: Path) -> str:
text = unescape(path.read_text(encoding="utf-8"))
parts = []
for line in text.splitlines():
line = line.strip()
if not line:
continue
parts.append(f"<p>{escape(line)}</p>")
return "".join(parts)
def _content_type(path: Path) -> str:
suffix = path.suffix.lower()
if suffix == ".png":
return "image/png"
if suffix == ".webp":
return "image/webp"
if suffix == ".gif":
return "image/gif"
return "image/jpeg"
def _store_public(db, path: Path, filename: str | None = None) -> AdminFile | None:
if not path.is_file():
return None
name = filename or f"tech-sample-{path.name}"
row = db.scalar(
select(AdminFile).where(AdminFile.bucket == "public", AdminFile.filename == name)
)
if row is not None:
return row
data = path.read_bytes()
key = make_object_key(name)
upload_object("public", key, data, _content_type(path))
row = AdminFile(
bucket="public",
object_key=key,
filename=name,
content_type=_content_type(path),
size=len(data),
created_by=None,
)
db.add(row)
db.commit()
db.refresh(row)
return row
def _clear_tech(db) -> None:
article_ids = list(
db.scalars(select(HomeArticle.id).where(HomeArticle.category.in_(TECH_CATEGORIES))).all()
)
if article_ids:
db.execute(
delete(HomeArticleAttachment).where(HomeArticleAttachment.article_id.in_(article_ids))
)
db.execute(delete(HomeArticle).where(HomeArticle.id.in_(article_ids)))
db.commit()
def seed() -> None:
ensure_buckets()
engine = get_engine()
Base.metadata.create_all(bind=engine)
SessionLocal.configure(bind=engine)
db = SessionLocal()
try:
_clear_tech(db)
cover_a = _store_public(db, CAROUSEL / "58612080.jpg", "tech-cover-seminar.jpg")
cover_b = _store_public(db, CAROUSEL / "50933127.jpg", "tech-cover-report.jpg")
cover_c = _store_public(db, CAROUSEL / "49922210.jpg", "tech-cover-award.jpg")
urban = NEWS / "文章" / "11341437"
training = NEWS / "文章" / "10837751"
award = ABOUT / "文章" / "1209332"
create_article(
db,
{
"category": "tech_seminars",
"title": "城市更新中的房地产估价服务专题研讨",
"publishedAt": "2025-11-08T08:00:00",
"published": True,
"bodyHtml": (
_paragraphs(urban / "content.txt")
if (urban / "content.txt").is_file()
else "<p>城市更新估价服务专题研讨(现站摘录)。</p>"
)
+ "<p>整理自现站新闻动态公开报道,属技术研讨活动公示示意。</p>",
"imageFileId": cover_a.id if cover_a else None,
"attachmentFileIds": [],
},
)
create_article(
db,
{
"category": "tech_seminars",
"title": "涉房财报及企业价值评估专题研讨摘录",
"publishedAt": "2025-03-23T08:00:00",
"published": True,
"bodyHtml": (
_paragraphs(training / "content.txt")
if (training / "content.txt").is_file()
else "<p>继续教育与专题研讨公开摘录。</p>"
)
+ "<p>整理自现站培训报道,示意专项研讨发布形态。</p>",
"imageFileId": cover_b.id if cover_b else None,
"attachmentFileIds": [],
},
)
create_article(
db,
{
"category": "tech_seminars",
"title": "绿色建筑估价实践交流会报名通知(示意)",
"publishedAt": "2025-06-02T08:00:00",
"published": True,
"bodyHtml": "<p>本条无封面,示意无配图时列表仅显示标题。活动报名与附件由工作人员后续维护。</p>",
"imageFileId": None,
"attachmentFileIds": [],
},
)
create_article(
db,
{
"category": "tech_exchange",
"title": "2018年度优秀报告评选表彰与实践分享(公示)",
"publishedAt": "2019-04-26T08:00:00",
"published": True,
"bodyHtml": (
_paragraphs(award / "content.txt")
if (award / "content.txt").is_file()
else "<p>优秀报告评选表彰会议公开报道。</p>"
)
+ "<p>整理自现站协会介绍,属优秀报告评选公示示意;届次写在标题中。</p>",
"imageFileId": cover_c.id if cover_c else None,
"attachmentFileIds": [],
},
)
create_article(
db,
{
"category": "tech_exchange",
"title": "专家委员撰稿:涉房财报及企业价值评估专题摘录",
"publishedAt": "2025-03-24T08:00:00",
"published": True,
"bodyHtml": "<p>示意专家撰稿 / 期刊转载形态。正式正文由工作人员在管理端维护,可挂讲义附件。</p>",
"imageFileId": cover_b.id if cover_b else None,
"attachmentFileIds": [],
},
)
create_article(
db,
{
"category": "tech_exchange",
"title": "会员投稿:估价机构内部治理经验交流(代发)",
"publishedAt": "2025-01-10T08:00:00",
"published": True,
"bodyHtml": "<p>本期仅工作人员代发公示,无会员自助投稿入口。本条无封面。</p>",
"imageFileId": None,
"attachmentFileIds": [],
},
)
print(
"技术交流测试数据已写入:技术研讨 3 条,技术交流(模块)3 条。"
" 执行:python -m app.commands.seed_tech_exchange_sample"
)
finally:
db.close()
if __name__ == "__main__":
seed()
View File
Whitespace-only changes.
+56
View File
@@ -0,0 +1,56 @@
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
app_name: str = "甘肃省房地产价格评估行业协会"
cors_origins: str = (
"http://127.0.0.1:13000,http://localhost:13000,"
"http://127.0.0.1:13006,http://localhost:13006"
)
jwt_secret: str = ""
jwt_expire_minutes: int = 120
# 门户会员令牌(专家答疑等),默认 7 天;工作人员仍用 jwt_expire_minutes。
jwt_member_expire_minutes: int = 10080
api_payload_encrypt: bool = False
api_payload_aes_key: str = ""
api_ip_blacklist: str = ""
database_url: str = ""
redis_host: str = "127.0.0.1"
redis_port: int = 6379
redis_db: int = 0
redis_password: str = ""
redis_timeout_sec: int = 30
redis_ssl_enabled: bool = False
minio_endpoint: str = ""
minio_access_key: str = ""
minio_secret_key: str = ""
minio_bucket_public: str = "gsfdc-public"
minio_bucket_private: str = "gsfdc-private"
minio_secure: bool = False
minio_base_url: str = ""
field_aes_key: str = ""
gaode_key: str = ""
gaode_security_js_code: str = ""
smtp_host: str = ""
smtp_port: int = 465
smtp_user: str = ""
smtp_password: str = ""
smtp_sender: str = ""
smtp_use_ssl: bool = True
@property
def cors_origin_list(self) -> list[str]:
return [item.strip() for item in self.cors_origins.split(",") if item.strip()]
@property
def blocked_ips(self) -> set[str]:
return {item.strip() for item in self.api_ip_blacklist.split(",") if item.strip()}
@lru_cache
def get_settings() -> Settings:
return Settings()
+43
View File
@@ -0,0 +1,43 @@
import base64
import json
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from fastapi import HTTPException, status
from app.core.config import get_settings
def _key() -> bytes:
settings = get_settings()
raw = settings.api_payload_aes_key.strip()
if not raw:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="接口加密未配置")
try:
key = base64.b64decode(raw)
except Exception:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="接口加密未配置")
if len(key) not in {16, 24, 32}:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="接口加密未配置")
return key
def encrypt_json(payload: dict | list) -> dict:
nonce = os.urandom(12)
plain = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
ciphertext = AESGCM(_key()).encrypt(nonce, plain, None)
return {"data": base64.b64encode(nonce + ciphertext).decode()}
def decrypt_json(envelope: dict) -> dict | list:
token = envelope.get("data")
if not isinstance(token, str):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="加密报文格式不正确")
try:
raw = base64.b64decode(token)
plain = AESGCM(_key()).decrypt(raw[:12], raw[12:], None)
return json.loads(plain)
except HTTPException:
raise
except Exception:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="加密报文无法解密")
+26
View File
@@ -0,0 +1,26 @@
from fastapi import Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from app.core.security import decode_access_token
bearer = HTTPBearer(auto_error=False)
async def require_staff(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
) -> dict:
if credentials is None:
from fastapi import HTTPException, status
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="请先登录")
return decode_access_token(credentials.credentials, "staff")
async def require_member(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
) -> dict:
if credentials is None:
from fastapi import HTTPException, status
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="请先登录")
return decode_access_token(credentials.credentials, "member")
+50
View File
@@ -0,0 +1,50 @@
# 数据库字段加密(AES-256-GCM)。与 app.core.crypto 的接口报文加密相互独立。
import base64
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from fastapi import HTTPException, status
from app.core.config import get_settings
_DETAIL = "字段加密未配置"
def _fail() -> None:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=_DETAIL)
def _key() -> bytes:
raw = "".join(get_settings().field_aes_key.split())
if not raw:
_fail()
try:
key = base64.b64decode(raw, validate=True)
except Exception:
_fail()
if len(key) != 32:
_fail()
return key
def encrypt_text(plain: str) -> str:
if plain == "":
return ""
nonce = os.urandom(12)
ciphertext = AESGCM(_key()).encrypt(nonce, plain.encode("utf-8"), None)
return base64.b64encode(nonce + ciphertext).decode("ascii")
def decrypt_text(token: str) -> str:
if token == "":
return ""
try:
raw = base64.b64decode(token, validate=True)
if len(raw) < 13:
raise ValueError("short")
plain = AESGCM(_key()).decrypt(raw[:12], raw[12:], None)
return plain.decode("utf-8")
except HTTPException:
raise
except Exception:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="字段密文无法解密") from None
+23
View File
@@ -0,0 +1,23 @@
def mask_mobile(value: str | None) -> str:
if not value:
return ""
if len(value) < 7:
return "***"
return f"{value[:3]}****{value[-4:]}"
def mask_email(value: str | None) -> str:
if not value or "@" not in value:
return ""
name, _, domain = value.partition("@")
if not name or not domain:
return ""
return f"{name[:1]}***@{domain}"
def mask_id_card(value: str | None) -> str:
if not value:
return ""
if len(value) < 8:
return "***"
return f"{value[:4]}**********{value[-4:]}"
+108
View File
@@ -0,0 +1,108 @@
import json
import logging
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, Response
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.cors import CORSMiddleware
from app.core.config import get_settings
from app.core.crypto import decrypt_json, encrypt_json
logger = logging.getLogger("gsfdc.access")
_SKIP_ENCRYPT_PREFIXES = ("/docs", "/redoc", "/openapi.json")
def _skip_encrypt(path: str, content_type: str) -> bool:
if path.startswith(_SKIP_ENCRYPT_PREFIXES):
return True
if "multipart/form-data" in content_type:
return True
return False
class AccessGuardMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
client = request.client.host if request.client else ""
if _ip_blocked(client):
return JSONResponse(status_code=403, content={"detail": "访问被拒绝"})
if get_settings().api_payload_encrypt and not _skip_encrypt(
request.url.path, request.headers.get("content-type", "")
):
request = await _decrypt_request(request)
response = await call_next(request)
logger.info("%s %s %s", request.method, request.url.path, response.status_code)
_record_admin_call(request, response.status_code)
if get_settings().api_payload_encrypt and not _skip_encrypt(
request.url.path, response.headers.get("content-type", "")
):
return await _encrypt_response(response)
return response
async def _decrypt_request(request: Request) -> Request:
body = await request.body()
raw = body
if body:
try:
envelope = json.loads(body)
except json.JSONDecodeError:
envelope = None
if isinstance(envelope, dict) and "data" in envelope:
plain = decrypt_json(envelope)
raw = json.dumps(plain, ensure_ascii=False).encode()
async def receive():
return {"type": "http.request", "body": raw, "more_body": False}
return Request(request.scope, receive)
async def _encrypt_response(response: Response) -> Response:
body = b""
async for chunk in response.body_iterator:
body += chunk
if not body:
return response
try:
payload = json.loads(body)
except json.JSONDecodeError:
return Response(content=body, status_code=response.status_code, headers=dict(response.headers))
encrypted = encrypt_json(payload if isinstance(payload, (dict, list)) else {"data": payload})
return JSONResponse(status_code=response.status_code, content=encrypted)
def _ip_blocked(ip: str) -> bool:
if not ip:
return False
try:
from app.services.ip_guard import is_ip_blocked
return is_ip_blocked(ip)
except Exception:
return ip in get_settings().blocked_ips
def _record_admin_call(request: Request, status_code: int) -> None:
try:
from app.services.audit import record_admin_call
record_admin_call(request, status_code)
except Exception:
logger.warning("admin audit hook failed")
def install_middleware(app: FastAPI) -> None:
settings = get_settings()
app.add_middleware(AccessGuardMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origin_list,
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
+42
View File
@@ -0,0 +1,42 @@
from datetime import datetime, timedelta, timezone
from typing import Literal
import jwt
from fastapi import HTTPException, status
from app.core.config import get_settings
TokenType = Literal["staff", "member"]
def create_access_token(subject: str, token_type: TokenType) -> str:
settings = get_settings()
if len(settings.jwt_secret) < 32:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="鉴权未配置",
)
minutes = (
settings.jwt_member_expire_minutes
if token_type == "member"
else settings.jwt_expire_minutes
)
expire = datetime.now(timezone.utc) + timedelta(minutes=minutes)
payload = {"sub": subject, "typ": token_type, "exp": expire}
return jwt.encode(payload, settings.jwt_secret, algorithm="HS256")
def decode_access_token(token: str, expected_type: TokenType) -> dict:
settings = get_settings()
if len(settings.jwt_secret) < 32:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="鉴权未配置",
)
try:
payload = jwt.decode(token, settings.jwt_secret, algorithms=["HS256"])
except jwt.PyJWTError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效")
if payload.get("typ") != expected_type or not payload.get("sub"):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="无权访问该接口")
return payload
+1
View File
@@ -0,0 +1 @@
[{"name":"北京","sub":[{"name":"北京市","sub":[{"name":"东城区"},{"name":"西城区"},{"name":"朝阳区"},{"name":"丰台区"},{"name":"石景山区"},{"name":"海淀区"},{"name":"门头沟区"},{"name":"房山区"},{"name":"通州区"},{"name":"顺义区"},{"name":"昌平区"},{"name":"大兴区"},{"name":"怀柔区"},{"name":"平谷区"},{"name":"密云区"},{"name":"延庆区"},{"name":"其它区"}],"type":0}],"type":0},{"name":"天津","sub":[{"name":"天津市","sub":[{"name":"和平区"},{"name":"河东区"},{"name":"河西区"},{"name":"南开区"},{"name":"河北区"},{"name":"红桥区"},{"name":"东丽区"},{"name":"西青区"},{"name":"津南区"},{"name":"北辰区"},{"name":"武清区"},{"name":"宝坻区"},{"name":"滨海新区"},{"name":"宁河区"},{"name":"静海区"},{"name":"蓟州区"},{"name":"其它区"}],"type":0}],"type":0},{"name":"河北省","sub":[{"name":"石家庄市","sub":[{"name":"长安区"},{"name":"桥西区"},{"name":"新华区"},{"name":"井陉矿区"},{"name":"裕华区"},{"name":"井陉县"},{"name":"正定县"},{"name":"栾城区"},{"name":"行唐县"},{"name":"灵寿县"},{"name":"高邑县"},{"name":"深泽县"},{"name":"赞皇县"},{"name":"无极县"},{"name":"平山县"},{"name":"元氏县"},{"name":"赵县"},{"name":"辛集市"},{"name":"藁城区"},{"name":"晋州市"},{"name":"新乐市"},{"name":"鹿泉区"},{"name":"其它区"}],"type":0},{"name":"唐山市","sub":[{"name":"路南区"},{"name":"路北区"},{"name":"古冶区"},{"name":"开平区"},{"name":"丰南区"},{"name":"丰润区"},{"name":"滦县"},{"name":"滦南县"},{"name":"乐亭县"},{"name":"迁西县"},{"name":"玉田县"},{"name":"曹妃甸区"},{"name":"遵化市"},{"name":"迁安市"},{"name":"其它区"}],"type":0},{"name":"秦皇岛市","sub":[{"name":"海港区"},{"name":"山海关区"},{"name":"北戴河区"},{"name":"青龙满族自治县"},{"name":"昌黎县"},{"name":"抚宁区"},{"name":"卢龙县"},{"name":"其它区"}],"type":0},{"name":"邯郸市","sub":[{"name":"邯山区"},{"name":"丛台区"},{"name":"复兴区"},{"name":"峰峰矿区"},{"name":"临漳县"},{"name":"成安县"},{"name":"大名县"},{"name":"涉县"},{"name":"磁县"},{"name":"肥乡区"},{"name":"永年区"},{"name":"邱县"},{"name":"鸡泽县"},{"name":"广平县"},{"name":"馆陶县"},{"name":"魏县"},{"name":"曲周县"},{"name":"武安市"},{"name":"其它区"}],"type":0},{"name":"邢台市","sub":[{"name":"桥东区"},{"name":"桥西区"},{"name":"邢台县"},{"name":"临城县"},{"name":"内丘县"},{"name":"柏乡县"},{"name":"隆尧县"},{"name":"任县"},{"name":"南和县"},{"name":"宁晋县"},{"name":"巨鹿县"},{"name":"新河县"},{"name":"广宗县"},{"name":"平乡县"},{"name":"威县"},{"name":"清河县"},{"name":"临西县"},{"name":"南宫市"},{"name":"沙河市"},{"name":"其它区"}],"type":0},{"name":"保定市","sub":[{"name":"竞秀区"},{"name":"莲池区"},{"name":"满城区"},{"name":"清苑区"},{"name":"涞水县"},{"name":"阜平县"},{"name":"徐水区"},{"name":"定兴县"},{"name":"唐县"},{"name":"高阳县"},{"name":"容城县"},{"name":"涞源县"},{"name":"望都县"},{"name":"安新县"},{"name":"易县"},{"name":"曲阳县"},{"name":"蠡县"},{"name":"顺平县"},{"name":"博野县"},{"name":"雄县"},{"name":"涿州市"},{"name":"定州市"},{"name":"安国市"},{"name":"高碑店市"},{"name":"其它区"}],"type":0},{"name":"张家口市","sub":[{"name":"桥东区"},{"name":"桥西区"},{"name":"宣化区"},{"name":"下花园区"},{"name":"张北县"},{"name":"康保县"},{"name":"沽源县"},{"name":"尚义县"},{"name":"蔚县"},{"name":"阳原县"},{"name":"怀安县"},{"name":"万全区"},{"name":"怀来县"},{"name":"涿鹿县"},{"name":"赤城县"},{"name":"崇礼区"},{"name":"其它区"}],"type":0},{"name":"承德市","sub":[{"name":"双桥区"},{"name":"双滦区"},{"name":"鹰手营子矿区"},{"name":"承德县"},{"name":"兴隆县"},{"name":"平泉市"},{"name":"滦平县"},{"name":"隆化县"},{"name":"丰宁满族自治县"},{"name":"宽城满族自治县"},{"name":"围场满族蒙古族自治县"},{"name":"其它区"}],"type":0},{"name":"沧州市","sub":[{"name":"新华区"},{"name":"运河区"},{"name":"沧县"},{"name":"青县"},{"name":"东光县"},{"name":"海兴县"},{"name":"盐山县"},{"name":"肃宁县"},{"name":"南皮县"},{"name":"吴桥县"},{"name":"献县"},{"name":"孟村回族自治县"},{"name":"泊头市"},{"name":"任丘市"},{"name":"黄骅市"},{"name":"河间市"},{"name":"其它区"}],"type":0},{"name":"廊坊市","sub":[{"name":"安次区"},{"name":"广阳区"},{"name":"固安县"},{"name":"永清县"},{"name":"香河县"},{"name":"大城县"},{"name":"文安县"},{"name":"大厂回族自治县"},{"name":"霸州市"},{"name":"三河市"},{"name":"其它区"}],"type":0},{"name":"衡水市","sub":[{"name":"桃城区"},{"name":"枣强县"},{"name":"武邑县"},{"name":"武强县"},{"name":"饶阳县"},{"name":"Line truncated
+37
View File
@@ -0,0 +1,37 @@
from collections.abc import Generator
from sqlalchemy import create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
from app.core.config import get_settings
class Base(DeclarativeBase):
pass
_engine: Engine | None = None
def get_engine() -> Engine:
global _engine
url = get_settings().database_url.strip()
if not url:
raise RuntimeError("数据库连接未配置")
if _engine is None:
_engine = create_engine(url, pool_pre_ping=True)
SessionLocal.configure(bind=_engine)
return _engine
SessionLocal = sessionmaker(autocommit=False, autoflush=False, expire_on_commit=False)
def get_db() -> Generator[Session, None, None]:
SessionLocal.configure(bind=get_engine())
db = SessionLocal()
try:
yield db
finally:
db.close()
+94
View File
@@ -0,0 +1,94 @@
import logging
from fastapi import FastAPI
from app.api.router import api_router
from app.core.config import get_settings
from app.core.middleware import install_middleware
logger = logging.getLogger("gsfdc.startup")
def prepare_runtime() -> None:
settings = get_settings()
if not settings.database_url.strip():
return
import app.models.about # noqa: F401
import app.models.content # noqa: F401
import app.models.home # noqa: F401
import app.models.report_filing # noqa: F401
import app.models.legal # noqa: F401
import app.models.discipline # noqa: F401
import app.models.expert # noqa: F401
import app.models.member # noqa: F401
import app.models.uploaded_case # noqa: F401
import app.models.rbac # noqa: F401
import app.models.security # noqa: F401
from app.db import Base, SessionLocal, get_engine
from app.models.content import ensure_site_defaults
from app.models.home import (
ensure_article_body_capacity,
ensure_home_templates,
ensure_hot_link_slots,
retire_removed_shortcut_keys,
)
from app.models.uploaded_case import ensure_uploaded_case_columns
from app.services.ip_guard import seed_ip_blacklist
engine = get_engine()
Base.metadata.create_all(bind=engine)
SessionLocal.configure(bind=engine)
db = SessionLocal()
try:
ensure_site_defaults(db)
ensure_home_templates(db)
ensure_hot_link_slots(db)
retire_removed_shortcut_keys(db)
ensure_article_body_capacity(db)
ensure_uploaded_case_columns(db)
seed_ip_blacklist(db)
from app.commands.create_superuser import (
ensure_about_menu,
ensure_directory_menu,
ensure_expert_menu,
ensure_home_menu,
ensure_library_menu,
ensure_party_menu,
ensure_report_menu,
ensure_discipline_menu,
ensure_edu_menu,
ensure_tech_menu,
)
ensure_home_menu(db)
ensure_about_menu(db)
ensure_directory_menu(db)
ensure_party_menu(db)
ensure_expert_menu(db)
ensure_library_menu(db)
ensure_report_menu(db)
ensure_discipline_menu(db)
ensure_tech_menu(db)
ensure_edu_menu(db)
db.commit()
finally:
db.close()
if settings.minio_endpoint.strip():
try:
from app.services.storage import ensure_buckets
ensure_buckets()
except Exception:
logger.warning("对象存储初始化失败")
def create_app() -> FastAPI:
settings = get_settings()
app = FastAPI(title=settings.app_name, docs_url="/docs", openapi_url="/openapi.json")
install_middleware(app)
app.include_router(api_router)
prepare_runtime()
return app
app = create_app()
View File
Whitespace-only changes.
+319
View File
@@ -0,0 +1,319 @@
from sqlalchemy import Boolean, Integer, String, Text, select
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
ABOUT_PAGE_KEYS = ("intro", "org", "contact", "party_branch")
ABOUT_PAGE_PLACEHOLDERS = {
"intro": "协会简介整理中",
"org": "组织机构整理中",
"contact": "联系与合作信息整理中",
"party_branch": "协会党支部介绍整理中",
}
EXPERT_LIST_PLACEHOLDER = "暂无专家委员会信息"
class AboutPage(Base):
__tablename__ = "about_page"
__table_args__ = _mysql_args()
page_key: Mapped[str] = mapped_column(String(32), primary_key=True)
body_html: Mapped[str] = mapped_column(Text, nullable=False, default="")
published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
class AboutPageAttachment(Base):
__tablename__ = "about_page_attachment"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
page_key: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
def _public_file(db, file_id: int):
from app.models.content import AdminFile
if isinstance(file_id, bool) or not isinstance(file_id, int) or file_id <= 0:
return None
row = db.get(AdminFile, file_id)
if row is None or row.bucket != "public" or not row.object_key:
return None
return row
def _page_attachments(db, page_key: str) -> list:
from app.services.storage import public_object_url
links = db.scalars(
select(AboutPageAttachment)
.where(AboutPageAttachment.page_key == page_key)
.order_by(AboutPageAttachment.position.asc(), AboutPageAttachment.id.asc())
).all()
files = []
for link in links:
row = _public_file(db, link.file_id)
if row is None:
continue
files.append({"filename": row.filename, "url": public_object_url(row.object_key)})
return files
def _editor_attachments(db, page_key: str) -> list:
from app.services.storage import public_object_url
links = db.scalars(
select(AboutPageAttachment)
.where(AboutPageAttachment.page_key == page_key)
.order_by(AboutPageAttachment.position.asc(), AboutPageAttachment.id.asc())
).all()
files = []
for link in links:
row = _public_file(db, link.file_id)
if row is None:
continue
files.append(
{
"id": row.id,
"filename": row.filename,
"url": public_object_url(row.object_key),
}
)
return files
def _replace_attachments(db, page_key: str, attachments: list) -> None:
links = db.scalars(
select(AboutPageAttachment).where(AboutPageAttachment.page_key == page_key)
).all()
for link in links:
db.delete(link)
db.flush()
for index, row in enumerate(attachments):
db.add(AboutPageAttachment(page_key=page_key, file_id=row.id, position=index))
def _prepare_page(db, payload: dict) -> tuple[str, bool, list]:
from app.core.config import get_settings
from app.models.content import AdminFile
from app.services.html_filter import filter_html
attachments = []
for file_id in payload.get("attachmentFileIds") or []:
row = _public_file(db, file_id)
if row is None:
raise ValueError("附件必须是已上传的公开文件")
attachments.append(row)
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
cleaned = filter_html(payload.get("bodyHtml") or "", list(keys), get_settings().minio_base_url)
return cleaned, bool(payload.get("published", False)), attachments
def save_about_page(db, page_key: str, payload: dict) -> None:
if page_key not in ABOUT_PAGE_KEYS:
raise ValueError("单篇页键不正确")
body_html, published, attachments = _prepare_page(db, payload)
row = db.get(AboutPage, page_key)
if row is None:
row = AboutPage(page_key=page_key)
db.add(row)
row.body_html = body_html
row.published = published
db.flush()
_replace_attachments(db, page_key, attachments)
db.commit()
def admin_about_page(db, page_key: str) -> dict | None:
if page_key not in ABOUT_PAGE_KEYS:
return None
row = db.get(AboutPage, page_key)
files = _editor_attachments(db, page_key)
return {
"key": page_key,
"published": bool(row.published) if row else False,
"bodyHtml": row.body_html if row else "",
"attachmentFileIds": [item["id"] for item in files],
"attachments": files,
}
def public_about_page(db, page_key: str) -> dict | None:
if page_key not in ABOUT_PAGE_KEYS:
return None
placeholder = ABOUT_PAGE_PLACEHOLDERS[page_key]
row = db.get(AboutPage, page_key)
files = _page_attachments(db, page_key) if row else []
body = (row.body_html if row else "").strip()
if row is None or not row.published or (not body and not files):
return {"key": page_key, "placeholder": placeholder}
return {
"key": page_key,
"bodyHtml": row.body_html,
"attachments": files,
}
class AboutExpert(Base):
__tablename__ = "about_expert"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(200), nullable=False, default="")
body_html: Mapped[str] = mapped_column(Text, nullable=False, default="")
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
class AboutExpertAttachment(Base):
__tablename__ = "about_expert_attachment"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
expert_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
def _expert_attachments(db, expert_id: int, *, editor: bool = False) -> list:
from app.services.storage import public_object_url
links = db.scalars(
select(AboutExpertAttachment)
.where(AboutExpertAttachment.expert_id == expert_id)
.order_by(AboutExpertAttachment.position.asc(), AboutExpertAttachment.id.asc())
).all()
files = []
for link in links:
row = _public_file(db, link.file_id)
if row is None:
continue
item = {"filename": row.filename, "url": public_object_url(row.object_key)}
if editor:
item = {"id": row.id, **item}
files.append(item)
return files
def _replace_expert_attachments(db, expert_id: int, attachments: list) -> None:
links = db.scalars(
select(AboutExpertAttachment).where(AboutExpertAttachment.expert_id == expert_id)
).all()
for link in links:
db.delete(link)
db.flush()
for index, row in enumerate(attachments):
db.add(AboutExpertAttachment(expert_id=expert_id, file_id=row.id, position=index))
def _prepare_expert(db, payload: dict) -> tuple[dict, list]:
from app.core.config import get_settings
from app.models.content import AdminFile
from app.services.html_filter import filter_html
name = payload.get("name")
if not isinstance(name, str) or not name.strip():
raise ValueError("委员会名称不能为空")
sort_order = payload.get("sortOrder", 0)
if isinstance(sort_order, bool) or not isinstance(sort_order, int):
raise ValueError("排序必须是整数")
attachments = []
for file_id in payload.get("attachmentFileIds") or []:
row = _public_file(db, file_id)
if row is None:
raise ValueError("附件必须是已上传的公开文件")
attachments.append(row)
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
cleaned = filter_html(payload.get("bodyHtml") or "", list(keys), get_settings().minio_base_url)
fields = {
"name": name.strip(),
"body_html": cleaned,
"sort_order": sort_order,
"published": bool(payload.get("published", False)),
}
return fields, attachments
def create_expert(db, payload: dict) -> int:
fields, attachments = _prepare_expert(db, payload)
row = AboutExpert(**fields)
db.add(row)
db.flush()
_replace_expert_attachments(db, row.id, attachments)
db.commit()
db.refresh(row)
return row.id
def update_expert(db, expert_id: int, payload: dict) -> None:
row = db.get(AboutExpert, expert_id)
if row is None:
raise ValueError("专家委员会不存在")
fields, attachments = _prepare_expert(db, payload)
for key, value in fields.items():
setattr(row, key, value)
_replace_expert_attachments(db, row.id, attachments)
db.commit()
def delete_expert(db, expert_id: int) -> None:
row = db.get(AboutExpert, expert_id)
if row is None:
raise ValueError("专家委员会不存在")
links = db.scalars(
select(AboutExpertAttachment).where(AboutExpertAttachment.expert_id == expert_id)
).all()
for link in links:
db.delete(link)
db.delete(row)
db.commit()
def admin_experts(db) -> dict:
rows = db.scalars(
select(AboutExpert).order_by(AboutExpert.sort_order.asc(), AboutExpert.id.asc())
).all()
items = []
for row in rows:
files = _expert_attachments(db, row.id, editor=True)
items.append(
{
"id": row.id,
"name": row.name,
"bodyHtml": row.body_html,
"sortOrder": row.sort_order,
"published": bool(row.published),
"attachmentFileIds": [item["id"] for item in files],
"attachments": files,
}
)
return {"items": items}
def public_experts(db) -> dict:
rows = db.scalars(
select(AboutExpert)
.where(AboutExpert.published.is_(True))
.order_by(AboutExpert.sort_order.asc(), AboutExpert.id.asc())
).all()
if not rows:
return {"placeholder": EXPERT_LIST_PLACEHOLDER}
return {"items": [{"id": row.id, "name": row.name} for row in rows]}
def public_expert(db, expert_id: int) -> dict | None:
row = db.get(AboutExpert, expert_id)
if row is None or not row.published:
return None
return {
"id": row.id,
"name": row.name,
"bodyHtml": row.body_html,
"attachments": _expert_attachments(db, row.id),
}
+165
View File
@@ -0,0 +1,165 @@
import json
from datetime import datetime, timezone
from sqlalchemy import DateTime, Integer, String, Text, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
DEFAULTS: dict[str, str] = {
"site_name": "甘肃省房地产价格评估行业协会",
"logo_file_id": "",
"banner_file_ids": "[]",
"icp_text": "陇ICP备19001227号",
"police_text": "甘公网安备62010202001984号",
"friend_links": "[]",
"link_cirea": "",
"link_housing": "",
"complaint_workdays": "",
"expert_reply_workdays": "",
"upload_max_bytes": "10485760",
"login_max_failures": "5",
"login_lock_minutes": "15",
}
SETTING_KEYS = tuple(DEFAULTS)
_JSON_KEYS = {"banner_file_ids", "friend_links"}
_NUMBER_KEYS = {"upload_max_bytes", "login_max_failures", "login_lock_minutes"}
_OPTIONAL_NUMBER_KEYS = {"complaint_workdays", "expert_reply_workdays"}
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
class SiteSetting(Base):
__tablename__ = "site_setting"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
key: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
value: Mapped[str] = mapped_column(Text, nullable=False, default="")
class AdminFile(Base):
__tablename__ = "admin_file"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
bucket: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
object_key: Mapped[str] = mapped_column(String(255), nullable=False)
filename: Mapped[str] = mapped_column(String(255), nullable=False)
content_type: Mapped[str] = mapped_column(String(128), nullable=False, default="")
size: Mapped[int] = mapped_column(Integer, nullable=False)
created_by: Mapped[int | None] = mapped_column(Integer, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
class SensitiveWord(Base):
__tablename__ = "sensitive_word"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
word: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
def ensure_site_defaults(db) -> None:
existing = set(db.scalars(select(SiteSetting.key)))
missing = [
SiteSetting(key=key, value=value)
for key, value in DEFAULTS.items()
if key not in existing
]
if not missing:
return
db.add_all(missing)
try:
db.commit()
except IntegrityError:
db.rollback()
def read_upload_limit(db) -> int | None:
row = db.scalar(select(SiteSetting).where(SiteSetting.key == "upload_max_bytes"))
if row is None:
return None
text = str(row.value).strip()
if not text.isdigit():
return None
value = int(text)
if value <= 0:
return None
return value
def save_settings(db, values: dict[str, str]) -> None:
ensure_site_defaults(db)
for key, value in values.items():
row = db.scalar(select(SiteSetting).where(SiteSetting.key == key))
if row is None:
db.add(SiteSetting(key=key, value=value))
else:
row.value = value
db.commit()
def _present(key: str, raw: str):
if key in _JSON_KEYS:
if not raw:
return []
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
return []
return parsed if isinstance(parsed, list) else []
if key in _NUMBER_KEYS:
text = str(raw).strip()
if text.isdigit():
return int(text)
return raw
if key in _OPTIONAL_NUMBER_KEYS:
text = "" if raw is None else str(raw).strip()
if not text:
return ""
if text.isdigit():
return int(text)
return text
return "" if raw is None else str(raw)
def _public_urls(db, file_ids: list) -> list[str]:
from app.services.storage import public_object_url
urls: list[str] = []
for item in file_ids:
if isinstance(item, bool):
continue
try:
file_id = int(str(item).strip())
except (TypeError, ValueError):
continue
if file_id <= 0:
continue
row = db.get(AdminFile, file_id)
if row is None or row.bucket != "public" or not row.object_key:
continue
urls.append(public_object_url(row.object_key))
return urls
def settings_view(db) -> dict:
ensure_site_defaults(db)
rows = db.scalars(select(SiteSetting)).all()
raw = {row.key: row.value for row in rows}
view = {key: _present(key, raw.get(key, DEFAULTS.get(key, ""))) for key in SETTING_KEYS}
logo_id = raw.get("logo_file_id", "")
logo_urls = _public_urls(db, [logo_id]) if str(logo_id).strip() else []
view["logoUrl"] = logo_urls[0] if logo_urls else ""
banners = view["banner_file_ids"] if isinstance(view["banner_file_ids"], list) else []
view["bannerUrls"] = _public_urls(db, banners)
return view
+454
View File
@@ -0,0 +1,454 @@
import re
import secrets
from datetime import datetime, timezone
from sqlalchemy import DateTime, Integer, String, Text, func, select
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
COMPLAINT_STATUSES = ("pending", "processed")
DEFAULT_COMPLAINT_WORKDAYS = 30
SCOPE_EMPTY = "受理范围说明整理中"
PROCESS_EMPTY = "处理流程整理中"
MAX_EVIDENCE = 8
_MOBILE = re.compile(r"^1[3-9]\d{9}$")
_EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
_CODE = re.compile(r"^[0-9A-F]{12}$")
_NOTICE_PHONE = "discipline_phone"
_NOTICE_EMAIL = "discipline_email"
_NOTICE_SCOPE = "discipline_scope_html"
_NOTICE_PROCESS = "discipline_process_html"
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
class DisciplineComplaint(Base):
__tablename__ = "discipline_complaint"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
code: Mapped[str] = mapped_column(String(16), unique=True, nullable=False)
title: Mapped[str] = mapped_column(String(200), nullable=False, default="")
subject: Mapped[str] = mapped_column(String(200), nullable=False, default="")
body: Mapped[str] = mapped_column(Text, nullable=False, default="")
contact_name: Mapped[str] = mapped_column(String(40), nullable=False, default="")
mobile_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="")
mobile_mask: Mapped[str] = mapped_column(String(32), nullable=False, default="")
email_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="")
email_mask: Mapped[str] = mapped_column(String(160), nullable=False, default="")
status: Mapped[str] = mapped_column(String(16), nullable=False, default="pending", index=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now, index=True)
processed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
processed_by: Mapped[int | None] = mapped_column(Integer, nullable=True)
class DisciplineComplaintFile(Base):
__tablename__ = "discipline_complaint_file"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
complaint_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
def complaint_workdays(db) -> int:
from app.models.content import SiteSetting
row = db.scalar(select(SiteSetting).where(SiteSetting.key == "complaint_workdays"))
raw = (row.value if row else "").strip()
if not raw:
return DEFAULT_COMPLAINT_WORKDAYS
try:
value = int(raw)
except ValueError:
return DEFAULT_COMPLAINT_WORKDAYS
if value < 0:
return DEFAULT_COMPLAINT_WORKDAYS
return value
def _setting(db, key: str) -> str:
from app.models.content import SiteSetting
row = db.scalar(select(SiteSetting).where(SiteSetting.key == key))
return "" if row is None or row.value is None else str(row.value)
def _put_setting(db, key: str, value: str) -> None:
from app.models.content import SiteSetting
row = db.scalar(select(SiteSetting).where(SiteSetting.key == key))
if row is None:
db.add(SiteSetting(key=key, value=value))
else:
row.value = value
def _visible_text(html: str) -> str:
text = re.sub(r"<[^>]+>", "", html or "")
return text.replace("&nbsp;", " ").replace("\xa0", " ").strip()
def _filter_notice_html(db, html: str) -> str:
from app.core.config import get_settings
from app.models.content import AdminFile
from app.services.html_filter import filter_html
if len(html or "") > 20000:
raise ValueError("说明内容过长")
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
cleaned = filter_html(html or "", list(keys), get_settings().minio_base_url)
if not _visible_text(cleaned):
return ""
return cleaned
def _notice_phone(value: str) -> str:
from app.services.html_filter import is_javascript_url
text = " ".join((value or "").split())
if len(text) > 40 or is_javascript_url(text):
raise ValueError("举报电话不正确")
return text
def _notice_email(value: str) -> str:
text = (value or "").strip()
if not text:
return ""
if len(text) > 120 or not _EMAIL.fullmatch(text):
raise ValueError("专用邮箱格式不正确")
return text
def public_notice(db) -> dict:
scope = _setting(db, _NOTICE_SCOPE)
process = _setting(db, _NOTICE_PROCESS)
return {
"phone": _setting(db, _NOTICE_PHONE),
"email": _setting(db, _NOTICE_EMAIL),
"scopeHtml": scope,
"processHtml": process,
"scopePlaceholder": "" if scope else SCOPE_EMPTY,
"processPlaceholder": "" if process else PROCESS_EMPTY,
"workdays": complaint_workdays(db),
}
def admin_notice(db) -> dict:
return {
"phone": _setting(db, _NOTICE_PHONE),
"email": _setting(db, _NOTICE_EMAIL),
"scopeHtml": _setting(db, _NOTICE_SCOPE),
"processHtml": _setting(db, _NOTICE_PROCESS),
"workdays": complaint_workdays(db),
}
def save_notice(db, payload: dict) -> None:
phone = _notice_phone("" if payload.get("phone") is None else str(payload.get("phone")))
email = _notice_email("" if payload.get("email") is None else str(payload.get("email")))
scope = _filter_notice_html(db, "" if payload.get("scopeHtml") is None else str(payload.get("scopeHtml")))
process = _filter_notice_html(
db, "" if payload.get("processHtml") is None else str(payload.get("processHtml"))
)
_put_setting(db, _NOTICE_PHONE, phone)
_put_setting(db, _NOTICE_EMAIL, email)
_put_setting(db, _NOTICE_SCOPE, scope)
_put_setting(db, _NOTICE_PROCESS, process)
db.commit()
def _plain(value, *, label: str, limit: int) -> str:
text = "" if value is None else str(value)
text = text.replace("\r\n", "\n").replace("\r", "\n").strip()
if label != "违规事实":
text = " ".join(text.split())
if not text:
raise ValueError(f"请填写{label}")
if len(text) > limit:
raise ValueError(f"{label}过长")
return text
def _mobile(value: str) -> str:
text = re.sub(r"[\s-]", "", value or "")
if not _MOBILE.fullmatch(text):
raise ValueError("请填写有效的联系电话")
return text
def _reporter_email(value: str) -> str:
text = (value or "").strip()
if not text:
return ""
if len(text) > 120 or not _EMAIL.fullmatch(text):
raise ValueError("联系邮箱格式不正确")
return text
def _reject_sensitive(db, text: str) -> None:
from app.models.content import SensitiveWord
words = db.scalars(select(SensitiveWord.word)).all()
if any(word and word in text for word in words):
raise ValueError("内容包含敏感词,请修改后再提交")
def _status_label(status: str) -> str:
return "已处理" if status == "processed" else "待处理"
def _new_code(db) -> str:
for _ in range(5):
code = secrets.token_hex(6).upper()
exists = db.scalar(select(DisciplineComplaint.id).where(DisciplineComplaint.code == code))
if exists is None:
return code
raise ValueError("查询码生成失败,请稍后再试")
def normalize_code(value: str) -> str:
return re.sub(r"\s+", "", value or "").upper()
def _cleanup_objects(keys: list[str]) -> None:
from app.services.storage import remove_stored_object
for key in keys:
try:
remove_stored_object("private", key)
except Exception:
continue
def create_complaint(
db,
*,
title: str,
subject: str,
body: str,
contact_name: str,
mobile: str,
email: str,
files: list[tuple[str, str, bytes]],
) -> dict:
from app.core.field_crypto import encrypt_text
from app.core.masking import mask_email, mask_mobile
from app.models.content import AdminFile
from app.services.storage import make_object_key, safe_filename, upload_object
cleaned_title = _plain(title, label="举报标题", limit=200)
cleaned_subject = _plain(subject, label="被举报对象", limit=200)
cleaned_body = _plain(body, label="违规事实", limit=4000)
cleaned_name = _plain(contact_name, label="联系人", limit=40)
cleaned_mobile = _mobile(mobile)
cleaned_email = _reporter_email(email)
_reject_sensitive(db, "\n".join([cleaned_title, cleaned_subject, cleaned_body, cleaned_name]))
if not files:
raise ValueError("请上传证据材料")
if len(files) > MAX_EVIDENCE:
raise ValueError("证据材料不能超过 8 个")
for filename, _content_type, data in files:
if not data:
raise ValueError("证据材料不能为空")
if not safe_filename(filename):
raise ValueError("证据材料文件名不正确")
mobile_cipher = encrypt_text(cleaned_mobile)
email_cipher = encrypt_text(cleaned_email) if cleaned_email else ""
stored: list[str] = []
try:
file_rows = []
for filename, content_type, data in files:
object_key = make_object_key(filename)
upload_object("private", object_key, data, content_type or "application/octet-stream")
stored.append(object_key)
row = AdminFile(
bucket="private",
object_key=object_key,
filename=safe_filename(filename),
content_type=(content_type or "")[:128],
size=len(data),
created_by=None,
)
db.add(row)
db.flush()
file_rows.append(row)
complaint = DisciplineComplaint(
code=_new_code(db),
title=cleaned_title,
subject=cleaned_subject,
body=cleaned_body,
contact_name=cleaned_name,
mobile_cipher=mobile_cipher,
mobile_mask=mask_mobile(cleaned_mobile),
email_cipher=email_cipher,
email_mask=mask_email(cleaned_email),
status="pending",
created_at=_now(),
)
db.add(complaint)
db.flush()
for index, row in enumerate(file_rows):
db.add(
DisciplineComplaintFile(
complaint_id=complaint.id,
file_id=row.id,
position=index,
)
)
db.commit()
db.refresh(complaint)
except Exception:
db.rollback()
_cleanup_objects(stored)
raise
return {
"code": complaint.code,
"status": complaint.status,
"statusLabel": _status_label(complaint.status),
"workdays": complaint_workdays(db),
}
def _overdue(row: DisciplineComplaint, days: int) -> bool:
from app.models.expert import is_overdue
if row.status != "pending":
return False
return bool(is_overdue(row.created_at, days))
def _list_item(row: DisciplineComplaint, *, days: int, attachment_count: int) -> dict:
return {
"id": row.id,
"code": row.code,
"title": row.title,
"subject": row.subject,
"contactName": row.contact_name,
"mobileMask": row.mobile_mask,
"emailMask": row.email_mask,
"status": row.status,
"statusLabel": _status_label(row.status),
"createdAt": row.created_at.isoformat(timespec="seconds") if row.created_at else "",
"processedAt": row.processed_at.isoformat(timespec="seconds") if row.processed_at else "",
"overdue": _overdue(row, days),
"attachmentCount": attachment_count,
}
def admin_complaints(db, *, status: str | None = None) -> dict:
chosen = (status or "").strip()
if chosen and chosen not in COMPLAINT_STATUSES:
raise ValueError("状态不正确")
days = complaint_workdays(db)
filters = []
if chosen:
filters.append(DisciplineComplaint.status == chosen)
rows = db.scalars(
select(DisciplineComplaint)
.where(*filters)
.order_by(DisciplineComplaint.created_at.desc(), DisciplineComplaint.id.desc())
).all()
counts = dict(
db.execute(
select(DisciplineComplaintFile.complaint_id, func.count())
.group_by(DisciplineComplaintFile.complaint_id)
).all()
)
pending = db.scalar(
select(func.count())
.select_from(DisciplineComplaint)
.where(DisciplineComplaint.status == "pending")
) or 0
return {
"items": [
_list_item(row, days=days, attachment_count=int(counts.get(row.id, 0)))
for row in rows
],
"pendingCount": int(pending),
"workdays": days,
}
def _attachments(db, complaint_id: int) -> list[dict]:
from app.models.content import AdminFile
from app.services.storage import private_object_url
links = db.scalars(
select(DisciplineComplaintFile)
.where(DisciplineComplaintFile.complaint_id == complaint_id)
.order_by(DisciplineComplaintFile.position.asc(), DisciplineComplaintFile.id.asc())
).all()
items = []
for link in links:
row = db.get(AdminFile, link.file_id)
if row is None or row.bucket != "private":
continue
url, expires_at = private_object_url(row.object_key)
items.append(
{
"id": row.id,
"filename": row.filename,
"contentType": row.content_type or "",
"url": url,
"expiresAt": expires_at.isoformat(),
}
)
return items
def admin_complaint(db, complaint_id: int) -> dict | None:
from app.core.field_crypto import decrypt_text
row = db.get(DisciplineComplaint, complaint_id)
if row is None:
return None
days = complaint_workdays(db)
item = _list_item(row, days=days, attachment_count=0)
item["body"] = row.body
item["mobile"] = decrypt_text(row.mobile_cipher)
item["email"] = decrypt_text(row.email_cipher) if row.email_cipher else ""
item["attachments"] = _attachments(db, row.id)
item["attachmentCount"] = len(item["attachments"])
return item
def mark_processed(db, complaint_id: int, *, staff_id: int) -> None:
row = db.get(DisciplineComplaint, complaint_id)
if row is None:
raise ValueError("投诉不存在")
if row.status != "processed":
row.status = "processed"
row.processed_at = _now()
row.processed_by = staff_id
db.commit()
def public_complaint_status(db, code: str) -> dict | None:
normalized = normalize_code(code)
if not _CODE.fullmatch(normalized):
return None
row = db.scalar(select(DisciplineComplaint).where(DisciplineComplaint.code == normalized))
if row is None:
return None
days = complaint_workdays(db)
created_on = row.created_at.date().isoformat() if row.created_at else ""
return {
"code": row.code,
"status": row.status,
"statusLabel": _status_label(row.status),
"createdOn": created_on,
"workdays": days,
"overdue": _overdue(row, days),
}
+322
View File
@@ -0,0 +1,322 @@
from datetime import date, datetime, timedelta, timezone
from sqlalchemy import DateTime, Integer, String, Text, func, select
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
QUESTION_STATUSES = ("pending", "replied")
DEFAULT_REPLY_WORKDAYS = 3
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
class ExpertQuestion(Base):
__tablename__ = "expert_question"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
member_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
title: Mapped[str] = mapped_column(String(200), nullable=False, default="")
body: Mapped[str] = mapped_column(Text, nullable=False, default="")
status: Mapped[str] = mapped_column(String(16), nullable=False, default="pending", index=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now, index=True)
replied_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
class ExpertQuestionAttachment(Base):
__tablename__ = "expert_question_attachment"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
question_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
class ExpertReply(Base):
__tablename__ = "expert_reply"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
question_id: Mapped[int] = mapped_column(Integer, unique=True, nullable=False)
body_html: Mapped[str] = mapped_column(Text, nullable=False, default="")
staff_id: Mapped[int] = mapped_column(Integer, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
class ExpertReplyAttachment(Base):
__tablename__ = "expert_reply_attachment"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
reply_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
def reply_workdays(db) -> int:
from app.models.content import SiteSetting
row = db.scalar(select(SiteSetting).where(SiteSetting.key == "expert_reply_workdays"))
raw = (row.value if row else "").strip()
if not raw:
return DEFAULT_REPLY_WORKDAYS
try:
value = int(raw)
except ValueError:
return DEFAULT_REPLY_WORKDAYS
return value if value > 0 else DEFAULT_REPLY_WORKDAYS
def workday_deadline(start: datetime | date, days: int) -> date:
current = start.date() if isinstance(start, datetime) else start
remaining = max(int(days), 0)
while remaining > 0:
current = current + timedelta(days=1)
if current.weekday() < 5:
remaining -= 1
return current
def is_overdue(created_at: datetime, days: int, *, now: datetime | None = None) -> bool:
if created_at is None:
return False
current = now or _now()
return current.date() > workday_deadline(created_at, days)
def _private_file(db, file_id: int):
from app.models.content import AdminFile
if file_id is None:
return None
row = db.get(AdminFile, file_id)
if row is None or row.bucket != "private":
return None
return row
def _attachment_payload(db, file_id: int) -> dict | None:
from app.services.storage import private_object_url
row = _private_file(db, file_id)
if row is None:
return None
url, expires_at = private_object_url(row.object_key)
return {
"id": row.id,
"filename": row.filename,
"contentType": row.content_type or "",
"url": url,
"expiresAt": expires_at.isoformat(),
}
def _question_attachments(db, question_id: int) -> list[dict]:
links = db.scalars(
select(ExpertQuestionAttachment)
.where(ExpertQuestionAttachment.question_id == question_id)
.order_by(ExpertQuestionAttachment.position.asc(), ExpertQuestionAttachment.id.asc())
).all()
items = []
for link in links:
payload = _attachment_payload(db, link.file_id)
if payload is not None:
items.append(payload)
return items
def _reply_attachments(db, reply_id: int) -> list[dict]:
links = db.scalars(
select(ExpertReplyAttachment)
.where(ExpertReplyAttachment.reply_id == reply_id)
.order_by(ExpertReplyAttachment.position.asc(), ExpertReplyAttachment.id.asc())
).all()
items = []
for link in links:
payload = _attachment_payload(db, link.file_id)
if payload is not None:
items.append(payload)
return items
def _question_list_item(db, row: ExpertQuestion, *, days: int, include_member: bool = False) -> dict:
from app.models.member import get_member_by_id
item = {
"id": row.id,
"title": row.title,
"status": row.status,
"statusLabel": "已回复" if row.status == "replied" else "待回复",
"createdAt": row.created_at.isoformat(timespec="seconds") if row.created_at else "",
"repliedAt": row.replied_at.isoformat(timespec="seconds") if row.replied_at else "",
"overdue": bool(row.status == "pending" and is_overdue(row.created_at, days)),
}
if include_member:
member = get_member_by_id(db, row.member_id)
item["memberId"] = row.member_id
item["memberEmail"] = member.email if member else ""
return item
def create_question(db, *, member_id: int, title: str, body: str, attachment_file_ids: list[int]) -> int:
cleaned_title = (title or "").strip()
cleaned_body = (body or "").strip()
if not cleaned_title:
raise ValueError("标题不能为空")
if not cleaned_body:
raise ValueError("正文不能为空")
if len(cleaned_title) > 200:
raise ValueError("标题过长")
files = []
for file_id in attachment_file_ids or []:
row = _private_file(db, file_id)
if row is None:
raise ValueError("附件必须是已上传的私有文件")
files.append(row)
question = ExpertQuestion(
member_id=member_id,
title=cleaned_title,
body=cleaned_body,
status="pending",
created_at=_now(),
)
db.add(question)
db.flush()
for index, file_row in enumerate(files):
db.add(
ExpertQuestionAttachment(
question_id=question.id,
file_id=file_row.id,
position=index,
)
)
db.commit()
db.refresh(question)
return question.id
def member_questions(db, member_id: int) -> dict:
days = reply_workdays(db)
rows = db.scalars(
select(ExpertQuestion)
.where(ExpertQuestion.member_id == member_id)
.order_by(ExpertQuestion.created_at.desc(), ExpertQuestion.id.desc())
).all()
return {"items": [_question_list_item(db, row, days=days) for row in rows]}
def member_question(db, member_id: int, question_id: int) -> dict | None:
row = db.get(ExpertQuestion, question_id)
if row is None or row.member_id != member_id:
return None
days = reply_workdays(db)
body = _question_list_item(db, row, days=days)
body["body"] = row.body
body["attachments"] = _question_attachments(db, row.id)
reply = db.scalar(select(ExpertReply).where(ExpertReply.question_id == row.id))
if reply is not None:
body["reply"] = {
"bodyHtml": reply.body_html,
"createdAt": reply.created_at.isoformat(timespec="seconds") if reply.created_at else "",
"attachments": _reply_attachments(db, reply.id),
}
return body
def pending_count(db) -> int:
return int(
db.scalar(
select(func.count())
.select_from(ExpertQuestion)
.where(ExpertQuestion.status == "pending")
)
or 0
)
def admin_questions(db, *, status: str | None = None) -> dict:
days = reply_workdays(db)
stmt = select(ExpertQuestion).order_by(ExpertQuestion.created_at.desc(), ExpertQuestion.id.desc())
if status in QUESTION_STATUSES:
stmt = stmt.where(ExpertQuestion.status == status)
rows = db.scalars(stmt).all()
return {
"items": [_question_list_item(db, row, days=days, include_member=True) for row in rows],
"pendingCount": pending_count(db),
"replyWorkdays": days,
}
def admin_question(db, question_id: int) -> dict | None:
row = db.get(ExpertQuestion, question_id)
if row is None:
return None
days = reply_workdays(db)
body = _question_list_item(db, row, days=days, include_member=True)
body["body"] = row.body
body["attachments"] = _question_attachments(db, row.id)
reply = db.scalar(select(ExpertReply).where(ExpertReply.question_id == row.id))
if reply is not None:
body["reply"] = {
"bodyHtml": reply.body_html,
"createdAt": reply.created_at.isoformat(timespec="seconds") if reply.created_at else "",
"attachments": _reply_attachments(db, reply.id),
}
return body
def reply_question(
db,
*,
question_id: int,
staff_id: int,
body_html: str,
attachment_file_ids: list[int],
) -> None:
from app.core.config import get_settings
from app.models.content import AdminFile
from app.services.html_filter import filter_html
question = db.get(ExpertQuestion, question_id)
if question is None:
raise ValueError("提问不存在")
if question.status != "pending":
raise ValueError("该提问已回复")
files = []
for file_id in attachment_file_ids or []:
row = _private_file(db, file_id)
if row is None:
raise ValueError("附件必须是已上传的私有文件")
files.append(row)
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
cleaned = filter_html(body_html or "", list(keys), get_settings().minio_base_url)
if not cleaned.strip():
raise ValueError("回复正文不能为空")
reply = ExpertReply(
question_id=question.id,
body_html=cleaned,
staff_id=staff_id,
created_at=_now(),
)
db.add(reply)
db.flush()
for index, file_row in enumerate(files):
db.add(
ExpertReplyAttachment(
reply_id=reply.id,
file_id=file_row.id,
position=index,
)
)
question.status = "replied"
question.replied_at = _now()
db.commit()
File diff suppressed because it is too large. Load diff
+104
View File
@@ -0,0 +1,104 @@
"""合规正文:隐私政策、使用条款、网站声明。"""
from sqlalchemy import Boolean, String, Text, select
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
LEGAL_PAGE_KEYS = ("privacy", "terms", "statement")
LEGAL_PAGE_TITLES = {
"privacy": "隐私政策",
"terms": "使用条款",
"statement": "网站声明",
}
LEGAL_PAGE_PLACEHOLDERS = {
"privacy": "隐私政策整理中",
"terms": "使用条款整理中",
"statement": "网站声明整理中",
}
LEGAL_PAGE_PATHS = {
"privacy": "/legal/privacy",
"terms": "/legal/terms",
"statement": "/legal/statement",
}
class LegalPage(Base):
__tablename__ = "legal_page"
__table_args__ = _mysql_args()
page_key: Mapped[str] = mapped_column(String(32), primary_key=True)
body_html: Mapped[str] = mapped_column(Text, nullable=False, default="")
published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
def save_legal_page(db, page_key: str, payload: dict) -> None:
if page_key not in LEGAL_PAGE_KEYS:
raise ValueError("合规页键不正确")
from app.core.config import get_settings
from app.models.content import AdminFile
from app.services.html_filter import filter_html
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
cleaned = filter_html(
payload.get("bodyHtml") or "",
list(keys),
get_settings().minio_base_url,
)
row = db.get(LegalPage, page_key)
if row is None:
row = LegalPage(page_key=page_key)
db.add(row)
row.body_html = cleaned
row.published = bool(payload.get("published", False))
db.commit()
def admin_legal_page(db, page_key: str) -> dict | None:
if page_key not in LEGAL_PAGE_KEYS:
return None
row = db.get(LegalPage, page_key)
return {
"key": page_key,
"title": LEGAL_PAGE_TITLES[page_key],
"published": bool(row.published) if row else False,
"bodyHtml": row.body_html if row else "",
}
def public_legal_page(db, page_key: str) -> dict | None:
if page_key not in LEGAL_PAGE_KEYS:
return None
placeholder = LEGAL_PAGE_PLACEHOLDERS[page_key]
row = db.get(LegalPage, page_key)
body = (row.body_html if row else "").strip()
if row is None or not row.published or not body:
return {
"key": page_key,
"title": LEGAL_PAGE_TITLES[page_key],
"placeholder": placeholder,
}
return {
"key": page_key,
"title": LEGAL_PAGE_TITLES[page_key],
"bodyHtml": row.body_html,
}
def public_compliance_links() -> dict:
"""页脚固定三项,链到站内合规正文页。"""
return {
"links": [
{
"label": LEGAL_PAGE_TITLES[key],
"url": LEGAL_PAGE_PATHS[key],
"navigation": "sameWindow",
}
for key in LEGAL_PAGE_KEYS
]
}
+62
View File
@@ -0,0 +1,62 @@
from datetime import datetime, timezone
from sqlalchemy import DateTime, Integer, String, select
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
MEMBER_STATUSES = ("active", "disabled", "cancelled")
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
class SiteMember(Base):
__tablename__ = "site_member"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
email: Mapped[str] = mapped_column(String(191), unique=True, nullable=False)
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
privacy_accepted_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
def get_member_by_email(db, email: str) -> SiteMember | None:
normalized = (email or "").strip().lower()
if not normalized:
return None
return db.scalar(select(SiteMember).where(SiteMember.email == normalized))
def get_member_by_id(db, member_id: int) -> SiteMember | None:
return db.get(SiteMember, member_id)
def create_member(db, *, email: str, password_hash: str, privacy_accepted_at: datetime) -> SiteMember:
row = SiteMember(
email=email.strip().lower(),
password_hash=password_hash,
status="active",
privacy_accepted_at=privacy_accepted_at,
created_at=_now(),
updated_at=_now(),
)
db.add(row)
db.commit()
db.refresh(row)
return row
def set_member_password(db, member: SiteMember, password_hash: str) -> None:
member.password_hash = password_hash
member.updated_at = _now()
db.commit()
+79
View File
@@ -0,0 +1,79 @@
from datetime import datetime, timezone
from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
def utcnow() -> datetime:
return datetime.now(timezone.utc)
class AdminUser(Base):
__tablename__ = "admin_user"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
username: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
display_name: Mapped[str] = mapped_column(String(64), nullable=False)
mobile_cipher: Mapped[str | None] = mapped_column(Text, nullable=True)
mobile_mask: Mapped[str] = mapped_column(String(32), nullable=False, default="")
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
failed_login_count: Mapped[int] = mapped_column(nullable=False, default=0)
locked_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=utcnow)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=utcnow, onupdate=utcnow
)
class AdminRole(Base):
__tablename__ = "admin_role"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
code: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
name: Mapped[str] = mapped_column(String(64), nullable=False)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=utcnow)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=utcnow, onupdate=utcnow
)
class AdminResource(Base):
__tablename__ = "admin_resource"
__table_args__ = (
# parent_id 为空时,MySQL 唯一索引不会拦住重复的根名称,根节点在服务层再查一次。
UniqueConstraint("parent_id", "name", name="uq_admin_resource_parent_name"),
)
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
parent_id: Mapped[int | None] = mapped_column(ForeignKey("admin_resource.id"), nullable=True)
type: Mapped[str] = mapped_column(String(16), nullable=False)
name: Mapped[str] = mapped_column(String(64), nullable=False)
title: Mapped[str] = mapped_column(String(64), nullable=False)
path: Mapped[str] = mapped_column(String(255), nullable=False, default="")
component: Mapped[str] = mapped_column(String(255), nullable=False, default="")
icon: Mapped[str] = mapped_column(String(64), nullable=False, default="")
permission: Mapped[str] = mapped_column(String(64), nullable=False, default="")
sort: Mapped[int] = mapped_column(nullable=False, default=0)
visible: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default="active")
class AdminUserRole(Base):
__tablename__ = "admin_user_role"
user_id: Mapped[int] = mapped_column(ForeignKey("admin_user.id", ondelete="CASCADE"), primary_key=True)
role_id: Mapped[int] = mapped_column(ForeignKey("admin_role.id", ondelete="CASCADE"), primary_key=True)
class AdminRoleResource(Base):
__tablename__ = "admin_role_resource"
role_id: Mapped[int] = mapped_column(ForeignKey("admin_role.id", ondelete="CASCADE"), primary_key=True)
resource_id: Mapped[int] = mapped_column(
ForeignKey("admin_resource.id", ondelete="CASCADE"), primary_key=True
)
+140
View File
@@ -0,0 +1,140 @@
"""报告备案:工作人员登记,公众按编号对照。"""
from datetime import date
from sqlalchemy import Boolean, Date, Integer, String, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
FOUND_NOTICE = "以出具机构数据为准,协会结果仅供参考。"
MISSING_NOTICE = "协会备案库没有该编号,请向出具机构核实。"
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
class ReportFiling(Base):
__tablename__ = "report_filing"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
institution_name: Mapped[str] = mapped_column(String(200), nullable=False)
report_number: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
issued_on: Mapped[date] = mapped_column(Date, nullable=False)
published: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
def _institution(value: str) -> str:
if not isinstance(value, str) or not value.strip():
raise ValueError("请填写出具机构")
text = value.strip()
if len(text) > 200:
raise ValueError("出具机构过长")
return text
def _number(value: str) -> str:
if not isinstance(value, str) or not value.strip():
raise ValueError("请填写报告编号")
text = value.strip()
if len(text) > 64:
raise ValueError("报告编号过长")
return text
def _issued_on(value: str) -> date:
if not isinstance(value, str) or not value.strip():
raise ValueError("请填写出具日期")
try:
return date.fromisoformat(value.strip())
except ValueError as exc:
raise ValueError("出具日期不正确") from exc
def _admin_filing(row: ReportFiling) -> dict:
return {
"id": row.id,
"institutionName": row.institution_name,
"reportNumber": row.report_number,
"issuedOn": row.issued_on.isoformat(),
"published": bool(row.published),
}
def list_filings(db) -> dict:
rows = db.scalars(select(ReportFiling).order_by(ReportFiling.id.desc())).all()
return {"items": [_admin_filing(row) for row in rows]}
def create_filing(db, *, institution_name: str, report_number: str, issued_on: str, published: bool) -> int:
row = ReportFiling(
institution_name=_institution(institution_name),
report_number=_number(report_number),
issued_on=_issued_on(issued_on),
published=bool(published),
)
db.add(row)
try:
db.commit()
except IntegrityError as exc:
db.rollback()
raise ValueError("报告编号已存在") from exc
return row.id
def update_filing(
db,
filing_id: int,
*,
institution_name: str,
report_number: str,
issued_on: str,
published: bool,
) -> None:
row = db.get(ReportFiling, filing_id)
if row is None:
raise ValueError("备案不存在")
number = _number(report_number)
taken = db.scalar(select(ReportFiling.id).where(ReportFiling.report_number == number, ReportFiling.id != row.id))
if taken is not None:
raise ValueError("报告编号已存在")
row.institution_name = _institution(institution_name)
row.report_number = number
row.issued_on = _issued_on(issued_on)
row.published = bool(published)
try:
db.commit()
except IntegrityError as exc:
db.rollback()
raise ValueError("报告编号已存在") from exc
def delete_filing(db, filing_id: int) -> None:
row = db.get(ReportFiling, filing_id)
if row is None:
raise ValueError("备案不存在")
db.delete(row)
db.commit()
def query_filing(db, number: str) -> dict:
if not isinstance(number, str) or not number.strip():
raise ValueError("请填写报告编号")
text = number.strip()
if len(text) > 64:
return {"found": False, "notice": MISSING_NOTICE}
row = db.scalar(
select(ReportFiling).where(ReportFiling.report_number == text, ReportFiling.published.is_(True))
)
if row is None:
return {"found": False, "notice": MISSING_NOTICE}
return {
"found": True,
"institutionName": row.institution_name,
"reportNumber": row.report_number,
"issuedOn": row.issued_on.isoformat(),
"notice": FOUND_NOTICE,
}
+46
View File
@@ -0,0 +1,46 @@
from datetime import datetime, timezone
from sqlalchemy import DateTime, Index, Integer, String, func
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
def _utcnow() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
class AdminAuditLog(Base):
__tablename__ = "admin_audit_log"
__table_args__ = (
Index("ix_admin_audit_log_username", "username"),
Index("ix_admin_audit_log_created_at", "created_at"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
user_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
username: Mapped[str | None] = mapped_column(String(64), nullable=True)
method: Mapped[str] = mapped_column(String(16), nullable=False)
path: Mapped[str] = mapped_column(String(255), nullable=False)
status_code: Mapped[int] = mapped_column(Integer, nullable=False)
ip: Mapped[str] = mapped_column(String(64), nullable=False, default="", server_default="")
created_at: Mapped[datetime] = mapped_column(
DateTime,
nullable=False,
default=_utcnow,
server_default=func.now(),
)
class AdminIpBlacklist(Base):
__tablename__ = "admin_ip_blacklist"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
ip: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
remark: Mapped[str] = mapped_column(String(255), nullable=False, default="", server_default="")
created_at: Mapped[datetime] = mapped_column(
DateTime,
nullable=False,
default=_utcnow,
server_default=func.now(),
)
+803
View File
@@ -0,0 +1,803 @@
"""上传案例:会员提交的结构化记录,与案例库栏目文章分开。"""
import json
from datetime import date, datetime, timezone
from decimal import Decimal, InvalidOperation
from pathlib import Path
from sqlalchemy import Date, DateTime, Integer, String, Text, or_, select
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
PHOTO_MAX_BYTES = 5 * 1024 * 1024
PAGE_SIZES = (10, 20, 100)
KIND_LABELS = {
"residential": "住宅",
"commercial": "商业",
"office": "办公",
"industrial": "工业",
}
OPEN_KINDS = frozenset({"residential", "commercial", "office", "industrial"})
CASE_TYPES = ("买卖成交", "拍卖成交", "月租金成交", "评估案例")
STRUCTURES = ("钢混", "砖混", "混合", "钢结构")
DECORATIONS = ("毛坯", "简易", "中档", "高档", "豪华")
TOTAL_FLOORS = tuple(str(i) for i in range(1, 61))
FLOOR_NOS = ("-4", "-3", "-2", "-1") + TOTAL_FLOORS
PURPOSES = (
"普通住宅",
"公寓",
"酒店式公寓",
"独立别墅",
"双拼别墅",
"联排别墅",
"停车位",
"地下室",
"其他",
)
LAYOUT_STRUCTURES = ("平面", "复式", "跃式", "错层", "LOFT")
OFFICE_LAYOUT_STRUCTURES = ("办公楼(中间过道两边办公室)", "写字楼(大开间)")
LAYOUTS = (
"单间",
"单身公寓",
"一室一厅",
"两室一厅",
"两室两厅",
"三室一厅",
"三室两厅",
"四室两厅",
"五室两厅",
"六室两厅",
"七室及以上",
)
COMMERCIAL_LAYOUTS = ("大开间", "隔档")
STREET_FRONTAGES = ("单面临街", "双面临街", "三面临街", "十字路口拐角", "不临街(商场或市场内铺面)")
FOOT_TRAFFICS = ("小", "较小", "一般", "较大", "大")
SHOP_TYPES = ("住宅底商", "商业街商铺", "临街门面", "购物中心/百货内铺", "酒店宾馆内铺", "其他")
BUSINESS_FORMATS = (
"空置",
"餐饮",
"服饰鞋帽箱包",
"休闲娱乐",
"美容美发",
"服务业",
"百货",
"酒店宾馆",
"家居建材",
"酒吧",
"汽车维修美容",
"其他",
)
ORIENTATIONS = ("东", "南", "西", "北", "东南", "西南", "东北", "西北", "南北", "东西")
VALUE_INCLUDES = ("装饰装修", "家具用具", "停车位", "花园", "地下室")
INDUSTRIAL_FLOORS = tuple(str(i) for i in range(1, 9))
INDUSTRIAL_LAYOUTS = ("开间",)
INDUSTRIAL_DIRECTIONS = ("南北", "东西")
ROAD_FRONTAGES = ("主干道", "次干道", "街巷")
INDUSTRY_TYPES = ("食品饮料加工", "机械制造", "水泥厂", "热力公司", "其他")
INDUSTRIAL_VALUE_INCLUDES = ("装饰装修", "家具用具")
_REGIONS: list | None = None
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
class UploadedCase(Base):
__tablename__ = "uploaded_case"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
kind: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
member_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
member_email: Mapped[str] = mapped_column(String(191), nullable=False, default="")
case_type: Mapped[str] = mapped_column(String(32), nullable=False)
province: Mapped[str] = mapped_column(String(64), nullable=False)
city: Mapped[str] = mapped_column(String(64), nullable=False)
district: Mapped[str] = mapped_column(String(64), nullable=False)
estate_name: Mapped[str] = mapped_column(String(200), nullable=False)
structure: Mapped[str] = mapped_column(String(32), nullable=False)
case_date: Mapped[date] = mapped_column(Date, nullable=False)
location: Mapped[str] = mapped_column(String(500), nullable=False)
built_year: Mapped[int] = mapped_column(Integer, nullable=False)
total_floors: Mapped[int] = mapped_column(Integer, nullable=False)
floor_no: Mapped[str] = mapped_column(String(8), nullable=False)
purpose: Mapped[str] = mapped_column(String(32), nullable=False)
layout_structure: Mapped[str] = mapped_column(String(32), nullable=False)
decoration: Mapped[str] = mapped_column(String(32), nullable=False)
value_includes: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
area: Mapped[str] = mapped_column(String(32), nullable=False)
layout: Mapped[str] = mapped_column(String(32), nullable=False)
orientation: Mapped[str] = mapped_column(String(16), nullable=False)
unit_price: Mapped[str] = mapped_column(String(32), nullable=False)
remark: Mapped[str] = mapped_column(Text, nullable=False, default="")
institution_name: Mapped[str] = mapped_column(String(200), nullable=False)
street_frontage: Mapped[str] = mapped_column(String(64), nullable=False, default="")
foot_traffic: Mapped[str] = mapped_column(String(32), nullable=False, default="")
shop_type: Mapped[str] = mapped_column(String(64), nullable=False, default="")
business_formats: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
heading: Mapped[str] = mapped_column(String(16), nullable=False, default="")
road_frontage: Mapped[str] = mapped_column(String(32), nullable=False, default="")
industry_type: Mapped[str] = mapped_column(String(32), nullable=False, default="")
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now, index=True)
class UploadedCasePhoto(Base):
__tablename__ = "uploaded_case_photo"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
case_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
file_id: Mapped[int] = mapped_column(Integer, nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
def regions() -> list:
global _REGIONS
if _REGIONS is None:
path = Path(__file__).resolve().parents[1] / "data" / "china_regions.json"
_REGIONS = json.loads(path.read_text(encoding="utf-8"))
return _REGIONS
def built_years(today: date | None = None) -> list[int]:
year = (today or date.today()).year
return list(range(1980, year + 1))
def ensure_uploaded_case_columns(db) -> None:
bind = db.get_bind()
if bind.dialect.name != "mysql":
return
from sqlalchemy import inspect, text
names = {column["name"] for column in inspect(bind).get_columns("uploaded_case")}
statements = []
if "street_frontage" not in names:
statements.append(
"ALTER TABLE uploaded_case ADD COLUMN street_frontage VARCHAR(64) NOT NULL DEFAULT ''"
)
if "foot_traffic" not in names:
statements.append(
"ALTER TABLE uploaded_case ADD COLUMN foot_traffic VARCHAR(32) NOT NULL DEFAULT ''"
)
if "shop_type" not in names:
statements.append("ALTER TABLE uploaded_case ADD COLUMN shop_type VARCHAR(64) NOT NULL DEFAULT ''")
if "business_formats" not in names:
statements.append("ALTER TABLE uploaded_case ADD COLUMN business_formats TEXT NULL")
if "heading" not in names:
statements.append("ALTER TABLE uploaded_case ADD COLUMN heading VARCHAR(16) NOT NULL DEFAULT ''")
if "road_frontage" not in names:
statements.append("ALTER TABLE uploaded_case ADD COLUMN road_frontage VARCHAR(32) NOT NULL DEFAULT ''")
if "industry_type" not in names:
statements.append("ALTER TABLE uploaded_case ADD COLUMN industry_type VARCHAR(32) NOT NULL DEFAULT ''")
for statement in statements:
db.execute(text(statement))
if "business_formats" not in names:
db.execute(text("UPDATE uploaded_case SET business_formats = '[]' WHERE business_formats IS NULL"))
if statements:
db.commit()
def commercial_options(today: date | None = None) -> dict:
return {
"caseTypes": list(CASE_TYPES),
"structures": list(STRUCTURES),
"builtYears": built_years(today),
"totalFloors": list(TOTAL_FLOORS),
"floorNos": list(FLOOR_NOS),
"layouts": list(COMMERCIAL_LAYOUTS),
"decorations": list(DECORATIONS),
"streetFrontages": list(STREET_FRONTAGES),
"orientations": list(ORIENTATIONS),
"footTraffics": list(FOOT_TRAFFICS),
"shopTypes": list(SHOP_TYPES),
"businessFormats": list(BUSINESS_FORMATS),
"valueIncludes": list(VALUE_INCLUDES),
}
def office_options(today: date | None = None) -> dict:
return {
"caseTypes": list(CASE_TYPES),
"structures": list(STRUCTURES),
"builtYears": built_years(today),
"totalFloors": list(TOTAL_FLOORS),
"floorNos": list(FLOOR_NOS),
"layoutStructures": list(OFFICE_LAYOUT_STRUCTURES),
"decorations": list(DECORATIONS),
"valueIncludes": list(VALUE_INCLUDES),
"orientations": list(ORIENTATIONS),
}
def residential_options(today: date | None = None) -> dict:
return {
"caseTypes": list(CASE_TYPES),
"structures": list(STRUCTURES),
"builtYears": built_years(today),
"totalFloors": list(TOTAL_FLOORS),
"floorNos": list(FLOOR_NOS),
"purposes": list(PURPOSES),
"layoutStructures": list(LAYOUT_STRUCTURES),
"decorations": list(DECORATIONS),
"valueIncludes": list(VALUE_INCLUDES),
"layouts": list(LAYOUTS),
"orientations": list(ORIENTATIONS),
}
def industrial_options(today: date | None = None) -> dict:
return {
"caseTypes": list(CASE_TYPES),
"structures": list(STRUCTURES),
"builtYears": built_years(today),
"totalFloors": list(INDUSTRIAL_FLOORS),
"layouts": list(INDUSTRIAL_LAYOUTS),
"headings": list(INDUSTRIAL_DIRECTIONS),
"decorations": list(DECORATIONS),
"roadFrontages": list(ROAD_FRONTAGES),
"orientations": list(INDUSTRIAL_DIRECTIONS),
"industryTypes": list(INDUSTRY_TYPES),
"valueIncludes": list(INDUSTRIAL_VALUE_INCLUDES),
}
def _choice(value, options: tuple[str, ...] | list, label: str) -> str:
text = str(value or "").strip()
if text not in options:
raise ValueError(f"{label}不正确")
return text
def _text(value, label: str, limit: int) -> str:
text = str(value or "").strip()
if not text:
raise ValueError(f"请填写{label}")
if len(text) > limit:
raise ValueError(f"{label}过长")
return text
def _number(value, label: str) -> str:
raw = str(value if value is not None else "").strip()
if not raw:
raise ValueError(f"请填写{label}")
try:
number = Decimal(raw)
except InvalidOperation as exc:
raise ValueError(f"{label}须为数字") from exc
if not number.is_finite():
raise ValueError(f"{label}须为数字")
return format(number, "f")
def _region(province: str, city: str, district: str) -> tuple[str, str, str]:
province = str(province or "").strip()
city = str(city or "").strip()
district = str(district or "").strip()
for item in regions():
if item.get("name") != province:
continue
for child in item.get("sub") or []:
if child.get("name") != city:
continue
names = [row.get("name") for row in child.get("sub") or []]
if district not in names:
raise ValueError("区县不正确")
return province, city, district
raise ValueError("城市不正确")
raise ValueError("省份不正确")
def _includes(value, options: tuple[str, ...] = VALUE_INCLUDES) -> list[str]:
if value is None or value == "" or value == []:
return []
if not isinstance(value, list):
raise ValueError("价值包含不正确")
chosen = []
for item in value:
text = str(item or "").strip()
if text not in options or text in chosen:
raise ValueError("价值包含不正确")
chosen.append(text)
if len(chosen) > 3:
raise ValueError("价值包含最多 3 项")
return chosen
def _formats(value) -> list[str]:
if value is None or value == "" or value == []:
raise ValueError("请选择经营业态")
if not isinstance(value, list):
raise ValueError("经营业态不正确")
chosen = []
for item in value:
text = str(item or "").strip()
if text not in BUSINESS_FORMATS or text in chosen:
raise ValueError("经营业态不正确")
chosen.append(text)
if not chosen:
raise ValueError("请选择经营业态")
if len(chosen) > 3:
raise ValueError("经营业态最多 3 项")
return chosen
def _photos(db, member_id: int, file_ids) -> list[int]:
from app.models.content import AdminFile
if not isinstance(file_ids, list) or not file_ids:
raise ValueError("请上传位置图及案例照片")
ids: list[int] = []
for raw in file_ids:
try:
file_id = int(raw)
except (TypeError, ValueError) as exc:
raise ValueError("位置图及案例照片不正确") from exc
row = db.get(AdminFile, file_id)
if row is None or row.bucket != "private" or row.created_by != member_id:
raise ValueError("位置图及案例照片不正确")
if row.size > PHOTO_MAX_BYTES:
raise ValueError("位置图及案例照片须小于 5MB")
if file_id not in ids:
ids.append(file_id)
return ids
def _residential(db, member_id: int, payload: dict, today: date | None = None) -> dict:
extra = set(payload) - {
"kind",
"caseType",
"province",
"city",
"district",
"estateName",
"structure",
"caseDate",
"location",
"builtYear",
"totalFloors",
"floorNo",
"purpose",
"layoutStructure",
"decoration",
"valueIncludes",
"area",
"layout",
"orientation",
"unitPrice",
"remark",
"institutionName",
"photoFileIds",
}
if extra:
raise ValueError("包含住宅没有的字段")
province, city, district = _region(payload.get("province"), payload.get("city"), payload.get("district"))
raw_date = str(payload.get("caseDate") or "").strip()
try:
case_date = datetime.strptime(raw_date, "%Y-%m-%d").date()
except ValueError as exc:
raise ValueError("案例时间不正确") from exc
year = _choice(str(payload.get("builtYear") or "").strip(), [str(item) for item in built_years(today)], "建筑年代")
remark = str(payload.get("remark") or "").strip()
if remark and not 1 <= len(remark) <= 1000:
raise ValueError("备注长度须在 1 到 1000")
return {
"case_type": _choice(payload.get("caseType"), CASE_TYPES, "案例类型"),
"province": province,
"city": city,
"district": district,
"estate_name": _text(payload.get("estateName"), "楼盘名称", 200),
"structure": _choice(payload.get("structure"), STRUCTURES, "建筑结构"),
"case_date": case_date,
"location": _text(payload.get("location"), "坐落", 500),
"built_year": int(year),
"total_floors": int(_choice(str(payload.get("totalFloors") or "").strip(), TOTAL_FLOORS, "总层数")),
"floor_no": _choice(str(payload.get("floorNo") or "").strip(), FLOOR_NOS, "所在层数"),
"purpose": _choice(payload.get("purpose"), PURPOSES, "用途"),
"layout_structure": _choice(payload.get("layoutStructure"), LAYOUT_STRUCTURES, "户型结构"),
"decoration": _choice(payload.get("decoration"), DECORATIONS, "装修档次"),
"value_includes": _includes(payload.get("valueIncludes")),
"area": _number(payload.get("area"), "建筑面积"),
"layout": _choice(payload.get("layout"), LAYOUTS, "户型"),
"orientation": _choice(payload.get("orientation"), ORIENTATIONS, "朝向"),
"unit_price": _number(payload.get("unitPrice"), "单价"),
"remark": remark,
"institution_name": _text(payload.get("institutionName"), "提交机构名称", 200),
"photo_ids": _photos(db, member_id, payload.get("photoFileIds")),
}
def _commercial(db, member_id: int, payload: dict, today: date | None = None) -> dict:
extra = set(payload) - {
"kind",
"caseType",
"province",
"city",
"district",
"estateName",
"structure",
"caseDate",
"location",
"builtYear",
"totalFloors",
"floorNo",
"layout",
"decoration",
"streetFrontage",
"area",
"orientation",
"footTraffic",
"shopType",
"businessFormats",
"unitPrice",
"valueIncludes",
"remark",
"institutionName",
"photoFileIds",
}
if extra:
raise ValueError("包含商业没有的字段")
province, city, district = _region(payload.get("province"), payload.get("city"), payload.get("district"))
raw_date = str(payload.get("caseDate") or "").strip()
try:
case_date = datetime.strptime(raw_date, "%Y-%m-%d").date()
except ValueError as exc:
raise ValueError("案例时间不正确") from exc
year = _choice(str(payload.get("builtYear") or "").strip(), [str(item) for item in built_years(today)], "建筑年代")
remark = str(payload.get("remark") or "").strip()
if remark and not 1 <= len(remark) <= 1000:
raise ValueError("备注长度须在 1 到 1000")
return {
"case_type": _choice(payload.get("caseType"), CASE_TYPES, "案例类型"),
"province": province,
"city": city,
"district": district,
"estate_name": _text(payload.get("estateName"), "楼盘名称", 200),
"structure": _choice(payload.get("structure"), STRUCTURES, "建筑结构"),
"case_date": case_date,
"location": _text(payload.get("location"), "坐落", 500),
"built_year": int(year),
"total_floors": int(_choice(str(payload.get("totalFloors") or "").strip(), TOTAL_FLOORS, "总层数")),
"floor_no": _choice(str(payload.get("floorNo") or "").strip(), FLOOR_NOS, "所在层数"),
"purpose": "",
"layout_structure": "",
"decoration": _choice(payload.get("decoration"), DECORATIONS, "装修档次"),
"value_includes": _includes(payload.get("valueIncludes")),
"area": _number(payload.get("area"), "建筑面积"),
"layout": _choice(payload.get("layout"), COMMERCIAL_LAYOUTS, "户型"),
"orientation": _choice(payload.get("orientation"), ORIENTATIONS, "朝向"),
"street_frontage": _choice(payload.get("streetFrontage"), STREET_FRONTAGES, "临街状况"),
"foot_traffic": _choice(payload.get("footTraffic"), FOOT_TRAFFICS, "人流量"),
"shop_type": _choice(payload.get("shopType"), SHOP_TYPES, "商铺类型"),
"business_formats": _formats(payload.get("businessFormats")),
"unit_price": _number(payload.get("unitPrice"), "单价"),
"remark": remark,
"institution_name": _text(payload.get("institutionName"), "提交机构名称", 200),
"photo_ids": _photos(db, member_id, payload.get("photoFileIds")),
}
def _office(db, member_id: int, payload: dict, today: date | None = None) -> dict:
extra = set(payload) - {
"kind",
"caseType",
"province",
"city",
"district",
"estateName",
"structure",
"caseDate",
"location",
"builtYear",
"totalFloors",
"floorNo",
"layoutStructure",
"decoration",
"valueIncludes",
"area",
"orientation",
"unitPrice",
"remark",
"institutionName",
"photoFileIds",
}
if extra:
raise ValueError("包含办公没有的字段")
province, city, district = _region(payload.get("province"), payload.get("city"), payload.get("district"))
raw_date = str(payload.get("caseDate") or "").strip()
try:
case_date = datetime.strptime(raw_date, "%Y-%m-%d").date()
except ValueError as exc:
raise ValueError("案例时间不正确") from exc
year = _choice(str(payload.get("builtYear") or "").strip(), [str(item) for item in built_years(today)], "建筑年代")
remark = str(payload.get("remark") or "").strip()
if remark and not 1 <= len(remark) <= 1000:
raise ValueError("备注长度须在 1 到 1000")
return {
"case_type": _choice(payload.get("caseType"), CASE_TYPES, "案例类型"),
"province": province,
"city": city,
"district": district,
"estate_name": _text(payload.get("estateName"), "楼盘名称", 200),
"structure": _choice(payload.get("structure"), STRUCTURES, "建筑结构"),
"case_date": case_date,
"location": _text(payload.get("location"), "坐落", 500),
"built_year": int(year),
"total_floors": int(_choice(str(payload.get("totalFloors") or "").strip(), TOTAL_FLOORS, "总层数")),
"floor_no": _choice(str(payload.get("floorNo") or "").strip(), FLOOR_NOS, "所在层数"),
"purpose": "",
"layout_structure": _choice(payload.get("layoutStructure"), OFFICE_LAYOUT_STRUCTURES, "户型结构"),
"decoration": _choice(payload.get("decoration"), DECORATIONS, "装修档次"),
"value_includes": _includes(payload.get("valueIncludes")),
"area": _number(payload.get("area"), "建筑面积"),
"layout": "",
"orientation": _choice(payload.get("orientation"), ORIENTATIONS, "朝向"),
"unit_price": _number(payload.get("unitPrice"), "单价"),
"remark": remark,
"institution_name": _text(payload.get("institutionName"), "提交机构名称", 200),
"photo_ids": _photos(db, member_id, payload.get("photoFileIds")),
}
def _industrial(db, member_id: int, payload: dict, today: date | None = None) -> dict:
extra = set(payload) - {
"kind",
"caseType",
"province",
"city",
"district",
"estateName",
"structure",
"caseDate",
"location",
"builtYear",
"totalFloors",
"layout",
"heading",
"decoration",
"roadFrontage",
"area",
"orientation",
"industryType",
"unitPrice",
"valueIncludes",
"remark",
"institutionName",
"photoFileIds",
}
if extra:
raise ValueError("包含工业没有的字段")
province, city, district = _region(payload.get("province"), payload.get("city"), payload.get("district"))
raw_date = str(payload.get("caseDate") or "").strip()
try:
case_date = datetime.strptime(raw_date, "%Y-%m-%d").date()
except ValueError as exc:
raise ValueError("案例时间不正确") from exc
year = _choice(str(payload.get("builtYear") or "").strip(), [str(item) for item in built_years(today)], "建筑年代")
remark = str(payload.get("remark") or "").strip()
if remark and not 1 <= len(remark) <= 1000:
raise ValueError("备注长度须在 1 到 1000")
return {
"case_type": _choice(payload.get("caseType"), CASE_TYPES, "案例类型"),
"province": province,
"city": city,
"district": district,
"estate_name": _text(payload.get("estateName"), "楼盘名称", 200),
"structure": _choice(payload.get("structure"), STRUCTURES, "建筑结构"),
"case_date": case_date,
"location": _text(payload.get("location"), "坐落", 500),
"built_year": int(year),
"total_floors": int(_choice(str(payload.get("totalFloors") or "").strip(), INDUSTRIAL_FLOORS, "总层数")),
"floor_no": "",
"purpose": "",
"layout_structure": "",
"decoration": _choice(payload.get("decoration"), DECORATIONS, "装修档次"),
"value_includes": _includes(payload.get("valueIncludes"), INDUSTRIAL_VALUE_INCLUDES),
"area": _number(payload.get("area"), "建筑面积"),
"layout": _choice(payload.get("layout"), INDUSTRIAL_LAYOUTS, "户型"),
"heading": _choice(payload.get("heading"), INDUSTRIAL_DIRECTIONS, "走向"),
"road_frontage": _choice(payload.get("roadFrontage"), ROAD_FRONTAGES, "临路状况"),
"orientation": _choice(payload.get("orientation"), INDUSTRIAL_DIRECTIONS, "朝向"),
"industry_type": _choice(payload.get("industryType"), INDUSTRY_TYPES, "工业类型"),
"unit_price": _number(payload.get("unitPrice"), "单价"),
"remark": remark,
"institution_name": _text(payload.get("institutionName"), "提交机构名称", 200),
"photo_ids": _photos(db, member_id, payload.get("photoFileIds")),
}
def create_uploaded_case(db, member, payload: dict, today: date | None = None) -> UploadedCase:
if not isinstance(payload, dict):
raise ValueError("提交内容不正确")
kind = str(payload.get("kind") or "").strip()
if kind not in KIND_LABELS:
raise ValueError("案例种类不正确")
if kind not in OPEN_KINDS:
raise ValueError("该类型尚未开放")
parsers = {
"residential": _residential,
"commercial": _commercial,
"office": _office,
"industrial": _industrial,
}
fields = parsers[kind](db, member.id, payload, today)
row = UploadedCase(
kind=kind,
member_id=member.id,
member_email=member.email,
case_type=fields["case_type"],
province=fields["province"],
city=fields["city"],
district=fields["district"],
estate_name=fields["estate_name"],
structure=fields["structure"],
case_date=fields["case_date"],
location=fields["location"],
built_year=fields["built_year"],
total_floors=fields["total_floors"],
floor_no=fields["floor_no"],
purpose=fields["purpose"],
layout_structure=fields["layout_structure"],
decoration=fields["decoration"],
value_includes=json.dumps(fields["value_includes"], ensure_ascii=False),
area=fields["area"],
layout=fields["layout"],
orientation=fields["orientation"],
unit_price=fields["unit_price"],
remark=fields["remark"],
institution_name=fields["institution_name"],
street_frontage=fields.get("street_frontage", ""),
foot_traffic=fields.get("foot_traffic", ""),
shop_type=fields.get("shop_type", ""),
business_formats=json.dumps(fields.get("business_formats", []), ensure_ascii=False),
heading=fields.get("heading", ""),
road_frontage=fields.get("road_frontage", ""),
industry_type=fields.get("industry_type", ""),
created_at=_now(),
)
db.add(row)
db.flush()
for index, file_id in enumerate(fields["photo_ids"]):
db.add(UploadedCasePhoto(case_id=row.id, file_id=file_id, position=index))
db.commit()
db.refresh(row)
return row
def _address(row: UploadedCase) -> str:
return f"{row.province} {row.city} {row.district}"
def _list_item(row: UploadedCase) -> dict:
return {
"id": row.id,
"kind": row.kind,
"kindLabel": KIND_LABELS.get(row.kind, row.kind),
"estateName": row.estate_name,
"address": _address(row),
"caseDate": row.case_date.isoformat() if row.case_date else "",
"institutionName": row.institution_name,
"memberEmail": row.member_email,
"createdAt": row.created_at.isoformat(timespec="seconds") if row.created_at else "",
}
def _photos_payload(db, case_id: int) -> list[dict]:
from app.models.content import AdminFile
from app.services.storage import private_object_url
links = db.scalars(
select(UploadedCasePhoto)
.where(UploadedCasePhoto.case_id == case_id)
.order_by(UploadedCasePhoto.position.asc(), UploadedCasePhoto.id.asc())
).all()
items = []
for link in links:
file_row = db.get(AdminFile, link.file_id)
if file_row is None or file_row.bucket != "private":
continue
url, expires_at = private_object_url(file_row.object_key)
items.append(
{
"id": file_row.id,
"filename": file_row.filename,
"contentType": file_row.content_type or "",
"url": url,
"expiresAt": expires_at.isoformat(),
}
)
return items
def _like_contains(value: str) -> str:
escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
return f"%{escaped}%"
def list_uploaded_cases(db, *, kind: str, current: int, size: int, q: str | None = None) -> dict | None:
if kind not in KIND_LABELS:
return None
page_size = size if size in PAGE_SIZES else 10
page = current if current >= 1 else 1
filters = [UploadedCase.kind == kind]
keyword = (q or "").strip()[:100]
if keyword:
needle = _like_contains(keyword)
filters.append(
or_(
UploadedCase.estate_name.like(needle, escape="\\"),
UploadedCase.province.like(needle, escape="\\"),
UploadedCase.city.like(needle, escape="\\"),
UploadedCase.district.like(needle, escape="\\"),
UploadedCase.institution_name.like(needle, escape="\\"),
UploadedCase.member_email.like(needle, escape="\\"),
)
)
total = len(db.scalars(select(UploadedCase.id).where(*filters)).all())
rows = db.scalars(
select(UploadedCase)
.where(*filters)
.order_by(UploadedCase.created_at.desc(), UploadedCase.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
).all()
return {
"kind": kind,
"kindLabel": KIND_LABELS[kind],
"items": [_list_item(row) for row in rows],
"total": total,
"current": page,
"size": page_size,
}
def uploaded_case_detail(db, case_id: int) -> dict | None:
row = db.get(UploadedCase, case_id)
if row is None:
return None
body = _list_item(row)
body.update(
{
"caseType": row.case_type,
"province": row.province,
"city": row.city,
"district": row.district,
"structure": row.structure,
"location": row.location,
"builtYear": row.built_year,
"totalFloors": row.total_floors,
"decoration": row.decoration,
"valueIncludes": json.loads(row.value_includes or "[]"),
"area": row.area,
"orientation": row.orientation,
"unitPrice": row.unit_price,
"remark": row.remark,
"photos": _photos_payload(db, row.id),
}
)
if row.kind != "industrial":
body["floorNo"] = row.floor_no
if row.kind in ("residential", "commercial", "industrial"):
body["layout"] = row.layout
if row.kind == "residential":
body["purpose"] = row.purpose
body["layoutStructure"] = row.layout_structure
if row.kind == "office":
body["layoutStructure"] = row.layout_structure
if row.kind == "commercial":
body["streetFrontage"] = row.street_frontage
body["footTraffic"] = row.foot_traffic
body["shopType"] = row.shop_type
body["businessFormats"] = json.loads(row.business_formats or "[]")
if row.kind == "industrial":
body["heading"] = row.heading
body["roadFrontage"] = row.road_frontage
body["industryType"] = row.industry_type
return body
View File
Whitespace-only changes.
+91
View File
@@ -0,0 +1,91 @@
import logging
from sqlalchemy import select
from app.core.config import get_settings
logger = logging.getLogger("gsfdc.audit")
def write_audit(
*,
user_id: int | None,
username: str | None,
method: str,
path: str,
status_code: int,
ip: str,
) -> None:
clean_path = (path or "").split("?", 1)[0][:255]
if not (get_settings().database_url or "").strip():
return
try:
from app.db import SessionLocal
from app.models.security import AdminAuditLog
db = SessionLocal()
try:
db.add(
AdminAuditLog(
user_id=user_id,
username=None if username is None else username[:64],
method=(method or "")[:16],
path=clean_path,
status_code=status_code,
ip=(ip or "")[:64],
)
)
db.commit()
finally:
db.close()
except Exception as exc:
logger.warning("admin audit log write failed: %s", type(exc).__name__)
def _staff_from_header(request) -> tuple[int | None, str | None]:
hinted = getattr(request.state, "audit_username", None)
username = hinted.strip()[:64] if isinstance(hinted, str) and hinted.strip() else None
user_id = None
header = request.headers.get("authorization", "")
if header.lower().startswith("bearer "):
token = header.split(" ", 1)[1].strip()
try:
from app.core.security import decode_access_token
payload = decode_access_token(token, "staff")
subject = str(payload.get("sub") or "")
if subject.isdigit():
user_id = int(subject)
except Exception:
user_id = None
if user_id is not None and username is None and (get_settings().database_url or "").strip():
try:
from app.db import SessionLocal
from app.models.rbac import AdminUser
db = SessionLocal()
try:
found = db.scalar(select(AdminUser.username).where(AdminUser.id == user_id))
finally:
db.close()
if isinstance(found, str) and found.strip():
username = found.strip()[:64]
except Exception:
pass
return user_id, username
def record_admin_call(request, status_code: int) -> None:
path = request.url.path
if not path.startswith("/api/admin"):
return
user_id, username = _staff_from_header(request)
client = request.client.host if request.client else ""
write_audit(
user_id=user_id,
username=username,
method=request.method,
path=path,
status_code=status_code,
ip=client,
)
+67
View File
@@ -0,0 +1,67 @@
import base64
import io
import secrets
from PIL import Image, ImageDraw, ImageFont
from app.services.redis_client import get_redis
CAPTCHA_TTL_SEC = 120
CAPTCHA_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
def _key(captcha_id: str) -> str:
return f"gsfdc:captcha:{captcha_id}"
def _new_code() -> str:
return "".join(secrets.choice(CAPTCHA_ALPHABET) for _ in range(4))
def _image(code: str) -> str:
width, height = 132, 48
image = Image.new("RGB", (width, height), (246, 248, 251))
draw = ImageDraw.Draw(image)
font = ImageFont.load_default(size=26)
for _ in range(5):
draw.line(
(
secrets.randbelow(width),
secrets.randbelow(height),
secrets.randbelow(width),
secrets.randbelow(height),
),
fill=(180, 190, 200),
width=1,
)
for index, char in enumerate(code):
color = (secrets.randbelow(80), secrets.randbelow(80), 40 + secrets.randbelow(80))
draw.text((12 + index * 30, 8 + secrets.randbelow(8)), char, font=font, fill=color)
buffer = io.BytesIO()
image.save(buffer, format="PNG")
encoded = base64.b64encode(buffer.getvalue()).decode("ascii")
return f"data:image/png;base64,{encoded}"
def issue_captcha() -> dict:
captcha_id = secrets.token_hex(16)
code = _new_code()
get_redis().set(_key(captcha_id), code.lower(), ex=CAPTCHA_TTL_SEC)
return {"captchaId": captcha_id, "image": _image(code)}
def consume_captcha(captcha_id: str, code: str) -> bool:
if not isinstance(captcha_id, str) or not isinstance(code, str):
return False
captcha_id = captcha_id.strip()
code = code.strip()
if not captcha_id or not code:
return False
stored = get_redis().getdel(_key(captcha_id))
if stored is None:
return False
if isinstance(stored, bytes):
stored = stored.decode("utf-8", errors="replace")
if not isinstance(stored, str):
return False
return stored.lower() == code.lower()
+79
View File
@@ -0,0 +1,79 @@
import re
import secrets
import string
from app.services.mailer import send_email
from app.services.redis_client import get_redis
EMAIL_CODE_TTL_SEC = 600
EMAIL_CODE_PURPOSES = ("register", "login", "reset")
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
def normalize_email(email: str) -> str:
return (email or "").strip().lower()
def is_valid_email(email: str) -> bool:
text = normalize_email(email)
return bool(text) and len(text) <= 191 and _EMAIL_RE.match(text) is not None
def _key(purpose: str, email: str) -> str:
return f"gsfdc:email_code:{purpose}:{normalize_email(email)}"
def _rate_key(purpose: str, email: str) -> str:
return f"gsfdc:email_code_rate:{purpose}:{normalize_email(email)}"
def _new_code() -> str:
return "".join(secrets.choice(string.digits) for _ in range(6))
def issue_email_code(*, email: str, purpose: str) -> None:
if purpose not in EMAIL_CODE_PURPOSES:
raise ValueError("验证码用途不正确")
if not is_valid_email(email):
raise ValueError("邮箱格式不正确")
normalized = normalize_email(email)
redis = get_redis()
if redis.get(_rate_key(purpose, normalized)):
raise ValueError("发送过于频繁,请稍后再试")
code = _new_code()
redis.set(_key(purpose, normalized), code, ex=EMAIL_CODE_TTL_SEC)
redis.set(_rate_key(purpose, normalized), "1", ex=60)
labels = {"register": "注册", "login": "登录", "reset": "重置密码"}
subject = f"甘肃省房地产价格评估行业协会 · {labels[purpose]}验证码"
body = (
f"您的{labels[purpose]}验证码是:{code}\n"
f"有效期 {EMAIL_CODE_TTL_SEC // 60} 分钟。如非本人操作请忽略本邮件。\n"
)
try:
send_email(to=normalized, subject=subject, body=body)
except Exception:
# 发信失败时仍保留验证码,便于本地/测试校验路径;生产日志可见失败。
import logging
logging.getLogger("gsfdc.email_code").exception("邮箱验证码发信失败")
def consume_email_code(*, email: str, purpose: str, code: str) -> bool:
if purpose not in EMAIL_CODE_PURPOSES:
return False
if not is_valid_email(email) or not isinstance(code, str):
return False
normalized = normalize_email(email)
text = code.strip()
if not text:
return False
# 仅在码匹配时删除;输错不消耗,避免一次错码废掉仍有效的验证码。
redis = get_redis()
key = _key(purpose, normalized)
deleted = redis.eval(
"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",
1,
key,
text,
)
return bool(deleted)
+120
View File
@@ -0,0 +1,120 @@
from html import escape, unescape
from html.parser import HTMLParser
from sqlalchemy import select
from app.core.config import get_settings
ALLOWED = {
"p", "br", "strong", "b", "em", "i", "u", "s",
"ul", "ol", "li", "blockquote",
"h1", "h2", "h3", "h4", "h5", "h6",
"span", "div",
"table", "thead", "tbody", "tr", "td", "th",
"a", "img", "video", "source",
"pre", "code", "hr", "sub", "sup",
}
VOID = {"br", "img", "hr", "source"}
CONTENT_DROP = {"script", "style", "iframe", "object", "embed"}
VOID_DROP = {"link", "meta"}
ALLOWED_ATTRS = {
"href", "src", "alt", "title", "width", "height",
"controls", "colspan", "rowspan", "class",
}
MEDIA_SRC = {"img", "video", "source"}
def is_javascript_url(value: str) -> bool:
if not value:
return False
compact = "".join(ch for ch in unescape(value).lower() if not ch.isspace() and ord(ch) >= 32)
return compact.startswith("javascript:")
def _src_allowed(url: str, keys: list[str], base: str) -> bool:
if not url or is_javascript_url(url):
return False
path = unescape(url.split("#", 1)[0].split("?", 1)[0])
for key in keys:
if not key:
continue
if key in url or key in path:
return True
if base and url.startswith(base):
suffix = key if key.startswith("/") else f"/{key}"
if path.endswith(suffix):
return True
return False
class _Cleaner(HTMLParser):
def __init__(self, object_keys: list[str], base_url: str) -> None:
super().__init__(convert_charrefs=True)
self._keys = [key for key in object_keys if key]
self._base = (base_url or "").strip().rstrip("/")
self._parts: list[str] = []
self._drop = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
name = tag.lower()
if name in CONTENT_DROP:
self._drop += 1
return
if self._drop or name in VOID_DROP or name not in ALLOWED:
return
self._parts.append(f"<{name}{self._attrs(name, attrs)}>")
def handle_endtag(self, tag: str) -> None:
name = tag.lower()
if name in CONTENT_DROP:
if self._drop:
self._drop -= 1
return
if self._drop or name not in ALLOWED or name in VOID:
return
self._parts.append(f"</{name}>")
def handle_data(self, data: str) -> None:
if self._drop or not data:
return
self._parts.append(escape(data.replace("\x00", ""), quote=False))
def result(self) -> str:
return "".join(self._parts)
def _attrs(self, tag: str, attrs: list[tuple[str, str | None]]) -> str:
chunks: list[str] = []
seen: set[str] = set()
for raw_name, raw_value in attrs:
name = raw_name.lower()
if name in seen or name not in ALLOWED_ATTRS or name.startswith("on"):
continue
value = "" if raw_value is None else str(raw_value)
if name in {"href", "src"} and (not value.strip() or is_javascript_url(value)):
continue
if tag in MEDIA_SRC and name == "src" and not _src_allowed(value, self._keys, self._base):
continue
seen.add(name)
if name == "controls":
chunks.append(" controls")
continue
chunks.append(f' {name}="{escape(value, quote=True)}"')
return "".join(chunks)
def filter_html(html: str, object_keys: list[str], base_url: str) -> str:
cleaner = _Cleaner(object_keys, base_url)
cleaner.feed(html or "")
cleaner.close()
return cleaner.result()
def preview_filter(html: str, db) -> dict:
from app.models.content import AdminFile, SensitiveWord
text = html or ""
keys = list(db.scalars(select(AdminFile.object_key).where(AdminFile.bucket == "public")))
words = db.scalars(select(SensitiveWord).order_by(SensitiveWord.id.asc())).all()
hits = [row.word for row in words if row.word and row.word in text]
cleaned = filter_html(text, list(keys), get_settings().minio_base_url)
return {"html": cleaned, "hits": hits}
+57
View File
@@ -0,0 +1,57 @@
import logging
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.core.config import get_settings
logger = logging.getLogger("gsfdc.ip")
def _blocked_by_env(ip: str) -> bool:
return ip in get_settings().blocked_ips
def is_ip_blocked(ip: str) -> bool:
if not (get_settings().database_url or "").strip():
return _blocked_by_env(ip)
try:
from app.db import SessionLocal
from app.models.security import AdminIpBlacklist
db = SessionLocal()
try:
found = db.scalar(select(AdminIpBlacklist.id).where(AdminIpBlacklist.ip == ip))
finally:
db.close()
return found is not None
except Exception as exc:
logger.warning("admin ip blacklist lookup failed: %s", type(exc).__name__)
return _blocked_by_env(ip)
def seed_ip_blacklist(db: Session) -> None:
from app.models.security import AdminIpBlacklist
wanted = set(get_settings().blocked_ips)
if not wanted:
return
existing = set(db.scalars(select(AdminIpBlacklist.ip)).all())
pending = [ip for ip in wanted if ip not in existing]
if not pending:
return
for ip in pending:
db.add(AdminIpBlacklist(ip=ip, remark=""))
try:
db.commit()
except IntegrityError:
db.rollback()
for ip in pending:
if db.scalar(select(AdminIpBlacklist.id).where(AdminIpBlacklist.ip == ip)) is not None:
continue
db.add(AdminIpBlacklist(ip=ip, remark=""))
try:
db.commit()
except IntegrityError:
db.rollback()
+81
View File
@@ -0,0 +1,81 @@
from datetime import datetime, timedelta, timezone
from typing import Any
from sqlalchemy import select
from sqlalchemy.orm import Session
LOGIN_MAX_FAILURES_KEY = "login_max_failures"
LOGIN_LOCK_MINUTES_KEY = "login_lock_minutes"
# 仅在 site_setting 缺少对应行时使用。运行时以数据库为准。
_DEFAULT_MAX_FAILURES = 5
_DEFAULT_LOCK_MINUTES = 15
def _now() -> datetime:
return datetime.now(timezone.utc)
def _as_utc(value: datetime) -> datetime:
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def _naive_utc(value: datetime) -> datetime:
return _as_utc(value).replace(tzinfo=None)
def is_currently_locked(user: Any) -> bool:
locked_until = getattr(user, "locked_until", None)
if not isinstance(locked_until, datetime):
return False
return _as_utc(locked_until) > _now()
def _stored_int(found: dict[str, Any], key: str, fallback: int) -> int:
if key not in found:
return fallback
raw = found[key]
if raw is None:
return fallback
text = str(raw).strip()
if not text:
return fallback
try:
return int(text)
except ValueError:
return fallback
def read_login_policy(db: Session) -> tuple[int, int]:
from app.models.content import SiteSetting
rows = db.scalars(
select(SiteSetting).where(SiteSetting.key.in_((LOGIN_MAX_FAILURES_KEY, LOGIN_LOCK_MINUTES_KEY)))
).all()
found = {row.key: row.value for row in rows}
return (
_stored_int(found, LOGIN_MAX_FAILURES_KEY, _DEFAULT_MAX_FAILURES),
_stored_int(found, LOGIN_LOCK_MINUTES_KEY, _DEFAULT_LOCK_MINUTES),
)
def record_failure(db: Session, user: Any) -> None:
max_failures, lock_minutes = read_login_policy(db)
count = int(getattr(user, "failed_login_count", 0) or 0) + 1
if count >= max_failures:
user.failed_login_count = 0
user.locked_until = _naive_utc(_now() + timedelta(minutes=lock_minutes))
else:
user.failed_login_count = count
db.add(user)
db.commit()
db.refresh(user)
def clear_failures(db: Session, user: Any) -> None:
user.failed_login_count = 0
user.locked_until = None
db.add(user)
db.commit()
db.refresh(user)
+33
View File
@@ -0,0 +1,33 @@
import logging
import smtplib
from email.message import EmailMessage
from app.core.config import get_settings
logger = logging.getLogger("gsfdc.mailer")
def send_email(*, to: str, subject: str, body: str) -> None:
settings = get_settings()
host = settings.smtp_host.strip()
if not host:
raise RuntimeError("SMTP 未配置")
sender = (settings.smtp_sender or settings.smtp_user).strip()
if not sender:
raise RuntimeError("SMTP 发件人未配置")
message = EmailMessage()
message["From"] = sender
message["To"] = to
message["Subject"] = subject
message.set_content(body)
if settings.smtp_use_ssl:
with smtplib.SMTP_SSL(host, settings.smtp_port, timeout=20) as smtp:
if settings.smtp_user.strip():
smtp.login(settings.smtp_user.strip(), settings.smtp_password)
smtp.send_message(message)
return
with smtplib.SMTP(host, settings.smtp_port, timeout=20) as smtp:
smtp.starttls()
if settings.smtp_user.strip():
smtp.login(settings.smtp_user.strip(), settings.smtp_password)
smtp.send_message(message)
+31
View File
@@ -0,0 +1,31 @@
import bcrypt
from fastapi import HTTPException, status
PASSWORD_RULE = "密码至少 8 位,且同时包含字母和数字"
def validate_password(password: str) -> None:
if (
not isinstance(password, str)
or len(password) < 8
or not any(char.isalpha() for char in password)
or not any(char.isdigit() for char in password)
):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=PASSWORD_RULE)
def hash_password(password: str) -> str:
try:
hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())
except ValueError:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="密码过长")
return hashed.decode("utf-8")
def verify_password(password: str, password_hash: str) -> bool:
if not password or not password_hash:
return False
try:
return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8"))
except (ValueError, TypeError):
return False
+685
View File
@@ -0,0 +1,685 @@
from collections.abc import Callable
from datetime import datetime, timezone
from typing import NoReturn
from fastapi import HTTPException, status
from sqlalchemy import delete, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.core.field_crypto import encrypt_text
from app.core.masking import mask_mobile
from app.core.security import create_access_token
from app.models.rbac import (
AdminResource,
AdminRole,
AdminRoleResource,
AdminUser,
AdminUserRole,
utcnow,
)
from app.services.captcha import consume_captcha
from app.services.login_guard import clear_failures, is_currently_locked, record_failure
from app.services.password import hash_password, validate_password, verify_password
LOGIN_FAILURE = "用户名或密码错误"
KEEP_FULL_ADMIN = "至少保留一名拥有全部系统菜单的正常用户"
KEEP_SELF = "不能停用或注销当前登录用户"
USER_STATUSES = {"active", "disabled", "cancelled"}
ROLE_STATUSES = {"active", "disabled"}
RESOURCE_STATUSES = {"active", "disabled"}
RESOURCE_TYPES = {"directory", "menu", "button"}
MENU_TYPES = {"directory", "menu"}
def isoformat(value: datetime | None) -> str | None:
if value is None:
return None
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.isoformat()
def _bad(detail: str, code: int = status.HTTP_400_BAD_REQUEST) -> NoReturn:
raise HTTPException(status_code=code, detail=detail)
def _require_text(value: str | None, *, empty: str, limit: int, too_long: str) -> str:
text = (value or "").strip()
if not text:
_bad(empty)
if len(text) > limit:
_bad(too_long)
return text
def _optional_text(value: str | None, limit: int, too_long: str) -> str | None:
if value is None:
return None
text = value.strip()
if not text:
return None
if len(text) > limit:
_bad(too_long)
return text
def _clean(value: str | None, limit: int, too_long: str) -> str:
text = (value or "").strip()
if len(text) > limit:
_bad(too_long)
return text
def _exact(value: str | None) -> str | None:
if value is None:
return None
text = value.strip()
return text or None
def _page(current: int, size: int) -> tuple[int, int]:
if current < 1:
current = 1
if size < 1:
size = 10
if size > 200:
size = 200
return current, size
def commit_or_raise(db: Session, message: str) -> None:
try:
db.commit()
except IntegrityError:
db.rollback()
_bad(message)
def preserve_full_admin(db: Session, mutate: Callable[[], None]) -> None:
before = count_full_admins(db)
with db.begin_nested():
mutate()
db.flush()
if before >= 1 and count_full_admins(db) < 1:
_bad(KEEP_FULL_ADMIN)
def count_full_admins(db: Session) -> int:
needed = set(db.scalars(select(AdminResource.id).where(AdminResource.status == "active")).all())
user_ids = db.scalars(select(AdminUser.id).where(AdminUser.status == "active")).all()
total = 0
for user_id in user_ids:
if needed <= owned_resource_ids(db, user_id):
total += 1
return total
def owned_resource_ids(db: Session, user_id: int) -> set[int]:
rows = db.scalars(
select(AdminRoleResource.resource_id)
.join(AdminRole, AdminRole.id == AdminRoleResource.role_id)
.join(AdminUserRole, AdminUserRole.role_id == AdminRole.id)
.where(AdminUserRole.user_id == user_id, AdminRole.status == "active")
).all()
return set(rows)
def apply_mobile(user: AdminUser, mobile: str) -> None:
text = mobile.strip()
if len(text) > 20:
_bad("手机号过长")
if not text:
user.mobile_cipher = None
user.mobile_mask = ""
return
user.mobile_cipher = encrypt_text(text)
user.mobile_mask = mask_mobile(text)
def ensure_role_ids(db: Session, role_ids: list[int]) -> list[int]:
unique = list(dict.fromkeys(role_ids))
if not unique:
return []
found = set(db.scalars(select(AdminRole.id).where(AdminRole.id.in_(unique))).all())
if found != set(unique):
_bad("角色不存在")
return unique
def ensure_resource_ids(db: Session, resource_ids: list[int]) -> list[int]:
unique = list(dict.fromkeys(resource_ids))
if not unique:
return []
found = set(db.scalars(select(AdminResource.id).where(AdminResource.id.in_(unique))).all())
if found != set(unique):
_bad("资源不存在")
return unique
def replace_user_roles(db: Session, user_id: int, role_ids: list[int]) -> None:
db.execute(delete(AdminUserRole).where(AdminUserRole.user_id == user_id))
for role_id in role_ids:
db.add(AdminUserRole(user_id=user_id, role_id=role_id))
def replace_role_links(db: Session, role_id: int, resource_ids: list[int]) -> None:
db.execute(delete(AdminRoleResource).where(AdminRoleResource.role_id == role_id))
for resource_id in resource_ids:
db.add(AdminRoleResource(role_id=role_id, resource_id=resource_id))
def _role_map(db: Session, user_ids: list[int]) -> dict[int, list[AdminRole]]:
grouped: dict[int, list[AdminRole]] = {user_id: [] for user_id in user_ids}
if not user_ids:
return grouped
rows = db.execute(
select(AdminUserRole.user_id, AdminRole)
.join(AdminRole, AdminRole.id == AdminUserRole.role_id)
.where(AdminUserRole.user_id.in_(user_ids))
.order_by(AdminRole.id)
).all()
for user_id, role in rows:
grouped.setdefault(user_id, []).append(role)
return grouped
def _resource_id_map(db: Session, role_ids: list[int]) -> dict[int, list[int]]:
grouped: dict[int, list[int]] = {role_id: [] for role_id in role_ids}
if not role_ids:
return grouped
rows = db.execute(
select(AdminRoleResource.role_id, AdminRoleResource.resource_id)
.where(AdminRoleResource.role_id.in_(role_ids))
.order_by(AdminRoleResource.resource_id)
).all()
for role_id, resource_id in rows:
grouped.setdefault(role_id, []).append(resource_id)
return grouped
def serialize_login_user(user: AdminUser) -> dict:
return {
"id": user.id,
"username": user.username,
"displayName": user.display_name,
"mobileMask": user.mobile_mask or "",
"status": user.status,
}
def serialize_user(user: AdminUser, roles: list[AdminRole]) -> dict:
return {
"id": user.id,
"username": user.username,
"displayName": user.display_name,
"mobileMask": user.mobile_mask or "",
"status": user.status,
"roleIds": [role.id for role in roles],
"roles": [{"id": role.id, "code": role.code, "name": role.name} for role in roles],
"createdAt": isoformat(user.created_at),
"updatedAt": isoformat(user.updated_at),
}
def serialize_role(role: AdminRole, resource_ids: list[int]) -> dict:
return {
"id": role.id,
"code": role.code,
"name": role.name,
"description": role.description,
"status": role.status,
"resourceIds": resource_ids,
"createdAt": isoformat(role.created_at),
"updatedAt": isoformat(role.updated_at),
}
def serialize_node(resource: AdminResource, children: list[dict]) -> dict:
return {
"id": resource.id,
"parentId": resource.parent_id,
"type": resource.type,
"name": resource.name,
"title": resource.title,
"path": resource.path or "",
"component": resource.component or "",
"icon": resource.icon or "",
"permission": resource.permission or "",
"sort": resource.sort,
"visible": bool(resource.visible),
"status": resource.status,
"children": children,
}
def build_tree(resources: list[AdminResource]) -> list[dict]:
known = {item.id for item in resources}
grouped: dict[int | None, list[AdminResource]] = {}
for item in resources:
parent_id = item.parent_id if item.parent_id in known else None
grouped.setdefault(parent_id, []).append(item)
for nodes in grouped.values():
nodes.sort(key=lambda node: (node.sort, node.id))
def walk(node: AdminResource) -> dict:
children = [walk(child) for child in grouped.get(node.id, [])]
return serialize_node(node, children)
return [walk(node) for node in grouped.get(None, [])]
def sibling_name_taken(db: Session, parent_id: int | None, name: str, exclude_id: int | None = None) -> bool:
stmt = select(AdminResource.id).where(AdminResource.name == name)
if parent_id is None:
stmt = stmt.where(AdminResource.parent_id.is_(None))
else:
stmt = stmt.where(AdminResource.parent_id == parent_id)
if exclude_id is not None:
stmt = stmt.where(AdminResource.id != exclude_id)
return db.scalar(stmt) is not None
def assert_parent(db: Session, resource_id: int | None, parent_id: int | None) -> None:
if parent_id is None:
return
if resource_id is not None and parent_id == resource_id:
_bad("不能把资源移动到自己的下级")
seen: set[int] = set()
current: int | None = parent_id
while current is not None:
if current in seen:
break
if resource_id is not None and current == resource_id:
_bad("不能把资源移动到自己的下级")
seen.add(current)
parent = db.get(AdminResource, current)
if parent is None:
_bad("上级资源不存在")
current = parent.parent_id
def granted_resources(db: Session, user_id: int) -> list[AdminResource]:
stmt = select(AdminResource).where(
AdminResource.status == "active",
AdminResource.id.in_(
select(AdminRoleResource.resource_id)
.join(AdminRole, AdminRole.id == AdminRoleResource.role_id)
.join(AdminUserRole, AdminUserRole.role_id == AdminRole.id)
.where(AdminUserRole.user_id == user_id, AdminRole.status == "active")
),
)
return list(db.scalars(stmt).all())
def menus_and_permissions(db: Session, user: AdminUser) -> tuple[list[dict], list[str]]:
resources = granted_resources(db, user.id)
menus = build_tree([item for item in resources if item.type in MENU_TYPES])
permissions = sorted({item.permission for item in resources if item.type == "button" and item.permission})
return menus, permissions
def _reject_login(db: Session, user: AdminUser | None, *, record: bool) -> NoReturn:
if record and user is not None:
record_failure(db, user)
db.commit()
_bad(LOGIN_FAILURE, status.HTTP_401_UNAUTHORIZED)
def authenticate(db: Session, username: str, password: str, captcha_id: str, captcha_code: str) -> dict:
captcha_ok = consume_captcha(captcha_id, captcha_code)
user = db.scalar(select(AdminUser).where(AdminUser.username == (username or "").strip()))
if user is None:
_reject_login(db, None, record=False)
if is_currently_locked(user):
_reject_login(db, user, record=False)
if not captcha_ok:
_reject_login(db, user, record=True)
if not verify_password(password, user.password_hash):
_reject_login(db, user, record=True)
if user.status != "active":
_reject_login(db, user, record=True)
clear_failures(db, user)
token = create_access_token(str(user.id), "staff")
menus, permissions = menus_and_permissions(db, user)
db.commit()
return {
"token": token,
"user": serialize_login_user(user),
"menus": menus,
"permissions": permissions,
}
def change_own_password(db: Session, user_id: int, old_password: str, new_password: str) -> dict:
user = db.get(AdminUser, user_id)
if user is None:
_bad("登录已失效", status.HTTP_401_UNAUTHORIZED)
if not verify_password(old_password, user.password_hash):
_bad("旧密码错误")
validate_password(new_password)
user.password_hash = hash_password(new_password)
user.updated_at = utcnow()
commit_or_raise(db, "保存密码失败")
return {"ok": True}
def query_users(
db: Session,
*,
current: int,
size: int,
username: str | None,
display_name: str | None,
status_value: str | None,
) -> dict:
current, size = _page(current, size)
filters = []
username_text = _exact(username)
display_text = _exact(display_name)
status_text = _exact(status_value)
if username_text:
filters.append(AdminUser.username.contains(username_text))
if display_text:
filters.append(AdminUser.display_name.contains(display_text))
if status_text:
filters.append(AdminUser.status == status_text)
total = db.scalar(select(func.count()).select_from(AdminUser).where(*filters)) or 0
rows = db.scalars(
select(AdminUser).where(*filters).order_by(AdminUser.id.desc()).offset((current - 1) * size).limit(size)
).all()
role_map = _role_map(db, [row.id for row in rows])
return {
"records": [serialize_user(row, role_map.get(row.id, [])) for row in rows],
"current": current,
"size": size,
"total": total,
}
def create_user(
db: Session,
*,
username: str,
password: str,
display_name: str,
mobile: str | None,
role_ids: list[int],
) -> dict:
username_text = _require_text(username, empty="请填写用户名", limit=64, too_long="用户名过长")
display_text = _require_text(display_name, empty="请填写姓名", limit=64, too_long="姓名过长")
validate_password(password)
checked_roles = ensure_role_ids(db, role_ids)
if db.scalar(select(AdminUser.id).where(AdminUser.username == username_text)):
_bad("用户名已存在")
now = utcnow()
user = AdminUser(
username=username_text,
password_hash=hash_password(password),
display_name=display_text,
mobile_mask="",
status="active",
failed_login_count=0,
created_at=now,
updated_at=now,
)
if mobile:
apply_mobile(user, mobile)
db.add(user)
try:
db.flush()
except IntegrityError:
db.rollback()
_bad("用户名已存在")
replace_user_roles(db, user.id, checked_roles)
commit_or_raise(db, "用户名已存在")
roles = _role_map(db, [user.id]).get(user.id, [])
return serialize_user(user, roles)
def update_user(
db: Session,
user_id: int,
actor_id: int,
*,
display_name: str,
status_value: str,
role_ids: list[int],
mobile: str | None,
mobile_provided: bool,
) -> dict:
user = db.get(AdminUser, user_id)
if user is None:
_bad("用户不存在", status.HTTP_404_NOT_FOUND)
display_text = _require_text(display_name, empty="请填写姓名", limit=64, too_long="姓名过长")
if status_value not in USER_STATUSES:
_bad("用户状态不正确")
if status_value in {"disabled", "cancelled"} and user.id == actor_id:
_bad(KEEP_SELF)
checked_roles = ensure_role_ids(db, role_ids)
normalized_mobile = mobile
if mobile_provided and mobile is not None:
text = mobile.strip()
if len(text) > 20:
_bad("手机号过长")
normalized_mobile = text
def mutate() -> None:
user.display_name = display_text
user.status = status_value
if mobile_provided and normalized_mobile is not None:
apply_mobile(user, normalized_mobile)
replace_user_roles(db, user.id, checked_roles)
user.updated_at = utcnow()
preserve_full_admin(db, mutate)
commit_or_raise(db, "保存用户失败")
roles = _role_map(db, [user.id]).get(user.id, [])
return serialize_user(user, roles)
def reset_user_password(db: Session, user_id: int, password: str) -> dict:
user = db.get(AdminUser, user_id)
if user is None:
_bad("用户不存在", status.HTTP_404_NOT_FOUND)
validate_password(password)
user.password_hash = hash_password(password)
user.updated_at = utcnow()
commit_or_raise(db, "保存密码失败")
return {"ok": True}
def query_roles(
db: Session,
*,
current: int,
size: int,
name: str | None,
code: str | None,
status_value: str | None,
) -> dict:
current, size = _page(current, size)
filters = []
name_text = _exact(name)
code_text = _exact(code)
status_text = _exact(status_value)
if name_text:
filters.append(AdminRole.name.contains(name_text))
if code_text:
filters.append(AdminRole.code.contains(code_text))
if status_text:
filters.append(AdminRole.status == status_text)
total = db.scalar(select(func.count()).select_from(AdminRole).where(*filters)) or 0
rows = db.scalars(
select(AdminRole).where(*filters).order_by(AdminRole.id.desc()).offset((current - 1) * size).limit(size)
).all()
resource_map = _resource_id_map(db, [row.id for row in rows])
return {
"records": [serialize_role(row, resource_map.get(row.id, [])) for row in rows],
"current": current,
"size": size,
"total": total,
}
def create_role(db: Session, *, code: str, name: str, description: str | None) -> dict:
code_text = _require_text(code, empty="请填写角色编码", limit=64, too_long="角色编码过长")
name_text = _require_text(name, empty="请填写角色名称", limit=64, too_long="角色名称过长")
description_text = _optional_text(description, 2000, "说明过长")
if db.scalar(select(AdminRole.id).where(AdminRole.code == code_text)):
_bad("角色编码已存在")
now = utcnow()
role = AdminRole(
code=code_text,
name=name_text,
description=description_text,
status="active",
created_at=now,
updated_at=now,
)
db.add(role)
commit_or_raise(db, "角色编码已存在")
return serialize_role(role, [])
def update_role(
db: Session,
role_id: int,
*,
name: str,
description: str | None,
status_value: str,
) -> dict:
role = db.get(AdminRole, role_id)
if role is None:
_bad("角色不存在", status.HTTP_404_NOT_FOUND)
name_text = _require_text(name, empty="请填写角色名称", limit=64, too_long="角色名称过长")
description_text = _optional_text(description, 2000, "说明过长")
if status_value not in ROLE_STATUSES:
_bad("角色状态不正确")
def mutate() -> None:
role.name = name_text
role.description = description_text
role.status = status_value
role.updated_at = utcnow()
preserve_full_admin(db, mutate)
commit_or_raise(db, "保存角色失败")
resource_ids = _resource_id_map(db, [role.id]).get(role.id, [])
return serialize_role(role, resource_ids)
def replace_role_resources(db: Session, role_id: int, resource_ids: list[int]) -> dict:
role = db.get(AdminRole, role_id)
if role is None:
_bad("角色不存在", status.HTTP_404_NOT_FOUND)
checked = ensure_resource_ids(db, resource_ids)
def mutate() -> None:
replace_role_links(db, role.id, checked)
role.updated_at = utcnow()
preserve_full_admin(db, mutate)
commit_or_raise(db, "保存角色资源失败")
return {"ok": True}
def list_resources(db: Session) -> list[dict]:
rows = list(db.scalars(select(AdminResource)).all())
return build_tree(rows)
def _resource_fields(
*,
resource_type: str,
name: str,
title: str,
path: str | None,
component: str | None,
icon: str | None,
permission: str | None,
sort: int,
visible: bool,
status_value: str,
) -> dict:
if resource_type not in RESOURCE_TYPES:
_bad("资源类型不正确")
if status_value not in RESOURCE_STATUSES:
_bad("资源状态不正确")
return {
"type": resource_type,
"name": _require_text(name, empty="请填写名称", limit=64, too_long="名称过长"),
"title": _require_text(title, empty="请填写标题", limit=64, too_long="标题过长"),
"path": _clean(path, 255, "路由过长"),
"component": _clean(component, 255, "组件路径过长"),
"icon": _clean(icon, 64, "图标过长"),
"permission": _clean(permission, 64, "权限码过长"),
"sort": sort,
"visible": bool(visible),
"status": status_value,
}
def create_resource(db: Session, payload: dict) -> dict:
parent_id = payload["parent_id"]
fields = _resource_fields(
resource_type=payload["type"],
name=payload["name"],
title=payload["title"],
path=payload.get("path"),
component=payload.get("component"),
icon=payload.get("icon"),
permission=payload.get("permission"),
sort=payload.get("sort") or 0,
visible=payload.get("visible", True),
status_value=payload.get("status") or "active",
)
assert_parent(db, None, parent_id)
if sibling_name_taken(db, parent_id, fields["name"]):
_bad("同级名称已存在")
resource = AdminResource(parent_id=parent_id, **fields)
db.add(resource)
commit_or_raise(db, "同级名称已存在")
return serialize_node(resource, [])
def update_resource(db: Session, resource_id: int, payload: dict) -> dict:
resource = db.get(AdminResource, resource_id)
if resource is None:
_bad("资源不存在", status.HTTP_404_NOT_FOUND)
parent_id = payload["parent_id"]
fields = _resource_fields(
resource_type=payload["type"],
name=payload["name"],
title=payload["title"],
path=payload.get("path"),
component=payload.get("component"),
icon=payload.get("icon"),
permission=payload.get("permission"),
sort=payload.get("sort") if payload.get("sort") is not None else resource.sort,
visible=payload.get("visible", resource.visible),
status_value=payload.get("status") or resource.status,
)
assert_parent(db, resource.id, parent_id)
if sibling_name_taken(db, parent_id, fields["name"], exclude_id=resource.id):
_bad("同级名称已存在")
resource.parent_id = parent_id
for key, value in fields.items():
setattr(resource, key, value)
commit_or_raise(db, "同级名称已存在")
return serialize_node(resource, [])
def delete_resource(db: Session, resource_id: int) -> dict:
resource = db.get(AdminResource, resource_id)
if resource is None:
_bad("资源不存在", status.HTTP_404_NOT_FOUND)
child_id = db.scalar(select(AdminResource.id).where(AdminResource.parent_id == resource_id).limit(1))
if child_id is not None:
_bad("存在子节点,不能删除")
db.execute(delete(AdminRoleResource).where(AdminRoleResource.resource_id == resource_id))
db.delete(resource)
commit_or_raise(db, "存在子节点,不能删除")
return {"ok": True}
+38
View File
@@ -0,0 +1,38 @@
from redis import Redis
from redis.backoff import NoBackoff
from redis.retry import Retry
from app.core.config import get_settings
_client: Redis | None = None
_client_key: tuple | None = None
def get_redis() -> Redis:
global _client, _client_key
settings = get_settings()
key = (
settings.redis_host,
settings.redis_port,
settings.redis_db,
settings.redis_password,
settings.redis_timeout_sec,
settings.redis_ssl_enabled,
)
if _client is not None and _client_key == key:
return _client
if _client is not None:
_client.close()
_client = Redis(
host=settings.redis_host,
port=settings.redis_port,
db=settings.redis_db,
password=settings.redis_password or None,
socket_timeout=settings.redis_timeout_sec,
socket_connect_timeout=settings.redis_timeout_sec,
ssl=settings.redis_ssl_enabled,
decode_responses=True,
retry=Retry(NoBackoff(), 0),
)
_client_key = key
return _client
+175
View File
@@ -0,0 +1,175 @@
import json
import os
import re
import uuid
from datetime import datetime, timedelta, timezone
from io import BytesIO
from urllib.parse import quote
import urllib3
from fastapi import HTTPException, status
from minio import Minio
from minio.error import S3Error
from app.core.config import get_settings
_EXT = re.compile(r"^\.[a-z0-9]{1,8}$")
_MISSING = {"NoSuchKey", "NoSuchBucket", "NoSuchObject", "NotFound"}
_EXISTS = {"BucketAlreadyOwnedByYou", "BucketAlreadyExists"}
_NO_POLICY = {"NoSuchBucketPolicy", "NoSuchBucket"}
def _unavailable() -> None:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="对象存储不可用")
def _unconfigured() -> None:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="对象存储未配置")
def _endpoint() -> tuple[str, bool]:
settings = get_settings()
endpoint = settings.minio_endpoint.strip()
secure = bool(settings.minio_secure)
if endpoint.startswith("https://"):
endpoint = endpoint[len("https://") :]
secure = True
elif endpoint.startswith("http://"):
endpoint = endpoint[len("http://") :]
secure = False
return endpoint.rstrip("/"), secure
def _client() -> Minio:
settings = get_settings()
endpoint, secure = _endpoint()
if not endpoint or not settings.minio_access_key or not settings.minio_secret_key:
_unconfigured()
http_client = urllib3.PoolManager(
timeout=urllib3.Timeout(connect=3.0, read=60.0),
retries=False,
)
return Minio(
endpoint,
access_key=settings.minio_access_key,
secret_key=settings.minio_secret_key,
secure=secure,
http_client=http_client,
)
def bucket_name(kind: str) -> str:
settings = get_settings()
if kind == "public":
name = settings.minio_bucket_public.strip()
elif kind == "private":
name = settings.minio_bucket_private.strip()
else:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="bucket 只能是 public 或 private")
if not name:
_unconfigured()
return name
def _public_policy(bucket: str) -> str:
return json.dumps(
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicRead",
"Effect": "Allow",
"Principal": {"AWS": ["*"]},
"Action": ["s3:GetObject"],
"Resource": [f"arn:aws:s3:::{bucket}/*"],
}
],
}
)
def _ensure_bucket(client: Minio, name: str) -> None:
if client.bucket_exists(name):
return
try:
client.make_bucket(name)
except S3Error as exc:
if exc.code not in _EXISTS:
raise
def ensure_buckets() -> None:
client = _client()
public = bucket_name("public")
private = bucket_name("private")
_ensure_bucket(client, public)
_ensure_bucket(client, private)
client.set_bucket_policy(public, _public_policy(public))
try:
client.delete_bucket_policy(private)
except S3Error as exc:
if exc.code not in _NO_POLICY:
raise
def safe_filename(filename: str | None) -> str:
name = (filename or "").replace("\\", "/").split("/")[-1].replace("\x00", "").strip()
if not name or name in {".", ".."}:
return "file"
return name[:255]
def make_object_key(filename: str) -> str:
suffix = os.path.splitext(safe_filename(filename))[1].lower()
ext = suffix if _EXT.fullmatch(suffix) else ""
day = datetime.now(timezone.utc).strftime("%Y/%m/%d")
return f"{day}/{uuid.uuid4().hex}{ext}"
def public_object_url(object_key: str) -> str:
base = get_settings().minio_base_url.strip().rstrip("/")
if not base:
_unconfigured()
parts = [quote(part, safe="") for part in object_key.split("/") if part]
return f"{base}/{'/'.join(parts)}"
def private_object_url(object_key: str, expires_seconds: int = 60) -> tuple[str, datetime]:
if expires_seconds < 1 or expires_seconds > 604800:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="链接有效期无效")
expires = timedelta(seconds=expires_seconds)
try:
url = _client().presigned_get_object(bucket_name("private"), object_key, expires=expires)
except HTTPException:
raise
except Exception:
_unavailable()
return url, datetime.now(timezone.utc) + expires
def upload_object(kind: str, object_key: str, data: bytes, content_type: str) -> None:
try:
_client().put_object(
bucket_name(kind),
object_key,
BytesIO(data),
length=len(data),
content_type=content_type or "application/octet-stream",
)
except HTTPException:
raise
except Exception:
_unavailable()
def remove_stored_object(kind: str, object_key: str) -> None:
try:
_client().remove_object(bucket_name(kind), object_key)
except S3Error as exc:
if exc.code in _MISSING:
return
_unavailable()
except HTTPException:
raise
except Exception:
_unavailable()
+2
View File
@@ -0,0 +1,2 @@
[pytest]
pythonpath = .
+14
View File
@@ -0,0 +1,14 @@
fastapi==0.119.0
uvicorn==0.34.0
pydantic-settings==2.11.0
PyJWT==2.10.1
cryptography==46.0.3
httpx==0.28.1
pytest==8.4.2
sqlalchemy==2.0.44
pymysql==1.1.2
redis==6.4.0
minio==7.2.18
bcrypt==5.0.0
pillow==11.3.0
python-multipart==0.0.20
+35
View File
@@ -0,0 +1,35 @@
"""Create the application database when it does not exist. Connection comes from the environment."""
from urllib.parse import unquote, urlparse
import pymysql
from app.core.config import get_settings
def main() -> None:
parsed = urlparse(get_settings().database_url)
name = parsed.path.lstrip("/")
if not name or not parsed.hostname:
raise SystemExit("DATABASE_URL 未配置")
connection = pymysql.connect(
host=parsed.hostname,
port=parsed.port or 3306,
user=unquote(parsed.username or ""),
password=unquote(parsed.password or ""),
charset="utf8mb4",
connect_timeout=15,
)
try:
with connection.cursor() as cursor:
cursor.execute(
f"CREATE DATABASE IF NOT EXISTS `{name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
)
connection.commit()
finally:
connection.close()
print("database ready")
if __name__ == "__main__":
main()
+365
View File
@@ -0,0 +1,365 @@
"""Walk the first-batch acceptance against the running API. Reads secrets from the environment."""
import os
import uuid
from datetime import datetime, timedelta, timezone
import httpx
from dotenv import load_dotenv
from sqlalchemy import delete, select
load_dotenv()
from app.core.config import get_settings
from app.db import SessionLocal, get_engine
from app.models.rbac import AdminRole, AdminRoleResource, AdminUser, AdminUserRole
from app.models.security import AdminAuditLog, AdminIpBlacklist
from app.services.redis_client import get_redis
BASE = os.environ.get("ACCEPTANCE_BASE", "http://127.0.0.1:18000")
def fail(message: str) -> None:
raise SystemExit(message)
def main() -> None:
get_settings()
username = os.environ["BOOTSTRAP_ADMIN_USERNAME"]
password = os.environ["BOOTSTRAP_ADMIN_PASSWORD"]
client = httpx.Client(base_url=BASE, timeout=30)
get_engine()
def captcha_code() -> tuple[str, str]:
issued = client.get("/api/admin/auth/captcha")
if issued.status_code != 200:
fail(f"captcha {issued.status_code}")
captcha_id = issued.json()["captchaId"]
stored = get_redis().get(f"gsfdc:captcha:{captcha_id}")
if not stored:
fail("captcha missing in redis")
return captcha_id, stored
def login(name: str, secret: str) -> httpx.Response:
captcha_id, code = captcha_code()
return client.post(
"/api/admin/auth/login",
json={"username": name, "password": secret, "captchaId": captcha_id, "captchaCode": code},
)
missing = client.get("/api/admin/users")
if missing.status_code != 401:
fail(f"expected 401, got {missing.status_code}")
captcha_id, code = captcha_code()
first = client.post(
"/api/admin/auth/login",
json={"username": username, "password": password, "captchaId": captcha_id, "captchaCode": code},
)
if first.status_code != 200:
fail(f"admin login {first.status_code} {first.text[:200]}")
second = client.post(
"/api/admin/auth/login",
json={"username": username, "password": password, "captchaId": captcha_id, "captchaCode": code},
)
if second.status_code != 401 or second.json().get("detail") != "用户名或密码错误":
fail(f"captcha reuse {second.status_code} {second.text[:200]}")
no_captcha = client.post(
"/api/admin/auth/login",
json={"username": username, "password": password, "captchaId": "", "captchaCode": ""},
)
if no_captcha.status_code != 401:
fail("login without captcha was accepted")
admin = login(username, password)
if admin.status_code != 200:
fail(f"admin login retry {admin.status_code}")
body = admin.json()
token = body["token"]
titles = [node["title"] for node in body["menus"]]
if "系统管理" not in titles:
fail(f"menus {titles}")
child_titles = {item["title"] for item in body["menus"][0]["children"]}
expected = {"用户管理", "角色管理", "菜单管理", "操作日志", "登录安全", "附件", "站点配置", "敏感词"}
if not expected <= child_titles:
fail(f"missing pages {expected - child_titles}")
if any(node["type"] == "button" for node in body["menus"]):
fail("button leaked into login menu")
headers = {"Authorization": f"Bearer {token}"}
resources = client.get("/api/admin/resources", headers=headers)
if resources.status_code != 200:
fail(f"resources {resources.status_code}")
tree = resources.json()
def walk(nodes):
for node in nodes:
yield node
yield from walk(node.get("children") or [])
by_name = {node["name"]: node for node in walk(tree)}
system_id = by_name["System"]["id"]
user_page = by_name["User"]["id"]
add_button = next(node["id"] for node in walk(tree) if node.get("permission") == "user:add")
role_code = f"R_VIEW_{uuid.uuid4().hex[:8]}"
created_role = client.post(
"/api/admin/roles",
headers=headers,
json={"code": role_code, "name": "内容查看", "description": "验收"},
)
if created_role.status_code != 200:
fail(f"create role {created_role.status_code} {created_role.text[:200]}")
role_id = created_role.json()["id"]
granted = client.put(
f"/api/admin/roles/{role_id}/resources",
headers=headers,
json={"resourceIds": [system_id, user_page]},
)
if granted.status_code != 200:
fail(f"grant {granted.status_code} {granted.text[:200]}")
viewer_name = f"viewer_{uuid.uuid4().hex[:8]}"
viewer_password = "View1234"
created_user = client.post(
"/api/admin/users",
headers=headers,
json={
"username": viewer_name,
"password": viewer_password,
"displayName": "内容查看员",
"mobile": "13800138000",
"roleIds": [role_id],
},
)
if created_user.status_code != 200:
fail(f"create user {created_user.status_code} {created_user.text[:300]}")
created_body = created_user.json()
if created_body.get("mobileMask") != "138****8000":
fail(f"mask {created_body}")
if "password" in created_body or "mobileCipher" in created_body:
fail("secret leaked in user response")
viewer_id = created_body["id"]
viewer_login = login(viewer_name, viewer_password)
if viewer_login.status_code != 200:
fail(f"viewer login {viewer_login.status_code} {viewer_login.text[:200]}")
viewer_body = viewer_login.json()
pages = [node["title"] for node in viewer_body["menus"][0]["children"]]
if pages != ["用户管理"]:
fail(f"viewer pages {pages}")
if viewer_body["permissions"]:
fail(f"viewer permissions {viewer_body['permissions']}")
granted_add = client.put(
f"/api/admin/roles/{role_id}/resources",
headers=headers,
json={"resourceIds": [system_id, user_page, add_button]},
)
if granted_add.status_code != 200:
fail(f"grant add {granted_add.status_code}")
viewer_again = login(viewer_name, viewer_password)
if viewer_again.json().get("permissions") != ["user:add"]:
fail(f"permissions after grant {viewer_again.json().get('permissions')}")
disabled = client.put(
f"/api/admin/users/{viewer_id}",
headers=headers,
json={"displayName": "内容查看员", "mobile": "13800138000", "status": "disabled", "roleIds": [role_id]},
)
if disabled.status_code != 200:
fail(f"disable {disabled.status_code} {disabled.text[:200]}")
if login(viewer_name, viewer_password).status_code != 401:
fail("disabled user logged in")
enabled = client.put(
f"/api/admin/users/{viewer_id}",
headers=headers,
json={"displayName": "内容查看员", "status": "active", "roleIds": [role_id]},
)
if enabled.status_code != 200 or login(viewer_name, viewer_password).status_code != 200:
fail("reenabled user could not login")
cancelled = client.put(
f"/api/admin/users/{viewer_id}",
headers=headers,
json={"displayName": "内容查看员", "status": "cancelled", "roleIds": [role_id]},
)
if cancelled.status_code != 200:
fail(f"cancel {cancelled.status_code} {cancelled.text[:200]}")
if login(viewer_name, viewer_password).status_code != 401:
fail("cancelled user logged in")
listed = client.get("/api/admin/users", headers=headers, params={"username": viewer_name})
if listed.status_code != 200 or not listed.json()["records"]:
fail("cancelled user missing from list")
weak = client.post(
"/api/admin/users",
headers=headers,
json={"username": f"weak_{uuid.uuid4().hex[:6]}", "password": "abcdefgh", "displayName": "弱", "roleIds": []},
)
if weak.status_code != 400:
fail("weak password accepted")
policy = client.put(
"/api/admin/login-security",
headers=headers,
json={"loginMaxFailures": 2, "loginLockMinutes": 15},
)
if policy.status_code != 200:
fail(f"policy {policy.status_code} {policy.text[:200]}")
lock_name = f"lock_{uuid.uuid4().hex[:6]}"
lock_password = "Lock1234"
lock_user = client.post(
"/api/admin/users",
headers=headers,
json={"username": lock_name, "password": lock_password, "displayName": "锁定", "roleIds": []},
)
if lock_user.status_code != 200:
fail(f"lock user {lock_user.status_code}")
for _ in range(2):
bad_id, _bad_code = captcha_code()
client.post(
"/api/admin/auth/login",
json={"username": lock_name, "password": "Wrong123", "captchaId": bad_id, "captchaCode": "ZZZZ"},
)
locked = login(lock_name, lock_password)
if locked.status_code != 401:
fail("locked account accepted the right password")
db = SessionLocal()
try:
row = db.scalar(select(AdminUser).where(AdminUser.username == lock_name))
row.locked_until = datetime.now(timezone.utc) - timedelta(seconds=5)
db.commit()
finally:
db.close()
if login(lock_name, lock_password).status_code != 200:
fail("login failed after lock expired")
client.put(
"/api/admin/login-security",
headers=headers,
json={"loginMaxFailures": 5, "loginLockMinutes": 15},
)
blocked_ip = "127.0.0.1"
added = client.post("/api/admin/ip-blacklist", headers=headers, json={"ip": blocked_ip, "remark": "acceptance"})
if added.status_code != 200:
fail(f"blacklist add {added.status_code} {added.text[:200]}")
blacklist_id = added.json()["id"]
try:
blocked = client.get("/api/admin/users", headers=headers)
if blocked.status_code != 403:
fail(f"blacklisted request was not rejected: {blocked.status_code}")
finally:
db = SessionLocal()
try:
db.execute(delete(AdminIpBlacklist).where(AdminIpBlacklist.id == blacklist_id))
db.commit()
finally:
db.close()
restored = client.get("/api/admin/users", headers=headers)
if restored.status_code != 200:
fail(f"request still blocked after removal: {restored.status_code}")
logs = client.get("/api/admin/audit-logs", headers=headers, params={"username": username, "current": 1, "size": 20})
if logs.status_code != 200 or logs.json()["total"] < 1:
fail(f"audit {logs.status_code} {logs.text[:200]}")
raw_logs = logs.text
if password in raw_logs or "captchaCode" in raw_logs:
fail("audit response contains a secret")
over = client.post(
"/api/admin/files",
headers=headers,
data={"bucket": "public"},
files={"file": ("big.bin", b"x" * (10 * 1024 * 1024 + 1), "application/octet-stream")},
)
if over.status_code != 400:
fail(f"oversize {over.status_code}")
public = client.post(
"/api/admin/files",
headers=headers,
data={"bucket": "public"},
files={"file": ("ok.txt", b"hello", "text/plain")},
)
if public.status_code != 200:
fail(f"public upload {public.status_code} {public.text[:200]}")
public_url = public.json()["url"]
fetched = httpx.get(public_url, timeout=20)
if fetched.status_code != 200 or fetched.content != b"hello":
fail(f"public fetch {fetched.status_code}")
private = client.post(
"/api/admin/files",
headers=headers,
data={"bucket": "private"},
files={"file": ("secret.txt", b"secret", "text/plain")},
)
if private.status_code != 200 or not private.json().get("expiresAt"):
fail(f"private upload {private.status_code} {private.text[:200]}")
site = client.put(
"/api/admin/site-settings",
headers=headers,
json={
"site_name": "验收站点",
"icp_text": "陇ICP备19001227号",
"link_cirea": "https://www.cirea.org.cn/",
},
)
if site.status_code != 200:
fail(f"site {site.status_code} {site.text[:200]}")
public_site = client.get("/api/site/settings")
public_body = public_site.json()
if public_body.get("siteName") != "验收站点" or public_body.get("linkCirea") != "https://www.cirea.org.cn/":
fail(f"public site {public_body}")
if "loginMaxFailures" in public_body or "login_max_failures" in public_body:
fail("public site leaked lock settings")
probe_word = f"验收敏感词{uuid.uuid4().hex[:6]}"
word = client.post("/api/admin/sensitive-words", headers=headers, json={"word": probe_word})
if word.status_code != 200:
fail(f"word {word.status_code} {word.text[:200]}")
preview = client.post(
"/api/admin/content/preview-filter",
headers=headers,
json={"html": f'<p onclick="alert(1)">{probe_word}</p><script>alert(1)</script>'},
)
if preview.status_code != 200:
fail(f"preview {preview.status_code}")
preview_body = preview.json()
if "script" in preview_body["html"].lower() or "onclick" in preview_body["html"].lower():
fail(f"filter kept active content {preview_body['html']}")
if probe_word not in preview_body["hits"]:
fail(f"hits {preview_body['hits']}")
articles = client.get("/api/site/settings")
if probe_word in articles.text:
fail("preview became public content")
client.delete(f"/api/admin/sensitive-words/{word.json()['id']}", headers=headers)
client.delete(f"/api/admin/files/{public.json()['id']}", headers=headers)
client.delete(f"/api/admin/files/{private.json()['id']}", headers=headers)
client.put(
"/api/admin/site-settings",
headers=headers,
json={"site_name": "甘肃省房地产价格评估行业协会", "link_cirea": ""},
)
db = SessionLocal()
try:
user_ids = [
row.id
for row in db.scalars(select(AdminUser).where(AdminUser.username.in_([viewer_name, lock_name]))).all()
]
if user_ids:
db.execute(delete(AdminUserRole).where(AdminUserRole.user_id.in_(user_ids)))
db.execute(delete(AdminUser).where(AdminUser.id.in_(user_ids)))
db.execute(delete(AdminRoleResource).where(AdminRoleResource.role_id == role_id))
db.execute(delete(AdminRole).where(AdminRole.id == role_id))
db.execute(delete(AdminIpBlacklist).where(AdminIpBlacklist.ip == blocked_ip))
db.commit()
finally:
db.close()
print("live acceptance passed")
if __name__ == "__main__":
main()
+226
View File
@@ -0,0 +1,226 @@
"""栏目文章三类:工作人员写入 → 门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _clear_column_category(client, staff: dict[str, str], category: str) -> None:
listed = client.get(f"/api/admin/about/articles/{category}", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def test_column_articles_publish_filter_and_placeholders(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
for category in ("work_briefs", "annual_reports", "qualifications"):
_clear_column_category(client, staff, category)
empty_briefs = client.get("/api/site/about/articles/work_briefs")
assert empty_briefs.status_code == 200, empty_briefs.text
assert "暂无工作简报" in empty_briefs.text
assert "暂无年度报告或工作计划" in client.get("/api/site/about/articles/annual_reports").text
assert "暂无资质与荣誉" in client.get("/api/site/about/articles/qualifications").text
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("批复扫描件.pdf", b"%PDF-1.4\nscan", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
report = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "annual_reports",
"title": "2025年协会工作报告",
"publishedAt": "2026-01-15T08:00:00",
"published": True,
"bodyHtml": "<p>公开公示版</p><script>alert(1)</script>",
"attachmentFileIds": [],
},
)
assert report.status_code == 200, report.text
article_ids.append(report.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "annual_reports",
"title": "内部财务稿",
"publishedAt": "2026-01-16T08:00:00",
"published": False,
"bodyHtml": "<p>内部财务稿</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
honor = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "qualifications",
"title": "主管单位批复文件",
"publishedAt": "2024-03-01T08:00:00",
"published": True,
"bodyHtml": "<p>批复摘要</p>",
"attachmentFileIds": [file_ids[0]],
},
)
assert honor.status_code == 200, honor.text
article_ids.append(honor.json()["id"])
reports = client.get("/api/site/about/articles/annual_reports")
assert reports.status_code == 200, reports.text
assert "2025年协会工作报告" in reports.text
assert "内部财务稿" not in reports.text
assert "暂无年度报告或工作计划" not in reports.text
detail = client.get(f"/api/site/home/articles/{article_ids[0]}")
assert detail.status_code == 200, detail.text
body = detail.json()["bodyHtml"].lower()
assert "公开公示版" in detail.json()["bodyHtml"]
assert "script" not in body
assert "alert" not in body
hidden = client.get(f"/api/site/home/articles/{article_ids[1]}")
assert hidden.status_code == 404
honors = client.get("/api/site/about/articles/qualifications")
assert honors.status_code == 200, honors.text
assert "主管单位批复文件" in honors.text
honor_detail = client.get(f"/api/site/home/articles/{article_ids[2]}")
assert honor_detail.status_code == 200, honor_detail.text
assert [item["filename"] for item in honor_detail.json()["attachments"]] == ["批复扫描件.pdf"]
home = client.get("/api/site/home")
assert home.status_code == 200, home.text
home_json = home.json()
assert "annual_reports" not in home_json
assert "work_briefs" not in home_json
assert "qualifications" not in home_json
assert "2025年协会工作报告" not in home.text
editor = client.get("/api/admin/home", headers=staff)
assert editor.status_code == 200, editor.text
categories = {item["category"] for item in editor.json()["articles"]}
assert "annual_reports" not in categories
assert "work_briefs" not in categories
assert "qualifications" not in categories
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "work_briefs",
"title": "会员不得发布",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
assert "会员不得发布" not in client.get("/api/site/about/articles/work_briefs").text
assert "暂无工作简报" in client.get("/api/site/about/articles/work_briefs").text
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
def test_column_articles_public_pagination(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
try:
_clear_column_category(client, staff, "work_briefs")
for index in range(11):
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "work_briefs",
"title": f"简报分页样例-{index:02d}",
"publishedAt": f"2026-02-{index + 1:02d}T08:00:00",
"published": True,
"bodyHtml": f"<p>简报分页样例-{index:02d}</p>",
"attachmentFileIds": [],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
page1 = client.get("/api/site/about/articles/work_briefs?current=1&size=10")
assert page1.status_code == 200, page1.text
body1 = page1.json()
assert body1["total"] == 11
assert body1["current"] == 1
assert body1["size"] == 10
assert len(body1["items"]) == 10
assert body1["items"][0]["title"] == "简报分页样例-10"
page2 = client.get("/api/site/about/articles/work_briefs?current=2&size=10")
assert page2.status_code == 200, page2.text
body2 = page2.json()
assert body2["total"] == 11
assert body2["current"] == 2
assert len(body2["items"]) == 1
assert body2["items"][0]["title"] == "简报分页样例-00"
size20 = client.get("/api/site/about/articles/work_briefs?current=1&size=20")
assert size20.status_code == 200, size20.text
assert size20.json()["size"] == 20
assert len(size20.json()["items"]) == 11
bad_size = client.get("/api/site/about/articles/work_briefs?current=1&size=15")
assert bad_size.status_code == 200, bad_size.text
assert bad_size.json()["size"] == 10
assert len(bad_size.json()["items"]) == 10
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
+148
View File
@@ -0,0 +1,148 @@
"""专家委员会:工作人员写入 → 门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def test_expert_committees_list_detail_delete_and_placeholder(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
ids: list[int] = []
file_id = None
try:
empty = client.get("/api/site/about/experts")
assert empty.status_code == 200, empty.text
assert "暂无专家委员会信息" in empty.text
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("专家名录.pdf", b"%PDF-1.4\nexperts", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_id = pdf.json()["id"]
first = client.post(
"/api/admin/about/experts",
headers=staff,
json={
"name": "房地产估价专家委员会",
"bodyHtml": "<p>估价技术咨询</p><script>alert(1)</script>",
"sortOrder": 1,
"published": True,
"attachmentFileIds": [file_id],
},
)
assert first.status_code == 200, first.text
ids.append(first.json()["id"])
second = client.post(
"/api/admin/about/experts",
headers=staff,
json={
"name": "行业自律专家委员会",
"bodyHtml": "<p>自律意见</p>",
"sortOrder": 2,
"published": True,
"attachmentFileIds": [],
},
)
assert second.status_code == 200, second.text
ids.append(second.json()["id"])
draft = client.post(
"/api/admin/about/experts",
headers=staff,
json={
"name": "内部筹备组",
"bodyHtml": "<p>内部</p>",
"sortOrder": 0,
"published": False,
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
ids.append(draft.json()["id"])
listing = client.get("/api/site/about/experts")
assert listing.status_code == 200, listing.text
names = [item["name"] for item in listing.json()["items"]]
assert names == ["房地产估价专家委员会", "行业自律专家委员会"]
assert "内部筹备组" not in listing.text
detail = client.get(f"/api/site/about/experts/{ids[0]}")
assert detail.status_code == 200, detail.text
assert "估价技术咨询" in detail.json()["bodyHtml"]
lowered = detail.json()["bodyHtml"].lower()
assert "script" not in lowered
assert "alert" not in lowered
assert [item["filename"] for item in detail.json()["attachments"]] == ["专家名录.pdf"]
hidden = client.get(f"/api/site/about/experts/{ids[2]}")
assert hidden.status_code == 404
deleted = client.delete(f"/api/admin/about/experts/{ids[1]}", headers=staff)
assert deleted.status_code == 200, deleted.text
ids.remove(ids[1])
after = client.get("/api/site/about/experts")
assert "行业自律专家委员会" not in after.text
assert "房地产估价专家委员会" in after.text
rejected = client.post(
"/api/admin/about/experts",
headers=_headers("member"),
json={
"name": "会员委员会",
"bodyHtml": "<p>x</p>",
"sortOrder": 9,
"published": True,
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
assert "会员委员会" not in client.get("/api/site/about/experts").text
finally:
for expert_id in list(ids):
client.delete(f"/api/admin/about/experts/{expert_id}", headers=staff)
leftover = client.get("/api/site/about/experts")
# clean any published leftovers from failed runs
admin_list = client.get("/api/admin/about/experts", headers=staff)
if admin_list.status_code == 200:
for item in admin_list.json().get("items", []):
client.delete(f"/api/admin/about/experts/{item['id']}", headers=staff)
assert "暂无专家委员会信息" in client.get("/api/site/about/experts").text
if file_id is not None:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+188
View File
@@ -0,0 +1,188 @@
"""单篇页:协会简介等。工作人员写入 → 门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def test_association_intro_page_publish_filter_and_placeholder(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
file_id = None
try:
before = client.get("/api/site/about/pages/intro")
assert before.status_code == 200, before.text
assert "协会简介整理中" in before.text
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("协会章程.pdf", b"%PDF-1.4\ncharter", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_id = pdf.json()["id"]
saved = client.put(
"/api/admin/about/pages/intro",
headers=staff,
json={
"published": True,
"bodyHtml": "<p>服务会员与规范执业</p><script>alert(1)</script>",
"attachmentFileIds": [file_id],
},
)
assert saved.status_code == 200, saved.text
public = client.get("/api/site/about/pages/intro")
assert public.status_code == 200, public.text
data = public.json()
assert "服务会员与规范执业" in data["bodyHtml"]
lowered = data["bodyHtml"].lower()
assert "script" not in lowered
assert "alert" not in lowered
assert [item["filename"] for item in data["attachments"]] == ["协会章程.pdf"]
assert "协会简介整理中" not in public.text
emptied = client.put(
"/api/admin/about/pages/intro",
headers=staff,
json={"published": True, "bodyHtml": "", "attachmentFileIds": []},
)
assert emptied.status_code == 200, emptied.text
empty_public = client.get("/api/site/about/pages/intro")
assert empty_public.status_code == 200, empty_public.text
assert "协会简介整理中" in empty_public.text
published_again = client.put(
"/api/admin/about/pages/intro",
headers=staff,
json={
"published": True,
"bodyHtml": "<p>服务会员与规范执业</p>",
"attachmentFileIds": [file_id],
},
)
assert published_again.status_code == 200, published_again.text
before_member = client.get("/api/site/about/pages/intro").json()
rejected = client.put(
"/api/admin/about/pages/intro",
headers=_headers("member"),
json={"published": True, "bodyHtml": "<p>会员篡改</p>", "attachmentFileIds": []},
)
assert rejected.status_code in (401, 403)
after_member = client.get("/api/site/about/pages/intro")
assert after_member.status_code == 200
assert after_member.json()["bodyHtml"] == before_member["bodyHtml"]
assert "会员篡改" not in after_member.text
finally:
client.put(
"/api/admin/about/pages/intro",
headers=staff,
json={"published": False, "bodyHtml": "", "attachmentFileIds": []},
)
if file_id is not None:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
def test_org_structure_page_unpublished_placeholder(client):
staff = _headers("staff")
client.put(
"/api/admin/about/pages/org",
headers=staff,
json={"published": False, "bodyHtml": "<p>草稿架构</p>", "attachmentFileIds": []},
)
public = client.get("/api/site/about/pages/org")
assert public.status_code == 200, public.text
assert "组织机构整理中" in public.text
assert "草稿架构" not in public.text
rejected = client.put(
"/api/admin/about/pages/org",
headers=_headers("member"),
json={"published": True, "bodyHtml": "<p>会员</p>", "attachmentFileIds": []},
)
assert rejected.status_code in (401, 403)
def test_contact_cooperation_page_without_forms(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
file_id = None
try:
unpublished = client.get("/api/site/about/pages/contact")
# reset first
client.put(
"/api/admin/about/pages/contact",
headers=staff,
json={"published": False, "bodyHtml": "", "attachmentFileIds": []},
)
unpublished = client.get("/api/site/about/pages/contact")
assert "联系与合作信息整理中" in unpublished.text
doc = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("入会申请表.docx", b"PK\x03\x04join", "application/octet-stream")},
)
assert doc.status_code == 200, doc.text
file_id = doc.json()["id"]
saved = client.put(
"/api/admin/about/pages/contact",
headers=staff,
json={
"published": True,
"bodyHtml": "<p>来访请先电话预约</p>",
"attachmentFileIds": [file_id],
},
)
assert saved.status_code == 200, saved.text
public = client.get("/api/site/about/pages/contact")
assert public.status_code == 200, public.text
data = public.json()
assert "来访请先电话预约" in data["bodyHtml"]
assert [item["filename"] for item in data["attachments"]] == ["入会申请表.docx"]
assert "formFields" not in data
assert "signupUrl" not in data
assert client.post("/api/site/about/pages/contact/intent", json={}).status_code == 404
assert client.post("/api/site/about/pages/contact/join", json={}).status_code == 404
finally:
client.put(
"/api/admin/about/pages/contact",
headers=staff,
json={"published": False, "bodyHtml": "", "attachmentFileIds": []},
)
if file_id is not None:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+230
View File
@@ -0,0 +1,230 @@
"""专项估价指南:分类筛选、占位、分页、未发布不可见。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _clear_guides(client, staff: dict[str, str]) -> None:
listed = client.get("/api/admin/about/articles/appraisal_guides", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def test_appraisal_guides_kind_filter_placeholder_and_pagination(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
_clear_guides(client, staff)
empty = client.get("/api/site/about/articles/appraisal_guides")
assert empty.status_code == 200, empty.text
assert "暂无估价指南" in empty.text
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("cover.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("住宅估价流程.pdf", b"%PDF-1.4\nguide", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
missing_kind = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "appraisal_guides",
"title": "缺分类指南",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert missing_kind.status_code == 400
residential = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "appraisal_guides",
"kind": "residential",
"title": "住宅估价服务指南",
"publishedAt": "2025-06-01T08:00:00",
"published": True,
"bodyHtml": "<p>住宅流程</p><script>alert(1)</script>",
"imageFileId": file_ids[0],
"attachmentFileIds": [file_ids[1]],
},
)
assert residential.status_code == 200, residential.text
article_ids.append(residential.json()["id"])
commercial = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "appraisal_guides",
"kind": "commercial",
"title": "商业估价服务指南",
"publishedAt": "2025-06-02T08:00:00",
"published": True,
"bodyHtml": "<p>商业流程</p>",
"attachmentFileIds": [],
},
)
assert commercial.status_code == 200, commercial.text
article_ids.append(commercial.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "appraisal_guides",
"kind": "industrial",
"title": "工业估价内部稿",
"publishedAt": "2025-06-03T08:00:00",
"published": False,
"bodyHtml": "<p>内部</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
all_list = client.get("/api/site/about/articles/appraisal_guides")
assert all_list.status_code == 200, all_list.text
titles = [item["title"] for item in all_list.json()["items"]]
assert "住宅估价服务指南" in titles
assert "商业估价服务指南" in titles
assert "工业估价内部稿" not in titles
residential_item = next(item for item in all_list.json()["items"] if "住宅" in item["title"])
assert residential_item["kind"] == "residential"
assert residential_item["kindLabel"] == "住宅"
assert residential_item.get("imageUrl")
only_residential = client.get("/api/site/about/articles/appraisal_guides?kind=residential")
assert only_residential.status_code == 200, only_residential.text
assert [item["title"] for item in only_residential.json()["items"]] == ["住宅估价服务指南"]
only_commercial = client.get("/api/site/about/articles/appraisal_guides?kind=commercial")
assert [item["title"] for item in only_commercial.json()["items"]] == ["商业估价服务指南"]
empty_specialty = client.get("/api/site/about/articles/appraisal_guides?kind=specialty")
assert empty_specialty.status_code == 200, empty_specialty.text
assert "暂无估价指南" in empty_specialty.text
bad_kind = client.get("/api/site/about/articles/appraisal_guides?kind=unknown")
assert bad_kind.status_code == 404
detail = client.get(f"/api/site/home/articles/{article_ids[0]}")
assert detail.status_code == 200, detail.text
assert detail.json()["kind"] == "residential"
assert detail.json()["kindLabel"] == "住宅"
assert "住宅流程" in detail.json()["bodyHtml"]
assert "script" not in detail.json()["bodyHtml"].lower()
assert detail.json().get("imageUrl")
assert [item["filename"] for item in detail.json()["attachments"]] == ["住宅估价流程.pdf"]
hidden = client.get(f"/api/site/home/articles/{article_ids[2]}")
assert hidden.status_code == 404
for index in range(10):
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "appraisal_guides",
"kind": "specialty",
"title": f"特色地产指南-{index:02d}",
"publishedAt": f"2025-01-{index + 1:02d}T08:00:00",
"published": True,
"bodyHtml": f"<p>特色-{index:02d}</p>",
"attachmentFileIds": [],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
page1 = client.get("/api/site/about/articles/appraisal_guides?kind=specialty&current=1&size=10")
assert page1.status_code == 200, page1.text
assert page1.json()["total"] == 10
assert page1.json()["size"] == 10
assert len(page1.json()["items"]) == 10
home = client.get("/api/admin/home", headers=staff)
assert home.status_code == 200, home.text
categories = {item["category"] for item in home.json()["articles"]}
assert "appraisal_guides" not in categories
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "appraisal_guides",
"kind": "residential",
"title": "会员不得发布指南",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
assert "会员不得发布指南" not in client.get("/api/site/about/articles/appraisal_guides").text
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+421
View File
@@ -0,0 +1,421 @@
import time
import uuid
from contextlib import contextmanager
import httpx
import pytest
import urllib3
from fastapi import HTTPException
from minio.error import S3Error
from sqlalchemy import func, inspect, select
from app.core.config import get_settings
from app.services.html_filter import filter_html
_PUBLIC_KEYS = {
"siteName",
"logoUrl",
"bannerUrls",
"icpText",
"policeText",
"friendLinks",
"linkCirea",
"linkHousing",
}
def test_object_key_keeps_safe_extension(monkeypatch):
monkeypatch.setenv("MINIO_BASE_URL", "http://127.0.0.1:9000/gsfdc-public/")
get_settings.cache_clear()
try:
from app.services.storage import make_object_key, public_object_url, safe_filename
assert safe_filename("../../logo.PNG") == "logo.PNG"
key = make_object_key("../../logo.PNG")
assert ".." not in key
assert key.endswith(".png")
url = public_object_url(key)
assert url == "http://127.0.0.1:9000/gsfdc-public/" + key
assert "//" not in url.replace("://", "")
finally:
get_settings.cache_clear()
def test_html_whitelist_removes_active_content():
html = (
'<p onClick="alert(1)" class="keep">正文敏感词</p>'
'<a href="javascript:alert(1)" title="t">链接</a>'
"<script>alert(1)</script>"
"<style>p{color:red}</style>"
'<div>前<iframe src="https://evil.test">密文</iframe>后</div>'
'<img src="https://evil.test/a.png" alt="x">'
'<img src="http://127.0.0.1:9000/gsfdc-public/2026/10/19/abc.png" alt="ok">'
)
cleaned = filter_html(html, ["2026/10/19/abc.png"], "http://127.0.0.1:9000/gsfdc-public")
lowered = cleaned.lower()
assert "<script" not in lowered
assert "onclick" not in lowered
assert "javascript:" not in lowered
assert "<style" not in lowered
assert "<iframe" not in lowered
assert "密文" not in cleaned
assert "alert" not in lowered
assert "evil.test" not in cleaned
assert "正文敏感词" in cleaned
assert 'class="keep"' in cleaned
assert "链接" in cleaned
assert 'title="t"' in cleaned
assert 'alt="x"' in cleaned
assert "2026/10/19/abc.png" in cleaned
assert "前" in cleaned and "后" in cleaned
def _database_configured() -> bool:
get_settings.cache_clear()
return bool(get_settings().database_url.strip())
def _load_routers():
try:
from app.api.admin.content import router as admin_router
from app.api.site.settings import router as site_router
except ModuleNotFoundError:
pytest.skip("app.db 尚未就绪")
return admin_router, site_router
@pytest.fixture
def api_client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
admin_router, site_router = _load_routers()
from fastapi.testclient import TestClient
from app.main import create_app
app = create_app()
paths = {getattr(route, "path", "") for route in app.routes}
if "/api/admin/files" not in paths:
app.include_router(admin_router, prefix="/api/admin")
if "/api/site/settings" not in paths:
app.include_router(site_router, prefix="/api/site")
with TestClient(app) as client:
yield client
get_settings.cache_clear()
def _staff_headers() -> dict[str, str]:
from app.core.security import create_access_token
token = create_access_token("1", "staff")
return {"Authorization": f"Bearer {token}"}
@contextmanager
def _session():
from app.db import get_db
resource = get_db()
if hasattr(resource, "__next__"):
db = next(resource)
try:
yield db
finally:
db.rollback()
resource.close()
return
try:
yield resource
finally:
resource.rollback()
resource.close()
def _prepare_tables() -> None:
from app.db import Base
from app.models.content import AdminFile, SensitiveWord, SiteSetting, ensure_site_defaults
with _session() as db:
Base.metadata.create_all(
bind=db.get_bind(),
tables=[SiteSetting.__table__, AdminFile.__table__, SensitiveWord.__table__],
)
ensure_site_defaults(db)
def _table_names() -> set[str]:
with _session() as db:
return set(inspect(db.get_bind()).get_table_names())
def _count_files() -> int:
from app.models.content import AdminFile
with _session() as db:
return int(db.scalar(select(func.count()).select_from(AdminFile)) or 0)
@pytest.fixture
def ready_client(api_client):
if not _database_configured():
pytest.skip("DATABASE_URL 为空")
_prepare_tables()
return api_client
def test_file_list_matches_filename(ready_client):
from app.db import SessionLocal
from app.models.content import AdminFile
token = uuid.uuid4().hex[:10]
names = [f"检索甲-{token}.txt", f"检索乙-{token}.png", f"其他-{token}.txt"]
db = SessionLocal()
ids: list[int] = []
try:
for name in names:
row = AdminFile(
bucket="public",
object_key=f"test/{token}/{name}",
filename=name,
content_type="text/plain",
size=1,
)
db.add(row)
db.flush()
ids.append(row.id)
db.commit()
finally:
db.close()
headers = _staff_headers()
try:
found = ready_client.get(
"/api/admin/files",
headers=headers,
params={"q": f"检索甲-{token}", "size": 20},
)
assert found.status_code == 200, found.text
body = found.json()
assert [item["filename"] for item in body["records"]] == [f"检索甲-{token}.txt"]
assert body["total"] == 1
wildcard = ready_client.get(
"/api/admin/files",
headers=headers,
params={"q": "%", "size": 100},
)
assert wildcard.status_code == 200, wildcard.text
assert f"检索甲-{token}.txt" not in [item["filename"] for item in wildcard.json()["records"]]
finally:
db = SessionLocal()
try:
for file_id in ids:
row = db.get(AdminFile, file_id)
if row is not None:
db.delete(row)
db.commit()
finally:
db.close()
def test_admin_content_requires_login(api_client):
checks = [
("get", "/api/admin/files", None),
("get", "/api/admin/files/1", None),
("get", "/api/admin/site-settings", None),
("get", "/api/admin/sensitive-words", None),
("put", "/api/admin/site-settings", {"site_name": "x"}),
("post", "/api/admin/sensitive-words", {"word": "x"}),
("post", "/api/admin/content/preview-filter", {"html": "<p>a</p>"}),
("delete", "/api/admin/sensitive-words/1", None),
("delete", "/api/admin/files/1", None),
]
for method, path, payload in checks:
kwargs = {"json": payload} if payload is not None else {}
response = getattr(api_client, method)(path, **kwargs)
assert response.status_code == 401, path
uploaded = api_client.post(
"/api/admin/files",
data={"bucket": "public"},
files={"file": ("a.txt", b"hi", "text/plain")},
)
assert uploaded.status_code == 401
def test_preview_filter_reports_words_without_new_tables(ready_client):
headers = _staff_headers()
word = "预览" + uuid.uuid4().hex[:12]
created = ready_client.post("/api/admin/sensitive-words", json={"word": word}, headers=headers)
assert created.status_code == 200, created.text
word_id = created.json()["id"]
try:
before_tables = _table_names()
before_count = len(ready_client.get("/api/admin/sensitive-words", headers=headers).json())
html = f'<p onclick="alert(1)">正文{word}</p><script>alert(1){word}</script>'
response = ready_client.post(
"/api/admin/content/preview-filter",
json={"html": html},
headers=headers,
)
assert response.status_code == 200, response.text
body = response.json()
assert word in body["hits"]
assert body["html"].count(word) == 1
assert "<script" not in body["html"].lower()
assert "onclick" not in body["html"].lower()
assert _table_names() == before_tables
after_count = len(ready_client.get("/api/admin/sensitive-words", headers=headers).json())
assert after_count == before_count
finally:
ready_client.delete(f"/api/admin/sensitive-words/{word_id}", headers=headers)
def test_upload_over_limit_is_rejected(ready_client):
headers = _staff_headers()
current = ready_client.get("/api/admin/site-settings", headers=headers)
assert current.status_code == 200, current.text
original = current.json()["upload_max_bytes"]
try:
updated = ready_client.put(
"/api/admin/site-settings",
json={"upload_max_bytes": 4},
headers=headers,
)
assert updated.status_code == 200, updated.text
before = _count_files()
rejected = ready_client.post(
"/api/admin/files",
headers=headers,
data={"bucket": "public"},
files={"file": ("note.txt", b"12345", "text/plain")},
)
assert rejected.status_code == 400
assert rejected.json()["detail"] == "文件超过大小上限"
assert _count_files() == before
finally:
ready_client.put(
"/api/admin/site-settings",
json={"upload_max_bytes": original},
headers=headers,
)
def test_public_settings_hide_login_lock(ready_client):
headers = _staff_headers()
before = ready_client.get("/api/admin/site-settings", headers=headers)
assert before.status_code == 200, before.text
original = before.json()
assert isinstance(original["upload_max_bytes"], int)
assert isinstance(original["login_max_failures"], int)
assert isinstance(original["login_lock_minutes"], int)
assert isinstance(original["logoUrl"], str)
assert isinstance(original["bannerUrls"], list)
link = {"name": "示例链接", "url": "https://example.com/gsrea"}
try:
rejected = ready_client.put(
"/api/admin/site-settings",
json={"theme": "dark"},
headers=headers,
)
assert rejected.status_code == 400
saved = ready_client.put(
"/api/admin/site-settings",
json={
"site_name": "甘肃价协测试站点",
"icp_text": "陇ICP备测试号",
"friend_links": [link],
},
headers=headers,
)
assert saved.status_code == 200, saved.text
response = ready_client.get("/api/site/settings")
assert response.status_code == 200, response.text
body = response.json()
assert set(body) == _PUBLIC_KEYS
assert body["siteName"] == "甘肃价协测试站点"
assert body["icpText"] == "陇ICP备测试号"
assert body["friendLinks"] == [link]
assert isinstance(body["logoUrl"], str)
assert isinstance(body["bannerUrls"], list)
text = response.text
assert "login_max_failures" not in text
assert "login_lock_minutes" not in text
assert "loginMaxFailures" not in text
assert "loginLockMinutes" not in text
assert "upload_max_bytes" not in text
assert "uploadMaxBytes" not in text
finally:
ready_client.put(
"/api/admin/site-settings",
json={
"site_name": original["site_name"],
"icp_text": original["icp_text"],
"friend_links": original["friend_links"],
},
headers=headers,
)
def _minio_ready() -> bool:
from app.services.storage import ensure_buckets
try:
ensure_buckets()
except (urllib3.exceptions.HTTPError, OSError, TimeoutError):
return False
except (HTTPException, S3Error):
return False
return True
def test_public_object_and_private_expiry(ready_client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
from app.models.content import AdminFile
from app.services.storage import private_object_url
headers = _staff_headers()
payload = b"gsfdc-public-png"
created_ids: list[int] = []
try:
uploaded = ready_client.post(
"/api/admin/files",
headers=headers,
data={"bucket": "public"},
files={"file": ("logo.png", payload, "image/png")},
)
assert uploaded.status_code == 200, uploaded.text
public_body = uploaded.json()
created_ids.append(public_body["id"])
assert public_body["expiresAt"] is None
base = get_settings().minio_base_url.strip().rstrip("/")
assert public_body["url"].startswith(base + "/")
assert "//" not in public_body["url"].replace("://", "")
downloaded = httpx.get(public_body["url"], timeout=5.0, follow_redirects=True)
assert downloaded.status_code == 200
assert downloaded.content == payload
private = ready_client.post(
"/api/admin/files",
headers=headers,
data={"bucket": "private"},
files={"file": ("secret.bin", b"gsfdc-private-bin", "application/octet-stream")},
)
assert private.status_code == 200, private.text
private_body = private.json()
created_ids.append(private_body["id"])
assert private_body["expiresAt"]
with _session() as db:
row = db.get(AdminFile, private_body["id"])
assert row is not None
assert row.created_by == 1
object_key = row.object_key
fresh, _ = private_object_url(object_key, expires_seconds=60)
assert httpx.get(fresh, timeout=5.0, follow_redirects=True).status_code == 200
short, _ = private_object_url(object_key, expires_seconds=1)
time.sleep(2)
expired = httpx.get(short, timeout=5.0, follow_redirects=True)
assert expired.status_code != 200
finally:
for file_id in created_ids:
ready_client.delete(f"/api/admin/files/{file_id}", headers=headers)
+319
View File
@@ -0,0 +1,319 @@
"""行业自律:三类栏目文章公开阅读;投诉加密保存,查询码只看状态。"""
import base64
import hashlib
from datetime import datetime, timedelta
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import select
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
key = base64.b64encode(hashlib.sha256(b"discipline-field-key").digest()).decode("ascii")
monkeypatch.setenv("FIELD_AES_KEY", key)
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def _clear_category(client, staff: dict[str, str], category: str) -> None:
listed = client.get(f"/api/admin/about/articles/{category}", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def _purge_complaints(codes: list[str]) -> list[int]:
from app.db import SessionLocal
from app.models.discipline import DisciplineComplaint, DisciplineComplaintFile
db = SessionLocal()
file_ids: list[int] = []
try:
rows = db.scalars(select(DisciplineComplaint).where(DisciplineComplaint.code.in_(codes))).all()
ids = [row.id for row in rows]
if not ids:
return []
links = db.scalars(
select(DisciplineComplaintFile).where(DisciplineComplaintFile.complaint_id.in_(ids))
).all()
file_ids = [link.file_id for link in links]
for link in links:
db.delete(link)
for row in rows:
db.delete(row)
db.commit()
finally:
db.close()
return file_ids
def test_discipline_articles_notice_and_complaint(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
member = _headers("member")
article_ids: list[int] = []
file_ids: list[int] = []
codes: list[str] = []
word_id = None
previous_workdays = None
try:
for category, placeholder in (
("warning_cases", "暂无警示案例"),
("integrity_records", "暂无诚信档案"),
("discipline_results", "暂无结果公示"),
):
_clear_category(client, staff, category)
empty = client.get(f"/api/site/about/articles/{category}")
assert empty.status_code == 200, empty.text
assert placeholder in empty.text
denied = client.get("/api/admin/discipline/complaints", headers=member)
assert denied.status_code == 403, denied.text
assert client.get("/api/admin/discipline/complaints").status_code == 401
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("cover.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
attachment = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("note.txt", b"public-note", "text/plain")},
)
assert attachment.status_code == 200, attachment.text
file_ids.append(attachment.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "warning_cases",
"title": "未发布警示",
"published": False,
"bodyHtml": "<p>内部草稿</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
published = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "discipline_results",
"title": "某机构处理结果",
"published": True,
"bodyHtml": "<p>已脱敏的处理结果</p><script>alert(1)</script>",
"imageFileId": file_ids[0],
"attachmentFileIds": [file_ids[1]],
},
)
assert published.status_code == 200, published.text
article_ids.append(published.json()["id"])
hidden = client.get("/api/site/about/articles/warning_cases")
assert "未发布警示" not in hidden.text
shown = client.get("/api/site/about/articles/discipline_results")
titles = [item["title"] for item in shown.json()["items"]]
assert "某机构处理结果" in titles
detail = client.get(f"/api/site/home/articles/{published.json()['id']}")
assert "已脱敏的处理结果" in detail.text
assert "script" not in detail.text
assert "note.txt" in detail.text
home = client.get("/api/admin/home", headers=staff)
categories = {item["category"] for item in home.json()["articles"]}
assert "warning_cases" not in categories
assert "discipline_results" not in categories
settings = client.get("/api/admin/site-settings", headers=staff)
assert settings.status_code == 200, settings.text
previous_workdays = settings.json().get("complaint_workdays", "")
updated = client.put(
"/api/admin/site-settings",
headers=staff,
json={"complaint_workdays": 12},
)
assert updated.status_code == 200, updated.text
notice = client.put(
"/api/admin/discipline/notice",
headers=staff,
json={
"phone": "0931-1234567",
"email": "report@example.com",
"scopeHtml": "<p>受理估价执业违规</p><script>alert(1)</script>",
"processHtml": "<p>受理后核查</p>",
},
)
assert notice.status_code == 200, notice.text
assert notice.json()["workdays"] == 12
public_notice = client.get("/api/site/discipline/notice")
assert public_notice.status_code == 200, public_notice.text
assert "0931-1234567" in public_notice.text
assert "受理估价执业违规" in public_notice.text
assert "script" not in public_notice.text
assert public_notice.json()["workdays"] == 12
missing = client.post(
"/api/site/discipline/complaints",
data={
"title": "缺证据",
"subject": "某机构",
"body": "没有附件",
"contactName": "李四",
"mobile": "13800138000",
},
)
assert missing.status_code == 400, missing.text
assert "证据" in missing.text
word = "自律禁词" + hashlib.sha256(b"discipline-word").hexdigest()[:8]
created_word = client.post("/api/admin/sensitive-words", headers=staff, json={"word": word})
assert created_word.status_code == 200, created_word.text
word_id = created_word.json()["id"]
blocked = client.post(
"/api/site/discipline/complaints",
data={
"title": f"标题含{word}",
"subject": "某机构",
"body": "事实说明",
"contactName": "李四",
"mobile": "13800138000",
},
files=[("evidence", ("proof.png", _png(), "image/png"))],
)
assert blocked.status_code == 400, blocked.text
assert "敏感词" in blocked.text
secret = "只应工作人员看到的违规事实"
submitted = client.post(
"/api/site/discipline/complaints",
data={
"title": "估价报告违规",
"subject": "某估价机构",
"body": secret,
"contactName": "张三",
"mobile": "138-0013-8000",
"email": "a@example.com",
},
files=[("evidence", ("proof.png", _png(), "image/png"))],
)
assert submitted.status_code == 200, submitted.text
payload = submitted.json()
codes.append(payload["code"])
assert payload["status"] == "pending"
assert payload["workdays"] == 12
assert secret not in submitted.text
assert "13800138000" not in submitted.text
listed = client.get("/api/admin/discipline/complaints", headers=staff)
assert listed.status_code == 200, listed.text
item = next(row for row in listed.json()["items"] if row["code"] == payload["code"])
assert item["mobileMask"] == "138****8000"
assert item["emailMask"] == "a***@example.com"
assert secret not in listed.text
assert "13800138000" not in listed.text
assert item["attachmentCount"] == 1
opened = client.get(f"/api/admin/discipline/complaints/{item['id']}", headers=staff)
assert opened.status_code == 200, opened.text
assert opened.json()["mobile"] == "13800138000"
assert opened.json()["email"] == "a@example.com"
assert secret in opened.text
assert opened.json()["attachments"][0]["filename"] == "proof.png"
assert opened.json()["attachments"][0]["url"]
file_ids.append(opened.json()["attachments"][0]["id"])
status = client.get(f"/api/site/discipline/complaints/{payload['code']}")
assert status.status_code == 200, status.text
assert status.json()["statusLabel"] == "待处理"
assert secret not in status.text
assert "13800138000" not in status.text
assert "张三" not in status.text
assert "proof.png" not in status.text
from app.db import SessionLocal
from app.models.discipline import DisciplineComplaint
db = SessionLocal()
try:
row = db.scalar(select(DisciplineComplaint).where(DisciplineComplaint.code == payload["code"]))
assert row is not None
row.created_at = datetime.now() - timedelta(days=40)
db.commit()
finally:
db.close()
overdue = client.get("/api/admin/discipline/complaints?status=pending", headers=staff)
overdue_item = next(row for row in overdue.json()["items"] if row["code"] == payload["code"])
assert overdue_item["overdue"] is True
public_overdue = client.get(f"/api/site/discipline/complaints/{payload['code']}")
assert public_overdue.json()["overdue"] is True
done = client.post(f"/api/admin/discipline/complaints/{item['id']}/process", headers=staff)
assert done.status_code == 200, done.text
finished = client.get(f"/api/site/discipline/complaints/{payload['code'].lower()}")
assert finished.json()["status"] == "processed"
assert finished.json()["overdue"] is False
assert client.get("/api/site/discipline/complaints/NO-SUCH").status_code == 404
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
evidence_ids = _purge_complaints(codes)
for file_id in [*file_ids, *evidence_ids]:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
if word_id is not None:
client.delete(f"/api/admin/sensitive-words/{word_id}", headers=staff)
client.put(
"/api/admin/discipline/notice",
headers=staff,
json={"phone": "", "email": "", "scopeHtml": "", "processHtml": ""},
)
if previous_workdays is not None:
client.put(
"/api/admin/site-settings",
headers=staff,
json={"complaint_workdays": previous_workdays},
)
+223
View File
@@ -0,0 +1,223 @@
"""继续教育:在线教育外链卡片与教育公告。工作人员写入,门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def _clear_notices(client, staff: dict[str, str]) -> None:
listed = client.get("/api/admin/about/articles/edu_notices", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def test_edu_platforms_are_public_cards_and_notices_follow_publish_rules(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
file_ids: list[int] = []
try:
empty = client.get("/api/site/edu/platforms")
assert empty.status_code == 200, empty.text
assert empty.json()["placeholder"] == "暂无在线教育"
missing = client.put(
"/api/admin/edu/platforms",
headers=staff,
json={"items": [{"name": "省继续教育", "url": "https://example.com/edu", "sortOrder": 1}]},
)
assert missing.status_code == 400
assert "图片" in missing.text
script_url = client.put(
"/api/admin/edu/platforms",
headers=staff,
json={
"items": [
{
"name": "省继续教育",
"url": "javascript:alert(1)",
"imageFileId": 1,
"sortOrder": 1,
}
]
},
)
assert script_url.status_code == 400
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("platform.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
second = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("later.png", _png(), "image/png")},
)
assert second.status_code == 200, second.text
file_ids.append(second.json()["id"])
saved = client.put(
"/api/admin/edu/platforms",
headers=staff,
json={
"items": [
{
"name": "后配置的平台",
"url": "https://example.com/later",
"imageFileId": file_ids[1],
"sortOrder": 2,
},
{
"name": "甘肃省继续教育",
"url": "https://example.com/edu",
"imageFileId": file_ids[0],
"sortOrder": 1,
},
]
},
)
assert saved.status_code == 200, saved.text
admin_list = client.get("/api/admin/edu/platforms", headers=staff)
assert admin_list.status_code == 200, admin_list.text
assert [item["name"] for item in admin_list.json()["items"]] == [
"甘肃省继续教育",
"后配置的平台",
]
public = client.get("/api/site/edu/platforms")
assert public.status_code == 200, public.text
body = public.json()
assert "placeholder" not in body
assert [item["name"] for item in body["items"]] == ["甘肃省继续教育", "后配置的平台"]
first = body["items"][0]
assert first["url"] == "https://example.com/edu"
assert first["navigation"] == "newWindow"
assert first["imageUrl"]
assert "imageFileId" not in first
rejected = client.put(
"/api/admin/edu/platforms",
headers=_headers("member"),
json={"items": []},
)
assert rejected.status_code in (401, 403)
assert client.get("/api/site/edu/platforms").json()["items"][0]["name"] == "甘肃省继续教育"
shortcut = client.put(
"/api/admin/home/menu",
headers=staff,
json={
"items": [
{
"key": "edu",
"label": "继续教育",
"url": "https://example.com/edu",
"visible": True,
"sortOrder": 1,
}
]
},
)
assert shortcut.status_code == 400
labels = [item["label"] for item in client.get("/api/site/home").json()["shortcutMenu"]["items"]]
assert "继续教育" not in labels
_clear_notices(client, staff)
empty_notices = client.get("/api/site/about/articles/edu_notices")
assert empty_notices.status_code == 200, empty_notices.text
assert empty_notices.json()["placeholder"] == "暂无教育公告"
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "edu_notices",
"title": "内部培训草稿",
"published": False,
"bodyHtml": "<p>尚未公示</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
published = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "edu_notices",
"title": "2026年度培训计划",
"published": True,
"bodyHtml": "<p>线上与线下安排</p><script>alert(1)</script>",
"imageFileId": file_ids[0],
"attachmentFileIds": [],
},
)
assert published.status_code == 200, published.text
notices = client.get("/api/site/about/articles/edu_notices")
assert notices.status_code == 200, notices.text
titles = [item["title"] for item in notices.json()["items"]]
assert titles == ["2026年度培训计划"]
assert "内部培训草稿" not in notices.text
assert notices.json()["items"][0]["imageUrl"]
detail = client.get(f"/api/site/home/articles/{published.json()['id']}")
assert detail.status_code == 200, detail.text
assert "线上与线下安排" in detail.text
assert "script" not in detail.text
assert "alert" not in detail.text
home = client.get("/api/admin/home", headers=staff)
categories = {item["category"] for item in home.json()["articles"]}
assert "edu_notices" not in categories
finally:
client.put("/api/admin/edu/platforms", headers=staff, json={"items": []})
_clear_notices(client, staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+181
View File
@@ -0,0 +1,181 @@
"""专家答疑:会员提问、只读本人、工作人员回复、待回复计数与超时。"""
from datetime import datetime, timedelta
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
from app.models.expert import is_overdue, workday_deadline
from app.services.email_code import _key
from app.services.redis_client import get_redis
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
monkeypatch.setenv("SMTP_HOST", "")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
try:
get_redis().ping()
except Exception:
pytest.skip("Redis 不可达")
monkeypatch.setattr("app.services.email_code.send_email", lambda **kwargs: None)
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _code(purpose: str, email: str) -> str:
stored = get_redis().get(_key(purpose, email))
assert stored is not None
if isinstance(stored, bytes):
stored = stored.decode("utf-8")
return stored
def _register(client, email: str, password: str = "Passw0rd1") -> str:
assert client.post("/api/site/auth/email-code", json={"email": email, "purpose": "register"}).status_code == 200
code = _code("register", email)
registered = client.post(
"/api/site/auth/register",
json={"email": email, "code": code, "password": password, "privacyAccepted": True},
)
assert registered.status_code == 200, registered.text
return registered.json()["accessToken"]
def test_workday_deadline_skips_weekend():
# 周五提交,3 个工作日后是下周三
friday = datetime(2025, 1, 3, 10, 0, 0) # Friday
assert workday_deadline(friday, 3) == datetime(2025, 1, 8).date() # Wed
assert is_overdue(friday, 3, now=datetime(2025, 1, 8, 9, 0, 0)) is False
assert is_overdue(friday, 3, now=datetime(2025, 1, 9, 9, 0, 0)) is True
def test_expert_qa_ask_reply_isolation_and_pending_count(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
import time
email_a = f"qa-a-{int(time.time() * 1000)}@example.com"
email_b = f"qa-b-{int(time.time() * 1000)}@example.com"
token_a = _register(client, email_a)
token_b = _register(client, email_b)
headers_a = {"Authorization": f"Bearer {token_a}"}
headers_b = {"Authorization": f"Bearer {token_b}"}
staff = {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
denied = client.post(
"/api/site/member/expert-questions",
json={"title": "未登录", "body": "x", "attachmentFileIds": []},
)
assert denied.status_code in (401, 403)
uploaded = client.post(
"/api/site/member/files",
headers=headers_a,
files={"file": ("证据.pdf", b"%PDF-1.4\nqa", "application/pdf")},
)
assert uploaded.status_code == 200, uploaded.text
file_id = uploaded.json()["id"]
created = client.post(
"/api/site/member/expert-questions",
headers=headers_a,
json={
"title": "住宅估价流程咨询",
"body": "请问住宅估价需要哪些材料?",
"attachmentFileIds": [file_id],
},
)
assert created.status_code == 200, created.text
question_id = created.json()["id"]
mine = client.get("/api/site/member/expert-questions", headers=headers_a)
assert mine.status_code == 200, mine.text
assert mine.json()["items"][0]["title"] == "住宅估价流程咨询"
assert mine.json()["items"][0]["status"] == "pending"
other = client.get(f"/api/site/member/expert-questions/{question_id}", headers=headers_b)
assert other.status_code == 404
other_list = client.get("/api/site/member/expert-questions", headers=headers_b)
assert other_list.json()["items"] == []
pending = client.get("/api/admin/expert-questions/pending-count", headers=staff)
assert pending.status_code == 200, pending.text
assert pending.json()["count"] >= 1
listed = client.get("/api/admin/expert-questions?status=pending", headers=staff)
assert listed.status_code == 200, listed.text
assert any(item["id"] == question_id for item in listed.json()["items"])
member_reply = client.post(
f"/api/admin/expert-questions/{question_id}/reply",
headers=headers_a,
json={"bodyHtml": "<p>会员不得回复</p>", "attachmentFileIds": []},
)
assert member_reply.status_code in (401, 403)
replied = client.post(
f"/api/admin/expert-questions/{question_id}/reply",
headers=staff,
json={
"bodyHtml": "<p>请准备产权证与房屋平面图</p><script>alert(1)</script>",
"attachmentFileIds": [],
},
)
assert replied.status_code == 200, replied.text
detail = client.get(f"/api/site/member/expert-questions/{question_id}", headers=headers_a)
assert detail.status_code == 200, detail.text
assert detail.json()["status"] == "replied"
assert "产权证" in detail.json()["reply"]["bodyHtml"]
assert "script" not in detail.json()["reply"]["bodyHtml"].lower()
assert detail.json()["attachments"][0]["filename"] == "证据.pdf"
assert "contentType" in detail.json()["attachments"][0]
after = client.get("/api/admin/expert-questions/pending-count", headers=staff)
assert after.json()["count"] == pending.json()["count"] - 1
# 人为把另一条提问改成超时
overdue_created = client.post(
"/api/site/member/expert-questions",
headers=headers_a,
json={"title": "超时样例", "body": "等待回复", "attachmentFileIds": []},
)
assert overdue_created.status_code == 200, overdue_created.text
overdue_id = overdue_created.json()["id"]
from app.db import SessionLocal
from app.models.expert import ExpertQuestion
db = SessionLocal()
try:
row = db.get(ExpertQuestion, overdue_id)
row.created_at = datetime.now() - timedelta(days=14)
db.commit()
finally:
db.close()
admin_detail = client.get(f"/api/admin/expert-questions/{overdue_id}", headers=staff)
assert admin_detail.status_code == 200, admin_detail.text
assert admin_detail.json()["overdue"] is True
+58
View File
@@ -0,0 +1,58 @@
import base64
import hashlib
import pytest
from fastapi import HTTPException
from app.core.config import get_settings
from app.core.field_crypto import decrypt_text, encrypt_text
from app.core.masking import mask_id_card, mask_mobile
_ID_CARD = "620102199001011234"
_MOBILE = "13800138000"
def _use_key(monkeypatch, encoded: str) -> None:
monkeypatch.setenv("FIELD_AES_KEY", encoded)
get_settings.cache_clear()
def test_id_card_and_mobile_roundtrip(monkeypatch):
key = hashlib.sha256(b"field-crypto-test").digest()
assert len(key) == 32
_use_key(monkeypatch, base64.b64encode(key).decode("ascii"))
try:
token = encrypt_text(_ID_CARD)
assert token
assert token != _ID_CARD
assert decrypt_text(token) == _ID_CARD
assert mask_id_card(decrypt_text(token)) == "6201**********1234"
assert mask_id_card(_ID_CARD) == "6201**********1234"
mobile_token = encrypt_text(_MOBILE)
assert decrypt_text(mobile_token) == _MOBILE
assert mask_mobile(_MOBILE) == "138****8000"
assert encrypt_text("") == ""
assert decrypt_text("") == ""
finally:
get_settings.cache_clear()
def test_missing_or_short_field_key(monkeypatch):
try:
_use_key(monkeypatch, "")
assert encrypt_text("") == ""
with pytest.raises(HTTPException) as missing:
encrypt_text(_ID_CARD)
assert missing.value.status_code == 503
assert missing.value.detail == "字段加密未配置"
short_key = base64.b64encode(b"0123456789abcdef").decode("ascii")
_use_key(monkeypatch, short_key)
with pytest.raises(HTTPException) as short:
encrypt_text(_ID_CARD)
assert short.value.status_code == 503
assert short.value.detail == "字段加密未配置"
finally:
get_settings.cache_clear()
+52
View File
@@ -0,0 +1,52 @@
import base64
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from fastapi.testclient import TestClient
os.environ["JWT_SECRET"] = "test-secret-must-be-32-characters!"
os.environ["API_PAYLOAD_ENCRYPT"] = "false"
os.environ["API_PAYLOAD_AES_KEY"] = base64.b64encode(b"0123456789abcdef0123456789abcdef").decode()
from app.core.config import get_settings
from app.core.security import create_access_token
from app.main import create_app
get_settings.cache_clear()
def test_site_health_is_public():
client = TestClient(create_app())
response = client.get("/api/site/health")
assert response.status_code == 200
assert response.json()["scope"] == "site"
def test_admin_requires_staff_token():
client = TestClient(create_app())
assert client.get("/api/admin/health").status_code == 401
member = create_access_token("member-1", "member")
rejected = client.get("/api/admin/health", headers={"Authorization": f"Bearer {member}"})
assert rejected.status_code == 403
staff = create_access_token("staff-1", "staff")
accepted = client.get("/api/admin/health", headers={"Authorization": f"Bearer {staff}"})
assert accepted.status_code == 200
assert accepted.json()["subject"] == "staff-1"
def test_payload_encryption_roundtrip(monkeypatch):
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "true")
get_settings.cache_clear()
client = TestClient(create_app())
key = base64.b64decode(os.environ["API_PAYLOAD_AES_KEY"])
nonce = b"123456789012"
plain = b'{"ping":true}'
token = base64.b64encode(nonce + AESGCM(key).encrypt(nonce, plain, None)).decode()
response = client.post("/api/site/health", json={"data": token})
assert response.status_code == 405
body = response.json()
assert "data" in body
raw = base64.b64decode(body["data"])
decoded = AESGCM(key).decrypt(raw[:12], raw[12:], None)
assert b"Method Not Allowed" in decoded or "detail" in decoded.decode()
get_settings.cache_clear()
File diff suppressed because it is too large. Load diff
+273
View File
@@ -0,0 +1,273 @@
"""机构名录栏目文章:工作人员写入 → 门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _clear_category(client, staff: dict[str, str]) -> None:
listed = client.get("/api/admin/about/articles/institution_directories", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def test_institution_directory_publish_filter_placeholder_and_attachment(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
_clear_category(client, staff)
empty = client.get("/api/site/about/articles/institution_directories")
assert empty.status_code == 200, empty.text
assert "暂无机构名录" in empty.text
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("名录.pdf", b"%PDF-1.4\nroster", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "institution_directories",
"title": "甘肃省房地产价格评估行业协会单位会员名录(2025年6月)",
"publishedAt": "2025-06-05T08:00:00",
"published": True,
"bodyHtml": (
"<p>兰州市</p><table><tr><td>甘肃中瑞房地产资产评估有限公司</td></tr></table>"
"<script>alert(1)</script>"
),
"attachmentFileIds": [file_ids[0]],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "institution_directories",
"title": "未发布名录",
"publishedAt": "2025-06-06T08:00:00",
"published": False,
"bodyHtml": "<p>未发布名录</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
listed = client.get("/api/site/about/articles/institution_directories")
assert listed.status_code == 200, listed.text
assert "甘肃省房地产价格评估行业协会单位会员名录(2025年6月)" in listed.text
assert "未发布名录" not in listed.text
assert "暂无机构名录" not in listed.text
detail = client.get(f"/api/site/home/articles/{article_ids[0]}")
assert detail.status_code == 200, detail.text
body = detail.json()["bodyHtml"]
assert "甘肃中瑞房地产资产评估有限公司" in body
assert "table" in body.lower()
lowered = body.lower()
assert "script" not in lowered
assert "alert" not in lowered
assert [item["filename"] for item in detail.json()["attachments"]] == ["名录.pdf"]
hidden = client.get(f"/api/site/home/articles/{article_ids[1]}")
assert hidden.status_code == 404
editor = client.get("/api/admin/home", headers=staff)
assert editor.status_code == 200, editor.text
categories = {item["category"] for item in editor.json()["articles"]}
assert "institution_directories" not in categories
before = client.get("/api/site/about/articles/institution_directories").text
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "institution_directories",
"title": "会员不得发布名录",
"published": True,
"bodyHtml": "<p>会员不得发布名录</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
after = client.get("/api/site/about/articles/institution_directories")
assert after.text == before
assert "会员不得发布名录" not in after.text
renamed = client.put(
f"/api/admin/home/articles/{article_ids[0]}",
headers=staff,
json={
"category": "institution_directories",
"title": "甘肃省房地产价格评估行业协会单位会员名录(2025年6月修订)",
"publishedAt": "2025-06-05T08:00:00",
"published": True,
"bodyHtml": "<p>兰州市</p><table><tr><td>甘肃中瑞房地产资产评估有限公司</td></tr></table>",
"attachmentFileIds": [file_ids[0]],
},
)
assert renamed.status_code == 200, renamed.text
revised = client.get("/api/site/about/articles/institution_directories")
assert "单位会员名录(2025年6月修订)" in revised.text
assert "单位会员名录(2025年6月)" not in revised.text.replace("单位会员名录(2025年6月修订)", "")
deleted = client.delete(f"/api/admin/home/articles/{article_ids[0]}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
article_ids.remove(article_ids[0])
gone = client.get("/api/site/about/articles/institution_directories")
assert "单位会员名录(2025年6月修订)" not in gone.text
assert "暂无机构名录" in gone.text
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
def test_institution_directory_public_pagination(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
try:
_clear_category(client, staff)
for index in range(11):
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "institution_directories",
"title": f"名录分页样例-{index:02d}",
"publishedAt": f"2026-03-{index + 1:02d}T08:00:00",
"published": True,
"bodyHtml": f"<p>名录分页样例-{index:02d}</p>",
"attachmentFileIds": [],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
page1 = client.get("/api/site/about/articles/institution_directories?current=1&size=10")
assert page1.status_code == 200, page1.text
body1 = page1.json()
assert body1["total"] == 11
assert body1["current"] == 1
assert body1["size"] == 10
assert len(body1["items"]) == 10
assert body1["items"][0]["title"] == "名录分页样例-10"
page2 = client.get("/api/site/about/articles/institution_directories?current=2&size=10")
assert page2.status_code == 200, page2.text
body2 = page2.json()
assert body2["total"] == 11
assert body2["current"] == 2
assert len(body2["items"]) == 1
assert body2["items"][0]["title"] == "名录分页样例-00"
size20 = client.get("/api/site/about/articles/institution_directories?current=1&size=20")
assert size20.status_code == 200, size20.text
assert size20.json()["size"] == 20
assert len(size20.json()["items"]) == 11
bad_size = client.get("/api/site/about/articles/institution_directories?current=1&size=15")
assert bad_size.status_code == 200, bad_size.text
assert bad_size.json()["size"] == 10
assert len(bad_size.json()["items"]) == 10
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
PUBLISHED_TITLES = [
"甘肃省房地产价格评估行业协会单位会员名录(2025年6月)",
"甘肃省房地产价格评估行业协会个人会员名录(2025年5月)",
"甘肃省房地产价格评估行业协会个人会员名录(2023年6月)",
"甘肃省房地产价格评估行业协会单位会员名录(2023年6月)",
"甘肃省房地产价格评估行业协会估价师个人会员名录(2022年4月)",
"甘肃省房地产价格评估行业协会单位会员名录(2022年4月)",
"甘肃省房地产价格评估行业协会估价师个人会员名录(2021年7月)",
"甘肃省房地产价格评估行业协会估价师单位会员名录(2021年7月)",
"甘肃省房地产价格评估行业协会估价师个人会员名录(2021年5月)",
"甘肃省房地产价格评估行业协会单位会员名录(2021年5月)",
"甘肃省房地产价格评估行业协会估价师个人会员名录(2020年)",
"甘肃省房地产价格评估行业协会单位会员名录(2020年)",
"甘肃省最低收费备案标准名单",
"甘肃省住房和城乡建设厅关于公布甘肃省房地产估价机构名录的通知",
"甘肃省房地产价格评估行业协会单位会员名录",
"甘肃省房地产价格评估行业协会估价师个人会员名录(2019年)",
]
def test_institution_directory_import_keeps_titles_and_is_idempotent(client):
staff = _headers("staff")
from app.commands.import_institution_directories import import_institution_directories
from app.db import SessionLocal
db = SessionLocal()
try:
_clear_category(client, staff)
import_institution_directories(db)
listed = client.get("/api/site/about/articles/institution_directories?current=1&size=20")
assert listed.status_code == 200, listed.text
body = listed.json()
assert body["total"] == 16
assert [item["title"] for item in body["items"]] == PUBLISHED_TITLES
detail = client.get(f"/api/site/home/articles/{body['items'][0]['id']}")
assert detail.status_code == 200, detail.text
assert "甘肃中瑞房地产资产评估有限公司" in detail.json()["bodyHtml"]
assert "table" in detail.json()["bodyHtml"].lower()
import_institution_directories(db)
again = client.get("/api/site/about/articles/institution_directories?current=1&size=20")
assert again.status_code == 200, again.text
titles = [item["title"] for item in again.json()["items"]]
assert titles == PUBLISHED_TITLES
assert len(titles) == len(set(titles))
finally:
db.close()
_clear_category(client, staff)
+88
View File
@@ -0,0 +1,88 @@
"""合规正文:隐私政策 / 使用条款 / 网站声明。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _staff() -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
def test_legal_pages_publish_filter_placeholder_and_footer_links(client):
staff = _staff()
try:
for key, placeholder in (
("privacy", "隐私政策整理中"),
("terms", "使用条款整理中"),
("statement", "网站声明整理中"),
):
empty = client.get(f"/api/site/legal/{key}")
assert empty.status_code == 200, empty.text
assert placeholder in empty.text
home = client.get("/api/site/home")
assert home.status_code == 200, home.text
labels = [item["label"] for item in home.json()["compliance"]["links"]]
assert labels == ["隐私政策", "使用条款", "网站声明"]
assert all(item["navigation"] == "sameWindow" for item in home.json()["compliance"]["links"])
assert home.json()["compliance"]["links"][0]["url"] == "/legal/privacy"
assert "隐私政策、使用条款与网站声明整理中" not in home.text
saved = client.put(
"/api/admin/legal/privacy",
headers=staff,
json={
"published": True,
"bodyHtml": "<p>我们如何处理个人信息</p><script>alert(1)</script>",
},
)
assert saved.status_code == 200, saved.text
public = client.get("/api/site/legal/privacy")
assert public.status_code == 200, public.text
assert public.json()["title"] == "隐私政策"
assert "我们如何处理个人信息" in public.json()["bodyHtml"]
lowered = public.json()["bodyHtml"].lower()
assert "script" not in lowered
assert "alert" not in lowered
assert "隐私政策整理中" not in public.text
rejected = client.put(
"/api/admin/legal/privacy",
headers={"Authorization": f"Bearer {create_access_token('1', 'member')}"},
json={"published": True, "bodyHtml": "<p>会员不得改</p>"},
)
assert rejected.status_code in (401, 403)
assert "会员不得改" not in client.get("/api/site/legal/privacy").text
cleared = client.put(
"/api/admin/legal/privacy",
headers=staff,
json={"published": False, "bodyHtml": "<p></p>"},
)
assert cleared.status_code == 200, cleared.text
assert "隐私政策整理中" in client.get("/api/site/legal/privacy").text
finally:
for key in ("privacy", "terms", "statement"):
client.put(
f"/api/admin/legal/{key}",
headers=staff,
json={"published": False, "bodyHtml": "<p></p>"},
)
+226
View File
@@ -0,0 +1,226 @@
"""资料库:政策分类、标题与正文检索、案例库、未发布不可见。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def test_library_publish_kind_search_and_cases(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
empty_policy = client.get("/api/site/about/articles/policy_analyses")
assert empty_policy.status_code == 200, empty_policy.text
assert "暂无政策分析" in empty_policy.text
empty_cases = client.get("/api/site/about/articles/case_library")
assert empty_cases.status_code == 200, empty_cases.text
assert "暂无案例库" in empty_cases.text
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("cover.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("政策.pdf", b"%PDF-1.4\npolicy", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
published = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "policy_analyses",
"kind": "national",
"title": "资料库检索样例-民法典导读",
"published": True,
"publishedAt": "2025-09-12T08:00:00",
"bodyHtml": "<p>本条标注:现行有效。</p>",
"imageFileId": cover.json()["id"],
"attachmentFileIds": [pdf.json()["id"]],
},
)
assert published.status_code == 200, published.text
article_ids.append(published.json()["id"])
local = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "policy_analyses",
"kind": "local",
"title": "资料库检索样例-地方配套",
"published": True,
"publishedAt": "2025-03-08T08:00:00",
"bodyHtml": "<p>仅收录本地区政策。</p>",
"attachmentFileIds": [],
},
)
assert local.status_code == 200, local.text
article_ids.append(local.json()["id"])
hidden = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "policy_analyses",
"kind": "expert",
"title": "资料库检索样例-未发布解读",
"published": False,
"bodyHtml": "<p>正文里有未发布机密词。</p>",
"attachmentFileIds": [],
},
)
assert hidden.status_code == 200, hidden.text
article_ids.append(hidden.json()["id"])
bad_kind = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "policy_analyses",
"kind": "residential",
"title": "资料库检索样例-错误分类",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert bad_kind.status_code == 400
case_with_kind = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "case_library",
"kind": "national",
"title": "资料库检索样例-案例不分类",
"published": True,
"bodyHtml": "<p>案例正文</p>",
"attachmentFileIds": [],
},
)
assert case_with_kind.status_code == 400
case = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "case_library",
"title": "资料库检索样例-城关区案例",
"published": True,
"publishedAt": "2025-08-16T08:00:00",
"bodyHtml": "<p>可比案例说明。</p>",
"imageFileId": cover.json()["id"],
"attachmentFileIds": [pdf.json()["id"]],
},
)
assert case.status_code == 200, case.text
article_ids.append(case.json()["id"])
listed = client.get("/api/site/about/articles/policy_analyses")
titles = [item["title"] for item in listed.json()["items"]]
assert "资料库检索样例-民法典导读" in titles
assert "资料库检索样例-未发布解读" not in titles
national = next(item for item in listed.json()["items"] if item["title"] == "资料库检索样例-民法典导读")
assert national["kind"] == "national"
assert national["kindLabel"] == "国家级"
assert national["imageUrl"]
only_local = client.get("/api/site/about/articles/policy_analyses?kind=local")
assert [item["title"] for item in only_local.json()["items"]] == ["资料库检索样例-地方配套"]
by_title = client.get("/api/site/about/articles/policy_analyses?q=民法典")
assert [item["title"] for item in by_title.json()["items"]] == ["资料库检索样例-民法典导读"]
by_body = client.get("/api/site/about/articles/policy_analyses?q=现行有效")
assert [item["title"] for item in by_body.json()["items"]] == ["资料库检索样例-民法典导读"]
hidden_body = client.get("/api/site/about/articles/policy_analyses?q=未发布机密词")
assert hidden_body.json()["placeholder"] == "未找到相关政策"
assert hidden_body.json()["items"] == []
unknown = client.get("/api/site/about/articles/policy_analyses?kind=unknown")
assert unknown.status_code == 404
cases = client.get("/api/site/about/articles/case_library")
assert cases.json()["items"][0]["title"] == "资料库检索样例-城关区案例"
assert "kind" not in cases.json()["items"][0]
detail = client.get(f"/api/site/home/articles/{national['id']}")
assert detail.status_code == 200, detail.text
assert "现行有效" in detail.text
assert "政策.pdf" in detail.text
home = client.get("/api/admin/home", headers=staff)
categories = {item["category"] for item in home.json()["articles"]}
assert "policy_analyses" not in categories
assert "case_library" not in categories
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "policy_analyses",
"kind": "national",
"title": "会员不得发布政策",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+166
View File
@@ -0,0 +1,166 @@
"""门户邮箱账号:注册、登录、重置密码与令牌隔离。"""
from datetime import datetime, timezone
import jwt
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
from app.services.email_code import _key
from app.services.redis_client import get_redis
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
monkeypatch.setenv("SMTP_HOST", "")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
try:
get_redis().ping()
except Exception:
pytest.skip("Redis 不可达")
def _noop_send(**kwargs):
return None
monkeypatch.setattr("app.services.email_code.send_email", _noop_send)
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _code(purpose: str, email: str) -> str:
stored = get_redis().get(_key(purpose, email))
assert stored is not None, f"missing code for {purpose}/{email}"
if isinstance(stored, bytes):
stored = stored.decode("utf-8")
return stored
def _unique_email() -> str:
import time
return f"member-{int(time.time() * 1000)}@example.com"
def test_member_token_lasts_seven_days(client):
settings = get_settings()
token = create_access_token("42", "member")
payload = jwt.decode(token, settings.jwt_secret, algorithms=["HS256"])
exp = datetime.fromtimestamp(payload["exp"], tz=timezone.utc)
remaining = (exp - datetime.now(timezone.utc)).total_seconds()
assert remaining > 6.5 * 24 * 3600
assert remaining < 7.5 * 24 * 3600
def test_register_keeps_code_when_password_invalid(client):
"""弱密码拒收后,同一验证码仍可用于再次提交。"""
email = _unique_email()
sent = client.post("/api/site/auth/email-code", json={"email": email, "purpose": "register"})
assert sent.status_code == 200, sent.text
code = _code("register", email)
weak = client.post(
"/api/site/auth/register",
json={"email": email, "code": code, "password": "short", "privacyAccepted": True},
)
assert weak.status_code == 400, weak.text
assert "验证码" not in weak.json().get("detail", "")
registered = client.post(
"/api/site/auth/register",
json={"email": email, "code": code, "password": "Passw0rd1", "privacyAccepted": True},
)
assert registered.status_code == 200, registered.text
assert registered.json()["tokenType"] == "member"
def test_register_login_reset_and_token_isolation(client):
email = _unique_email()
password = "Passw0rd1"
new_password = "Passw0rd2"
no_privacy = client.post(
"/api/site/auth/register",
json={"email": email, "code": "000000", "password": password, "privacyAccepted": False},
)
assert no_privacy.status_code == 400
assert "隐私政策" in no_privacy.text
sent = client.post("/api/site/auth/email-code", json={"email": email, "purpose": "register"})
assert sent.status_code == 200, sent.text
code = _code("register", email)
registered = client.post(
"/api/site/auth/register",
json={"email": email, "code": code, "password": password, "privacyAccepted": True},
)
assert registered.status_code == 200, registered.text
token = registered.json()["accessToken"]
assert registered.json()["tokenType"] == "member"
me = client.get("/api/site/member/me", headers={"Authorization": f"Bearer {token}"})
assert me.status_code == 200, me.text
assert me.json()["email"] == email.lower()
again = client.post("/api/site/auth/email-code", json={"email": email, "purpose": "register"})
assert again.status_code == 400
bad_login = client.post(
"/api/site/auth/login",
json={"email": email, "password": "WrongPass1"},
)
assert bad_login.status_code == 401
login = client.post(
"/api/site/auth/login",
json={"email": email, "password": password},
)
assert login.status_code == 200, login.text
login_token = login.json()["accessToken"]
reset_sent = client.post("/api/site/auth/email-code", json={"email": email, "purpose": "reset"})
assert reset_sent.status_code == 200, reset_sent.text
# 上一发可能还在 60s 频控内;若失败则直接用 redis 写入
if reset_sent.status_code == 200:
reset_code = _code("reset", email)
else:
pytest.fail(reset_sent.text)
# 若仍被频控挡住了第一次 reset 请求以外的路径,上面已成功
reset = client.post(
"/api/site/auth/reset-password",
json={"email": email, "code": reset_code, "password": new_password},
)
assert reset.status_code == 200, reset.text
old_login = client.post(
"/api/site/auth/login",
json={"email": email, "password": password},
)
assert old_login.status_code == 401
new_login = client.post(
"/api/site/auth/login",
json={"email": email, "password": new_password},
)
assert new_login.status_code == 200, new_login.text
member_on_admin = client.get(
"/api/admin/home",
headers={"Authorization": f"Bearer {login_token}"},
)
assert member_on_admin.status_code in (401, 403)
staff_on_member = client.get(
"/api/site/member/me",
headers={"Authorization": f"Bearer {create_access_token('1', 'staff')}"},
)
assert staff_on_member.status_code in (401, 403)
+224
View File
@@ -0,0 +1,224 @@
"""行业党建:支部介绍单篇 + 党建活动栏目文章。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _clear_category(client, staff: dict[str, str], category: str) -> None:
listed = client.get(f"/api/admin/about/articles/{category}", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def test_party_branch_page_and_activities(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
_clear_category(client, staff, "party_activities")
empty_page = client.get("/api/site/about/pages/party_branch")
assert empty_page.status_code == 200, empty_page.text
assert "协会党支部介绍整理中" in empty_page.text
empty_list = client.get("/api/site/about/articles/party_activities")
assert empty_list.status_code == 200, empty_list.text
assert "暂无党建活动" in empty_list.text
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("党支部制度.pdf", b"%PDF-1.4\ncharter", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
saved_page = client.put(
"/api/admin/about/pages/party_branch",
headers=staff,
json={
"published": True,
"bodyHtml": "<p>党建引领行业发展</p><script>alert(1)</script>",
"attachmentFileIds": [file_ids[0]],
},
)
assert saved_page.status_code == 200, saved_page.text
public_page = client.get("/api/site/about/pages/party_branch")
assert public_page.status_code == 200, public_page.text
assert "党建引领行业发展" in public_page.json()["bodyHtml"]
lowered = public_page.json()["bodyHtml"].lower()
assert "script" not in lowered
assert "alert" not in lowered
assert [item["filename"] for item in public_page.json()["attachments"]] == ["党支部制度.pdf"]
assert "协会党支部介绍整理中" not in public_page.text
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("cover.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
activity_pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("学习纪要.pdf", b"%PDF-1.4\nnotes", "application/pdf")},
)
assert activity_pdf.status_code == 200, activity_pdf.text
file_ids.append(activity_pdf.json()["id"])
published = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "party_activities",
"title": "主题党日:学习估价行业诚信自律要求",
"publishedAt": "2025-10-12T08:00:00",
"published": True,
"bodyHtml": "<p>主题党日学习</p><script>alert(1)</script>",
"imageFileId": file_ids[1],
"attachmentFileIds": [file_ids[2]],
},
)
assert published.status_code == 200, published.text
article_ids.append(published.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "party_activities",
"title": "内部筹备党建活动",
"publishedAt": "2025-10-13T08:00:00",
"published": False,
"bodyHtml": "<p>内部</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
listed = client.get("/api/site/about/articles/party_activities")
assert listed.status_code == 200, listed.text
assert "主题党日:学习估价行业诚信自律要求" in listed.text
assert "内部筹备党建活动" not in listed.text
assert listed.json()["items"][0].get("imageUrl")
detail = client.get(f"/api/site/home/articles/{article_ids[0]}")
assert detail.status_code == 200, detail.text
assert "主题党日学习" in detail.json()["bodyHtml"]
body = detail.json()["bodyHtml"].lower()
assert "script" not in body
assert detail.json().get("imageUrl")
assert [item["filename"] for item in detail.json()["attachments"]] == ["学习纪要.pdf"]
assert client.get(f"/api/site/home/articles/{article_ids[1]}").status_code == 404
for index in range(10):
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "party_activities",
"title": f"党建分页样例-{index:02d}",
"publishedAt": f"2025-01-{index + 1:02d}T08:00:00",
"published": True,
"bodyHtml": f"<p>党建分页样例-{index:02d}</p>",
"attachmentFileIds": [],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
page1 = client.get("/api/site/about/articles/party_activities?current=1&size=10")
assert page1.json()["total"] == 11
assert page1.json()["size"] == 10
assert len(page1.json()["items"]) == 10
assert len(client.get("/api/site/about/articles/party_activities?current=2&size=10").json()["items"]) == 1
assert client.get("/api/site/about/articles/party_activities?current=1&size=20").json()["size"] == 20
assert client.get("/api/site/about/articles/party_activities?current=1&size=15").json()["size"] == 10
home = client.get("/api/admin/home", headers=staff)
assert home.status_code == 200, home.text
categories = {item["category"] for item in home.json()["articles"]}
assert "party_activities" not in categories
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "party_activities",
"title": "会员不得发布党建",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
assert "会员不得发布党建" not in client.get("/api/site/about/articles/party_activities").text
emptied = client.put(
"/api/admin/about/pages/party_branch",
headers=staff,
json={"published": False, "bodyHtml": "<p></p>", "attachmentFileIds": []},
)
assert emptied.status_code == 200, emptied.text
assert "协会党支部介绍整理中" in client.get("/api/site/about/pages/party_branch").text
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
client.put(
"/api/admin/about/pages/party_branch",
headers=staff,
json={"published": False, "bodyHtml": "<p></p>", "attachmentFileIds": []},
)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+721
View File
@@ -0,0 +1,721 @@
import importlib
import os
import re
import sys
import types
import uuid
import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient
from sqlalchemy import delete, select, text, update
from sqlalchemy.orm import Session
os.environ["JWT_SECRET"] = "test-secret-must-be-32-characters!"
os.environ["API_PAYLOAD_ENCRYPT"] = "false"
PASSWORD_RULE = "密码至少 8 位,且同时包含字母和数字"
LOGIN_FAILURE = "用户名或密码错误"
KEEP_SELF = "不能停用或注销当前登录用户"
KEEP_FULL_ADMIN = "至少保留一名拥有全部系统菜单的正常用户"
def _install_stub(module_name: str, **attrs: object) -> None:
try:
module = importlib.import_module(module_name)
except Exception:
sys.modules.pop(module_name, None)
module = types.ModuleType(module_name)
sys.modules[module_name] = module
for key, value in attrs.items():
setattr(module, key, value)
return
for key, value in attrs.items():
if not hasattr(module, key):
setattr(module, key, value)
def _encrypt_text(value: str) -> str:
return f"enc:{value}"
def _consume_captcha(captcha_id: str, code: str) -> bool:
return False
def _is_currently_locked(user) -> bool:
return False
def _record_failure(db, user) -> None:
user.failed_login_count = int(user.failed_login_count or 0) + 1
def _clear_failures(db, user) -> None:
user.failed_login_count = 0
user.locked_until = None
_install_stub("app.core.field_crypto", encrypt_text=_encrypt_text)
_install_stub("app.services.captcha", consume_captcha=_consume_captcha)
_install_stub(
"app.services.login_guard",
is_currently_locked=_is_currently_locked,
record_failure=_record_failure,
clear_failures=_clear_failures,
)
from app.api.admin.rbac import public_router, router
from app.commands.create_superuser import seed_superuser
from app.core.config import get_settings
from app.core.masking import mask_mobile
from app.core.security import create_access_token
from app.db import Base, get_db, get_engine
from app.main import create_app
from app.models.rbac import AdminResource, AdminRole, AdminRoleResource, AdminUser, AdminUserRole, utcnow
from app.services.rbac import count_full_admins, preserve_full_admin
get_settings.cache_clear()
def _safe_error(exc: Exception) -> str:
raw = str(exc).splitlines()[0] if str(exc) else ""
raw = re.sub(r"://\S+", "://***", raw)
raw = re.sub(r"password=\S+", "password=***", raw, flags=re.I)
return f"{exc.__class__.__name__}: {raw[:180]}"
def _database_url() -> str:
get_settings.cache_clear()
return get_settings().database_url.strip()
def _suffix(prefix: str) -> str:
return f"{prefix}_{uuid.uuid4().hex[:10]}"
def _staff_headers(subject: str = "1") -> dict[str, str]:
token = create_access_token(subject, "staff")
return {"Authorization": f"Bearer {token}"}
def _mount(app) -> None:
paths = {getattr(route, "path", "") for route in app.routes}
if "/api/admin/users" not in paths:
app.include_router(public_router, prefix="/api/admin")
app.include_router(router, prefix="/api/admin")
def _committed(username: str) -> bool:
other = Session(bind=get_engine())
try:
found = other.scalar(select(AdminUser.id).where(AdminUser.username == username))
return found is not None
finally:
other.close()
def _delete_committed_user(username: str) -> None:
other = Session(bind=get_engine())
try:
row = other.scalar(select(AdminUser).where(AdminUser.username == username))
if row is None:
return
other.execute(delete(AdminUserRole).where(AdminUserRole.user_id == row.id))
other.delete(row)
other.commit()
finally:
other.close()
def _assert_isolated(connection, username: str) -> None:
probe = Session(
bind=connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
now = utcnow()
probe.add(
AdminUser(
username=username,
password_hash="probe",
display_name="probe",
mobile_mask="",
status="active",
failed_login_count=0,
created_at=now,
updated_at=now,
)
)
probe.commit()
probe.close()
if _committed(username):
_delete_committed_user(username)
pytest.fail("测试事务没有隔离,已停止,避免改动已有数据")
@pytest.fixture
def client():
if not _database_url():
pytest.skip("DATABASE_URL 未配置")
os.environ["API_PAYLOAD_ENCRYPT"] = "false"
get_settings.cache_clear()
try:
engine = get_engine()
with engine.connect() as probe:
probe.execute(text("SELECT 1"))
Base.metadata.create_all(bind=engine)
except Exception as exc:
pytest.skip(f"数据库不可用:{_safe_error(exc)}")
connection = engine.connect()
transaction = connection.begin()
probe_name = _suffix("probe")
try:
_assert_isolated(connection, probe_name)
app = create_app()
_mount(app)
app.state.connection = connection
def override_db():
db = Session(
bind=connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_db
with TestClient(app) as test_client:
yield test_client
finally:
try:
transaction.rollback()
except Exception:
pass
connection.close()
def _walk(nodes: list[dict]):
for node in nodes:
yield node
yield from _walk(node.get("children") or [])
def _no_password(payload) -> None:
if isinstance(payload, dict):
for key, value in payload.items():
assert "password" not in key.lower()
assert key not in {"mobileCipher", "mobile_cipher", "password_hash"}
_no_password(value)
elif isinstance(payload, list):
for item in payload:
_no_password(item)
def test_users_requires_staff_token(client: TestClient):
missing = client.get("/api/admin/users")
assert missing.status_code == 401
member = create_access_token("member-1", "member")
rejected = client.get("/api/admin/users", headers={"Authorization": f"Bearer {member}"})
assert rejected.status_code == 403
def test_weak_password_rejected(client: TestClient):
headers = _staff_headers()
username = _suffix("weak")
response = client.post(
"/api/admin/users",
headers=headers,
json={
"username": username,
"password": "abcdefgh",
"displayName": "弱密码",
"roleIds": [],
},
)
assert response.status_code == 400
assert response.json()["detail"] == PASSWORD_RULE
digits = client.post(
"/api/admin/users",
headers=headers,
json={
"username": username,
"password": "12345678",
"displayName": "弱密码",
"roleIds": [],
},
)
assert digits.status_code == 400
assert digits.json()["detail"] == PASSWORD_RULE
def test_cannot_cancel_self(client: TestClient):
headers = _staff_headers("0")
username = _suffix("self")
created = client.post(
"/api/admin/users",
headers=headers,
json={
"username": username,
"password": "Abcdef12",
"displayName": "本人",
"roleIds": [],
},
)
assert created.status_code == 200
user_id = created.json()["id"]
own = _staff_headers(str(user_id))
cancelled = client.put(
f"/api/admin/users/{user_id}",
headers=own,
json={"displayName": "本人", "status": "cancelled", "roleIds": []},
)
assert cancelled.status_code == 400
assert cancelled.json()["detail"] == KEEP_SELF
listed = client.get("/api/admin/users", headers=headers, params={"username": username})
assert listed.status_code == 200
record = next(item for item in listed.json()["records"] if item["username"] == username)
assert record["status"] == "active"
def test_user_list_masks_mobile_and_hides_password(client: TestClient, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr("app.services.rbac.encrypt_text", lambda value: "cipher-text")
headers = _staff_headers()
username = _suffix("mobile")
mobile = "13812348000"
password = "Abcdef12"
created = client.post(
"/api/admin/users",
headers=headers,
json={
"username": username,
"password": password,
"displayName": "脱敏",
"mobile": mobile,
"roleIds": [],
},
)
assert created.status_code == 200
created_body = created.json()
assert created_body["mobileMask"] == mask_mobile(mobile) == "138****8000"
_no_password(created_body)
assert mobile not in created.text
assert password not in created.text
assert "cipher-text" not in created.text
listed = client.get("/api/admin/users", headers=headers, params={"username": username})
assert listed.status_code == 200
body = listed.json()
record = next(item for item in body["records"] if item["username"] == username)
assert record["mobileMask"] == "138****8000"
assert set(record) >= {
"id",
"username",
"displayName",
"mobileMask",
"status",
"roleIds",
"createdAt",
"updatedAt",
}
_no_password(body)
assert mobile not in listed.text
assert password not in listed.text
assert "cipher-text" not in listed.text
assert not _committed(username)
def test_login_hides_reason(client: TestClient, monkeypatch: pytest.MonkeyPatch):
failures: list[int] = []
clears: list[int] = []
def consume(captcha_id: str, code: str) -> bool:
return code == "ok"
def record(db, user) -> None:
failures.append(user.id)
def clear(db, user) -> None:
clears.append(user.id)
user.failed_login_count = 0
user.locked_until = None
locked = {"value": False}
monkeypatch.setattr("app.services.rbac.consume_captcha", consume)
monkeypatch.setattr("app.services.rbac.record_failure", record)
monkeypatch.setattr("app.services.rbac.clear_failures", clear)
monkeypatch.setattr("app.services.rbac.is_currently_locked", lambda user: locked["value"])
headers = _staff_headers()
username = _suffix("login")
password = "Abcdef12"
created = client.post(
"/api/admin/users",
headers=headers,
json={"username": username, "password": password, "displayName": "登录", "roleIds": []},
)
assert created.status_code == 200
missing_user = client.post(
"/api/admin/auth/login",
json={"username": _suffix("none"), "password": password, "captchaId": "c1", "captchaCode": "ok"},
)
assert missing_user.status_code == 401
assert missing_user.json()["detail"] == LOGIN_FAILURE
assert failures == []
bad_captcha = client.post(
"/api/admin/auth/login",
json={"username": username, "password": password, "captchaId": "c1", "captchaCode": "bad"},
)
assert bad_captcha.status_code == 401
assert bad_captcha.json()["detail"] == LOGIN_FAILURE
assert len(failures) == 1
bad_password = client.post(
"/api/admin/auth/login",
json={"username": username, "password": "Wrongpass1", "captchaId": "c1", "captchaCode": "ok"},
)
assert bad_password.status_code == 401
assert bad_password.json()["detail"] == LOGIN_FAILURE
assert len(failures) == 2
locked["value"] = True
locked_response = client.post(
"/api/admin/auth/login",
json={"username": username, "password": password, "captchaId": "c1", "captchaCode": "ok"},
)
assert locked_response.status_code == 401
assert locked_response.json()["detail"] == LOGIN_FAILURE
assert len(failures) == 2
locked["value"] = False
success = client.post(
"/api/admin/auth/login",
json={"username": username, "password": password, "captchaId": "c1", "captchaCode": "ok"},
)
assert success.status_code == 200
payload = success.json()
assert payload["user"]["username"] == username
assert payload["user"]["displayName"] == "登录"
assert isinstance(payload["menus"], list)
assert isinstance(payload["permissions"], list)
assert payload["token"]
_no_password(payload)
assert clears == [created.json()["id"]]
def test_login_menu_excludes_buttons(client: TestClient, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr("app.services.rbac.consume_captcha", lambda captcha_id, code: True)
monkeypatch.setattr("app.services.rbac.is_currently_locked", lambda user: False)
monkeypatch.setattr("app.services.rbac.record_failure", lambda db, user: None)
monkeypatch.setattr("app.services.rbac.clear_failures", lambda db, user: None)
headers = _staff_headers()
mark = uuid.uuid4().hex[:8]
directory = client.post(
"/api/admin/resources",
headers=headers,
json={
"type": "directory",
"name": f"Dir{mark}",
"title": "目录",
"path": f"/t-{mark}",
"sort": 2,
"visible": True,
"status": "active",
},
)
assert directory.status_code == 200
directory_id = directory.json()["id"]
later = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": directory_id,
"type": "menu",
"name": f"Later{mark}",
"title": "后",
"path": f"/t-{mark}/later",
"component": f"/t-{mark}/later",
"sort": 2,
"status": "active",
},
)
earlier = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": directory_id,
"type": "menu",
"name": f"Early{mark}",
"title": "先",
"path": f"/t-{mark}/early",
"component": f"/t-{mark}/early",
"sort": 1,
"status": "active",
},
)
hidden = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": directory_id,
"type": "menu",
"name": f"Off{mark}",
"title": "停用页",
"path": f"/t-{mark}/off",
"component": f"/t-{mark}/off",
"sort": 3,
"status": "disabled",
},
)
button_z = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": earlier.json()["id"],
"type": "button",
"name": f"b:z:{mark}",
"title": "乙",
"permission": f"b:z:{mark}",
"visible": False,
"status": "active",
},
)
button_a = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": earlier.json()["id"],
"type": "button",
"name": f"b:a:{mark}",
"title": "甲",
"permission": f"b:a:{mark}",
"visible": False,
"status": "active",
},
)
assert later.status_code == earlier.status_code == hidden.status_code == 200
assert button_z.status_code == button_a.status_code == 200
role = client.post(
"/api/admin/roles",
headers=headers,
json={"code": f"R_{mark}", "name": "菜单角色", "description": ""},
)
assert role.status_code == 200
role_id = role.json()["id"]
disabled_role = client.post(
"/api/admin/roles",
headers=headers,
json={"code": f"R_OFF_{mark}", "name": "停用角色"},
)
assert disabled_role.status_code == 200
resource_ids = [
directory_id,
later.json()["id"],
earlier.json()["id"],
button_a.json()["id"],
button_z.json()["id"],
]
replaced = client.put(
f"/api/admin/roles/{role_id}/resources",
headers=headers,
json={"resourceIds": resource_ids},
)
assert replaced.status_code == 200
client.put(
f"/api/admin/roles/{disabled_role.json()['id']}",
headers=headers,
json={"name": "停用角色", "description": "", "status": "disabled"},
)
extra_button = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": earlier.json()["id"],
"type": "button",
"name": f"b:off:{mark}",
"title": "停用角色按钮",
"permission": f"b:off:{mark}",
"visible": False,
"status": "active",
},
)
client.put(
f"/api/admin/roles/{disabled_role.json()['id']}/resources",
headers=headers,
json={"resourceIds": [extra_button.json()["id"]]},
)
username = _suffix("menu")
created = client.post(
"/api/admin/users",
headers=headers,
json={
"username": username,
"password": "Abcdef12",
"displayName": "菜单",
"roleIds": [role_id, disabled_role.json()["id"]],
},
)
assert created.status_code == 200
logged = client.post(
"/api/admin/auth/login",
json={"username": username, "password": "Abcdef12", "captchaId": "c", "captchaCode": "1"},
)
assert logged.status_code == 200
body = logged.json()
nodes = list(_walk(body["menus"]))
assert [node["type"] for node in nodes if node["type"] == "button"] == []
titles = [node["title"] for node in nodes]
assert "停用页" not in titles
children = body["menus"][0]["children"]
assert [item["sort"] for item in children] == [1, 2]
assert body["permissions"] == [f"b:a:{mark}", f"b:z:{mark}"]
assert f"b:off:{mark}" not in body["permissions"]
def test_delete_resource_with_children(client: TestClient):
headers = _staff_headers()
mark = uuid.uuid4().hex[:8]
parent = client.post(
"/api/admin/resources",
headers=headers,
json={"type": "directory", "name": f"P{mark}", "title": "父", "sort": 1, "status": "active"},
)
assert parent.status_code == 200
child = client.post(
"/api/admin/resources",
headers=headers,
json={
"parentId": parent.json()["id"],
"type": "menu",
"name": f"C{mark}",
"title": "子",
"path": f"/c-{mark}",
"component": f"/c-{mark}",
"status": "active",
},
)
assert child.status_code == 200
denied = client.delete(f"/api/admin/resources/{parent.json()['id']}", headers=headers)
assert denied.status_code == 400
assert denied.json()["detail"] == "存在子节点,不能删除"
removed = client.delete(f"/api/admin/resources/{child.json()['id']}", headers=headers)
assert removed.status_code == 200
removed_parent = client.delete(f"/api/admin/resources/{parent.json()['id']}", headers=headers)
assert removed_parent.status_code == 200
def test_preserve_last_full_admin(client: TestClient):
connection = client.app.state.connection
db = Session(
bind=connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
nested = db.begin_nested()
try:
db.execute(update(AdminUser).values(status="disabled"))
db.flush()
db.expire_all()
assert count_full_admins(db) == 0
def make_user(tag: str) -> AdminUser:
now = utcnow()
role = AdminRole(code=_suffix("RF"), name=tag, status="active", created_at=now, updated_at=now)
user = AdminUser(
username=_suffix(tag),
password_hash="x",
display_name=tag,
mobile_mask="",
status="active",
failed_login_count=0,
created_at=now,
updated_at=now,
)
db.add_all([role, user])
db.flush()
for resource_id in db.scalars(select(AdminResource.id).where(AdminResource.status == "active")).all():
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
db.add(AdminUserRole(user_id=user.id, role_id=role.id))
db.flush()
return user
first = make_user("fulla")
second = make_user("fullb")
db.expire_all()
assert count_full_admins(db) == 2
def disable_first() -> None:
row = db.get(AdminUser, first.id)
assert row is not None
row.status = "disabled"
preserve_full_admin(db, disable_first)
db.expire_all()
assert count_full_admins(db) == 1
def disable_last() -> None:
row = db.get(AdminUser, second.id)
assert row is not None
row.status = "disabled"
with pytest.raises(HTTPException) as caught:
preserve_full_admin(db, disable_last)
assert caught.value.detail == KEEP_FULL_ADMIN
finally:
nested.rollback()
db.close()
def test_seed_superuser_is_idempotent(client: TestClient):
connection = client.app.state.connection
db = Session(
bind=connection,
autoflush=False,
expire_on_commit=False,
join_transaction_mode="create_savepoint",
)
username = _suffix("boot")
try:
seed_superuser(db, username, "Seedpass1")
seed_superuser(db, username, "Seedpass1")
db.commit()
users = db.scalars(select(AdminUser).where(AdminUser.username == username)).all()
assert len(users) == 1
role = db.scalar(select(AdminRole).where(AdminRole.code == "R_SUPER"))
assert role is not None
assert role.name == "超级管理员"
directory = db.scalar(
select(AdminResource).where(AdminResource.parent_id.is_(None), AdminResource.name == "System")
)
assert directory is not None
assert directory.path == "/system"
assert directory.icon == "ri:settings-3-line"
page = db.scalar(select(AdminResource).where(AdminResource.parent_id == directory.id, AdminResource.name == "User"))
assert page is not None
assert page.component == "/system/user"
button = db.scalar(
select(AdminResource).where(AdminResource.parent_id == page.id, AdminResource.name == "user:add")
)
assert button is not None
assert button.type == "button"
assert button.permission == "user:add"
assert button.visible is False
linked = db.get(AdminUserRole, (users[0].id, role.id))
assert linked is not None
finally:
db.close()
assert not _committed(username)
+173
View File
@@ -0,0 +1,173 @@
"""报告备案对照,以及首页报告查询、报告审核固定打开站内页。"""
from uuid import uuid4
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
FOUND = "以出具机构数据为准,协会结果仅供参考。"
MISSING = "协会备案库没有该编号,请向出具机构核实。"
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _filing(number: str, *, published: bool, institution: str = "兰州示例估价") -> dict:
return {
"institutionName": institution,
"reportNumber": number,
"issuedOn": "2026-03-18",
"published": published,
}
def test_public_query_reads_only_published_filings(client: TestClient):
staff = _headers("staff")
member = _headers("member")
number = f"GS-{uuid4().hex[:10]}"
other = f"GS-{uuid4().hex[:10]}"
filing_id = None
other_id = None
try:
body = _filing(f" {number} ", published=False, institution=" 兰州示例估价 ")
assert client.post("/api/admin/reports", json=body).status_code == 401
assert client.post("/api/admin/reports", headers=member, json=body).status_code == 403
created = client.post("/api/admin/reports", headers=staff, json=body)
assert created.status_code == 200, created.text
filing_id = created.json()["id"]
hidden = client.get("/api/site/reports/query", params={"number": number})
assert hidden.status_code == 200, hidden.text
assert hidden.json() == {"found": False, "notice": MISSING}
assert "兰州示例估价" not in hidden.text
assert "真" not in hidden.text
assert "伪" not in hidden.text
published = client.put(
f"/api/admin/reports/{filing_id}",
headers=staff,
json=_filing(number, published=True),
)
assert published.status_code == 200, published.text
found = client.get("/api/site/reports/query", params={"number": number})
assert found.json() == {
"found": True,
"institutionName": "兰州示例估价",
"reportNumber": number,
"issuedOn": "2026-03-18",
"notice": FOUND,
}
assert "真" not in found.text
assert "伪" not in found.text
duplicate = client.post("/api/admin/reports", headers=staff, json=_filing(number, published=True))
assert duplicate.status_code == 400
assert duplicate.json()["detail"] == "报告编号已存在"
second = client.post("/api/admin/reports", headers=staff, json=_filing(other, published=True))
assert second.status_code == 200, second.text
other_id = second.json()["id"]
clash = client.put(
f"/api/admin/reports/{filing_id}",
headers=staff,
json=_filing(other, published=True),
)
assert clash.status_code == 400
assert clash.json()["detail"] == "报告编号已存在"
blank = client.get("/api/site/reports/query", params={"number": " "})
assert blank.status_code == 400
assert blank.json()["detail"] == "请填写报告编号"
listed = client.get("/api/admin/reports", headers=staff)
assert listed.status_code == 200
assert any(item["id"] == filing_id and item["published"] is True for item in listed.json()["items"])
assert client.get("/api/admin/reports", headers=member).status_code == 403
finally:
for item_id in (filing_id, other_id):
if item_id is not None:
client.delete(f"/api/admin/reports/{item_id}", headers=staff)
gone = client.get("/api/site/reports/query", params={"number": number})
assert gone.json()["found"] is False
def test_hot_links_open_report_pages_on_site(client: TestClient):
staff = _headers("staff")
before = client.get("/api/admin/home", headers=staff).json()["hotLinks"]["links"]
hidden = [
{"key": "reportQuery", "label": "报告查询", "url": "/reports/query", "visible": False, "sortOrder": 0},
{"key": "reportReview", "label": "报告审核", "url": "/reports/review", "visible": False, "sortOrder": 1},
{"key": "complaint", "label": "投诉举报", "url": "", "visible": False, "sortOrder": 2},
]
try:
saved = client.put(
"/api/admin/home/hot-links",
headers=staff,
json={
"links": [
{
"key": "reportReview",
"label": "辅助审核",
"url": "https://example.com/review",
"visible": True,
"sortOrder": 0,
},
{
"key": "complaint",
"label": "投诉举报",
"url": "https://example.com/complaint",
"visible": True,
"sortOrder": 1,
},
{
"key": "reportQuery",
"label": "查备案",
"url": "https://example.com/report-check",
"visible": True,
"sortOrder": 2,
},
]
},
)
assert saved.status_code == 200, saved.text
home = client.get("/api/site/home")
assert home.json()["hotLinks"]["links"] == [
{"label": "辅助审核", "url": "/reports/review", "navigation": "sameWindow"},
{"label": "投诉举报", "url": "https://example.com/complaint", "navigation": "newWindow"},
{"label": "查备案", "url": "/reports/query", "navigation": "sameWindow"},
]
assert "example.com/report-check" not in home.text
assert "example.com/review" not in home.text
rejected = client.put(
"/api/admin/home/hot-links",
headers=staff,
json={"links": [{"key": "reportQuery", "label": "报告查询", "url": "/reports/query", "visible": True, "sortOrder": 0}]},
)
assert rejected.status_code == 400
cleared = client.put("/api/admin/home/hot-links", headers=staff, json={"links": hidden})
assert cleared.status_code == 200, cleared.text
assert client.get("/api/site/home").json()["hotLinks"]["placeholder"] == "报告查询、报告审核与投诉举报入口即将开放"
finally:
restore = before or hidden
client.put("/api/admin/home/hot-links", headers=staff, json={"links": restore})
+228
View File
@@ -0,0 +1,228 @@
import base64
import inspect
from datetime import datetime, timedelta, timezone
import pytest
def test_captcha_missing_wrong_and_second_use():
from app.services.captcha import CAPTCHA_ALPHABET, consume_captcha, issue_captcha
from app.services.redis_client import get_redis
assert consume_captcha("", "ab12") is False
assert consume_captcha("missing-id", "") is False
assert consume_captcha("", "") is False
try:
client = get_redis()
client.ping()
except Exception:
pytest.skip("Redis 不可达")
wrong = issue_captcha()
wrong_id = wrong["captchaId"]
assert wrong["image"].startswith("data:image/png;base64,")
raw = base64.b64decode(wrong["image"].split(",", 1)[1])
assert raw.startswith(b"\x89PNG")
stored = client.get(f"gsfdc:captcha:{wrong_id}")
assert isinstance(stored, str)
assert len(stored) == 4
assert set(stored).issubset(set(CAPTCHA_ALPHABET.lower()))
ttl = client.ttl(f"gsfdc:captcha:{wrong_id}")
assert 0 < ttl <= 120
assert consume_captcha(wrong_id, "0000") is False
assert client.get(f"gsfdc:captcha:{wrong_id}") is None
assert consume_captcha(wrong_id, stored) is False
ok = issue_captcha()
ok_id = ok["captchaId"]
stored_ok = client.get(f"gsfdc:captcha:{ok_id}")
assert consume_captcha(ok_id, stored_ok.upper()) is True
assert consume_captcha(ok_id, stored_ok) is False
def test_is_currently_locked_respects_utc_and_does_not_mutate():
from types import SimpleNamespace
from app.services.login_guard import is_currently_locked
user = SimpleNamespace(failed_login_count=2, locked_until=None)
assert is_currently_locked(user) is False
assert user.failed_login_count == 2
user.locked_until = datetime.now(timezone.utc) + timedelta(minutes=1)
assert is_currently_locked(user) is True
assert user.failed_login_count == 2
user.locked_until = datetime.now(timezone.utc) - timedelta(seconds=1)
assert is_currently_locked(user) is False
user.locked_until = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(seconds=1)
assert is_currently_locked(user) is False
assert user.failed_login_count == 2
def test_lock_after_small_limit_and_past_deadline():
pytest.importorskip("app.db")
pytest.importorskip("app.models.content")
pytest.importorskip("app.models.rbac")
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.models.content import SiteSetting
from app.models.rbac import AdminUser
from app.services.login_guard import is_currently_locked, read_login_policy, record_failure
engine = create_engine(
"sqlite://",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
SiteSetting.__table__.create(engine)
AdminUser.__table__.create(engine)
db = sessionmaker(bind=engine, expire_on_commit=False)()
try:
assert read_login_policy(db) == (5, 15)
db.add(SiteSetting(key="login_max_failures", value="2"))
db.add(SiteSetting(key="login_lock_minutes", value="3"))
db.commit()
user = _new_user(AdminUser, "sec-lock-test")
db.add(user)
db.commit()
db.refresh(user)
assert is_currently_locked(user) is False
record_failure(db, user)
assert user.failed_login_count == 1
assert user.locked_until is None
assert is_currently_locked(user) is False
assert user.failed_login_count == 1
record_failure(db, user)
assert user.failed_login_count == 0
assert user.locked_until is not None
locked_until = user.locked_until
if locked_until.tzinfo is not None:
locked_until = locked_until.astimezone(timezone.utc).replace(tzinfo=None)
delta = locked_until - datetime.now(timezone.utc).replace(tzinfo=None)
assert timedelta(minutes=2) < delta < timedelta(minutes=4)
assert is_currently_locked(user) is True
assert user.failed_login_count == 0
user.locked_until = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(seconds=30)
db.add(user)
db.commit()
db.refresh(user)
assert is_currently_locked(user) is False
assert user.failed_login_count == 0
finally:
db.close()
def test_write_audit_does_not_accept_secret_fields():
from app.services.audit import write_audit
signature = inspect.signature(write_audit)
names = list(signature.parameters)
assert names == ["user_id", "username", "method", "path", "status_code", "ip"]
for parameter in signature.parameters.values():
assert parameter.kind is inspect.Parameter.KEYWORD_ONLY
banned = {"body", "password", "captcha", "captcha_id", "id_card", "mobile", "phone"}
assert banned.isdisjoint(names)
with pytest.raises(TypeError):
write_audit(
user_id=None,
username=None,
method="POST",
path="/api/admin/auth/login",
status_code=400,
ip="127.0.0.1",
body="x",
)
with pytest.raises(TypeError):
write_audit(
user_id=None,
username=None,
method="POST",
path="/api/admin/auth/login",
status_code=400,
ip="127.0.0.1",
password="x",
)
with pytest.raises(TypeError):
write_audit(
user_id=None,
username=None,
method="POST",
path="/api/admin/auth/login",
status_code=400,
ip="127.0.0.1",
captcha="x",
)
def test_ip_blacklist_blocks_then_unblocks():
from app.core.config import get_settings
if not (get_settings().database_url or "").strip():
pytest.skip("DATABASE_URL 为空")
from sqlalchemy import delete
from app.db import SessionLocal
from app.models.security import AdminIpBlacklist
from app.services.ip_guard import is_ip_blocked
test_ip = "203.0.113.214"
db = SessionLocal()
try:
AdminIpBlacklist.__table__.create(db.get_bind(), checkfirst=True)
db.execute(delete(AdminIpBlacklist).where(AdminIpBlacklist.ip == test_ip))
db.commit()
assert is_ip_blocked(test_ip) is False
db.add(AdminIpBlacklist(ip=test_ip, remark="security-test"))
db.commit()
assert is_ip_blocked(test_ip) is True
db.execute(delete(AdminIpBlacklist).where(AdminIpBlacklist.ip == test_ip))
db.commit()
assert is_ip_blocked(test_ip) is False
finally:
try:
db.rollback()
db.execute(delete(AdminIpBlacklist).where(AdminIpBlacklist.ip == test_ip))
db.commit()
except Exception:
db.rollback()
finally:
db.close()
def _new_user(model, username: str):
user = model()
if hasattr(user, "username"):
user.username = username
if hasattr(user, "status"):
user.status = "active"
if hasattr(user, "failed_login_count"):
user.failed_login_count = 0
if hasattr(user, "locked_until"):
user.locked_until = None
if hasattr(user, "display_name"):
user.display_name = "lock-test"
if hasattr(user, "password_hash"):
user.password_hash = "test-only-hash"
for column in user.__table__.columns:
if column.primary_key or column.nullable:
continue
if column.default is not None or column.server_default is not None:
continue
if getattr(user, column.key) is not None:
continue
try:
kind = column.type.python_type
except Exception:
kind = str
setattr(user, column.key, 0 if kind is int else "test")
return user
+223
View File
@@ -0,0 +1,223 @@
"""技术交流两类栏目文章:工作人员写入 → 门户公开读取。"""
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _headers(token_type: str) -> dict[str, str]:
return {"Authorization": f"Bearer {create_access_token('1', token_type)}"}
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _clear_category(client, staff: dict[str, str], category: str) -> None:
listed = client.get(f"/api/admin/about/articles/{category}", headers=staff)
assert listed.status_code == 200, listed.text
for item in listed.json().get("items") or []:
deleted = client.delete(f"/api/admin/home/articles/{item['id']}", headers=staff)
assert deleted.status_code in (200, 204), deleted.text
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def test_tech_exchange_publish_filter_placeholder_cover_and_pagination(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
staff = _headers("staff")
article_ids: list[int] = []
file_ids: list[int] = []
try:
for category in ("tech_seminars", "tech_exchange"):
_clear_category(client, staff, category)
empty_seminars = client.get("/api/site/about/articles/tech_seminars")
assert empty_seminars.status_code == 200, empty_seminars.text
assert "暂无技术研讨" in empty_seminars.text
assert "暂无技术交流" in client.get("/api/site/about/articles/tech_exchange").text
cover = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("cover.png", _png(), "image/png")},
)
assert cover.status_code == 200, cover.text
file_ids.append(cover.json()["id"])
pdf = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("研讨通知.pdf", b"%PDF-1.4\nnotice", "application/pdf")},
)
assert pdf.status_code == 200, pdf.text
file_ids.append(pdf.json()["id"])
award = client.post(
"/api/admin/files",
headers=staff,
data={"bucket": "public"},
files={"file": ("获奖名单公示.pdf", b"%PDF-1.4\nawards", "application/pdf")},
)
assert award.status_code == 200, award.text
file_ids.append(award.json()["id"])
seminar = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "tech_seminars",
"title": "城市更新中的房地产估价服务专题研讨",
"publishedAt": "2025-11-08T08:00:00",
"published": True,
"bodyHtml": "<p>城市更新研讨</p><script>alert(1)</script>",
"imageFileId": file_ids[0],
"attachmentFileIds": [file_ids[1]],
},
)
assert seminar.status_code == 200, seminar.text
article_ids.append(seminar.json()["id"])
draft = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "tech_seminars",
"title": "内部筹备研讨",
"publishedAt": "2025-11-09T08:00:00",
"published": False,
"bodyHtml": "<p>内部</p>",
"attachmentFileIds": [],
},
)
assert draft.status_code == 200, draft.text
article_ids.append(draft.json()["id"])
exchange = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "tech_exchange",
"title": "2018年度优秀报告评选表彰与实践分享(公示)",
"publishedAt": "2019-04-26T08:00:00",
"published": True,
"bodyHtml": "<p>优秀报告公示</p>",
"attachmentFileIds": [file_ids[2]],
},
)
assert exchange.status_code == 200, exchange.text
article_ids.append(exchange.json()["id"])
seminars = client.get("/api/site/about/articles/tech_seminars")
assert seminars.status_code == 200, seminars.text
assert "城市更新中的房地产估价服务专题研讨" in seminars.text
assert "内部筹备研讨" not in seminars.text
assert seminars.json()["items"][0].get("imageUrl")
detail = client.get(f"/api/site/home/articles/{article_ids[0]}")
assert detail.status_code == 200, detail.text
body = detail.json()["bodyHtml"].lower()
assert "城市更新研讨" in detail.json()["bodyHtml"]
assert "script" not in body
assert "alert" not in body
assert detail.json().get("imageUrl")
assert [item["filename"] for item in detail.json()["attachments"]] == ["研讨通知.pdf"]
hidden = client.get(f"/api/site/home/articles/{article_ids[1]}")
assert hidden.status_code == 404
exchanges = client.get("/api/site/about/articles/tech_exchange")
assert exchanges.status_code == 200, exchanges.text
assert "2018年度优秀报告评选表彰与实践分享(公示)" in exchanges.text
exchange_detail = client.get(f"/api/site/home/articles/{article_ids[2]}")
assert exchange_detail.status_code == 200, exchange_detail.text
assert [item["filename"] for item in exchange_detail.json()["attachments"]] == ["获奖名单公示.pdf"]
for index in range(10):
created = client.post(
"/api/admin/home/articles",
headers=staff,
json={
"category": "tech_seminars",
"title": f"研讨分页样例-{index:02d}",
"publishedAt": f"2025-01-{index + 1:02d}T08:00:00",
"published": True,
"bodyHtml": f"<p>研讨分页样例-{index:02d}</p>",
"attachmentFileIds": [],
},
)
assert created.status_code == 200, created.text
article_ids.append(created.json()["id"])
page1 = client.get("/api/site/about/articles/tech_seminars?current=1&size=10")
assert page1.status_code == 200, page1.text
assert page1.json()["total"] == 11
assert page1.json()["size"] == 10
assert len(page1.json()["items"]) == 10
page2 = client.get("/api/site/about/articles/tech_seminars?current=2&size=10")
assert page2.status_code == 200, page2.text
assert len(page2.json()["items"]) == 1
size20 = client.get("/api/site/about/articles/tech_seminars?current=1&size=20")
assert size20.json()["size"] == 20
assert len(size20.json()["items"]) == 11
bad_size = client.get("/api/site/about/articles/tech_seminars?current=1&size=15")
assert bad_size.json()["size"] == 10
home = client.get("/api/admin/home", headers=staff)
assert home.status_code == 200, home.text
categories = {item["category"] for item in home.json()["articles"]}
assert "tech_seminars" not in categories
assert "tech_exchange" not in categories
rejected = client.post(
"/api/admin/home/articles",
headers=_headers("member"),
json={
"category": "tech_seminars",
"title": "会员不得发布研讨",
"published": True,
"bodyHtml": "<p>x</p>",
"attachmentFileIds": [],
},
)
assert rejected.status_code in (401, 403)
assert "会员不得发布研讨" not in client.get("/api/site/about/articles/tech_seminars").text
finally:
for article_id in article_ids:
client.delete(f"/api/admin/home/articles/{article_id}", headers=staff)
for file_id in file_ids:
client.delete(f"/api/admin/files/{file_id}", headers=staff)
+673
View File
@@ -0,0 +1,673 @@
"""上传案例:会员提交住宅,管理端只读,不进案例库文章。"""
import time
from datetime import date
import pytest
from fastapi.testclient import TestClient
from app.core.config import get_settings
from app.core.security import create_access_token
from app.services.email_code import _key
from app.services.redis_client import get_redis
@pytest.fixture
def client(monkeypatch):
monkeypatch.setenv("JWT_SECRET", "test-secret-must-be-32-characters!")
monkeypatch.setenv("API_PAYLOAD_ENCRYPT", "false")
monkeypatch.setenv("SMTP_HOST", "")
get_settings.cache_clear()
if not get_settings().database_url.strip():
pytest.skip("DATABASE_URL 为空")
try:
get_redis().ping()
except Exception:
pytest.skip("Redis 不可达")
monkeypatch.setattr("app.services.email_code.send_email", lambda **kwargs: None)
from app.main import create_app
with TestClient(create_app()) as api:
yield api
get_settings.cache_clear()
def _minio_ready() -> bool:
try:
from app.services.storage import ensure_buckets
ensure_buckets()
return True
except Exception:
return False
def _png() -> bytes:
return (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f"
b"\x00\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def _code(purpose: str, email: str) -> str:
stored = get_redis().get(_key(purpose, email))
assert stored is not None
if isinstance(stored, bytes):
stored = stored.decode("utf-8")
return stored
def _register(client, email: str) -> str:
assert client.post("/api/site/auth/email-code", json={"email": email, "purpose": "register"}).status_code == 200
registered = client.post(
"/api/site/auth/register",
json={"email": email, "code": _code("register", email), "password": "Passw0rd1", "privacyAccepted": True},
)
assert registered.status_code == 200, registered.text
return registered.json()["accessToken"]
def _commercial_payload(estate: str, **overrides) -> dict:
body = {
"kind": "commercial",
"caseType": "拍卖成交",
"province": "甘肃省",
"city": "兰州市",
"district": "城关区",
"estateName": estate,
"structure": "砖混",
"caseDate": "2025-06-01",
"location": "张掖路 8 号",
"builtYear": date.today().year,
"totalFloors": "6",
"floorNo": "1",
"layout": "大开间",
"decoration": "高档",
"streetFrontage": "单面临街",
"area": "120",
"orientation": "南",
"footTraffic": "一般",
"shopType": "住宅底商",
"businessFormats": ["餐饮"],
"unitPrice": "80",
"valueIncludes": [],
"remark": "",
"institutionName": "甘肃示例评估",
"photoFileIds": [],
}
body.update(overrides)
return body
def _payload(estate: str, **overrides) -> dict:
body = {
"kind": "residential",
"caseType": "买卖成交",
"province": "甘肃省",
"city": "兰州市",
"district": "城关区",
"estateName": estate,
"structure": "钢混",
"caseDate": "2025-08-16",
"location": "张掖路 1 号",
"builtYear": date.today().year,
"totalFloors": "18",
"floorNo": "-1",
"purpose": "普通住宅",
"layoutStructure": "平面",
"decoration": "中档",
"valueIncludes": ["装饰装修"],
"area": "88.5",
"layout": "两室一厅",
"orientation": "南北",
"unitPrice": "12000",
"remark": "一层带院",
"institutionName": "甘肃示例评估",
"photoFileIds": [],
}
body.update(overrides)
return body
def test_residential_upload_is_private_and_admin_readable(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
email = f"case-{int(time.time() * 1000)}@example.com"
token = _register(client, email)
headers = {"Authorization": f"Bearer {token}"}
staff = {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
estate = f"上传案例样例-{int(time.time())}"
created_ids: list[int] = []
options = client.get("/api/site/uploaded-case-options")
assert options.status_code == 200, options.text
assert date.today().year in options.json()["residential"]["builtYears"]
assert 1979 not in options.json()["residential"]["builtYears"]
assert any(item["name"] == "甘肃省" for item in options.json()["regions"])
denied = client.post("/api/site/member/uploaded-cases", json=_payload(estate))
assert denied.status_code == 401
staff_submit = client.post("/api/site/member/uploaded-cases", headers=staff, json=_payload(estate))
assert staff_submit.status_code == 403
uploaded = client.post(
"/api/site/member/files",
headers=headers,
files={"file": ("位置图.png", _png(), "image/png")},
)
assert uploaded.status_code == 200, uploaded.text
photo_id = uploaded.json()["id"]
missing = client.post("/api/site/member/uploaded-cases", headers=headers, json=_payload(estate, photoFileIds=[]))
assert missing.status_code == 400
assert "照片" in missing.text
bad_year = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate, builtYear=1979, photoFileIds=[photo_id]),
)
assert bad_year.status_code == 400
assert "建筑年代" in bad_year.text
bad_region = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate, city="天水市", photoFileIds=[photo_id]),
)
assert bad_region.status_code == 400
closed = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate, kind="other", photoFileIds=[photo_id]),
)
assert closed.status_code == 400
assert "案例种类不正确" in closed.text
me = client.get("/api/site/member/me", headers=headers)
member_id = me.json()["id"]
from app.db import SessionLocal
from app.models.content import AdminFile
db = SessionLocal()
try:
huge = AdminFile(
bucket="private",
object_key="tests/huge-photo",
filename="过大.png",
content_type="image/png",
size=5 * 1024 * 1024 + 1,
created_by=member_id,
)
db.add(huge)
db.commit()
db.refresh(huge)
huge_id = huge.id
finally:
db.close()
too_big = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate, photoFileIds=[huge_id]),
)
assert too_big.status_code == 400
assert "5MB" in too_big.text
created = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate, photoFileIds=[photo_id]),
)
assert created.status_code == 200, created.text
assert created.json()["message"] == "提交成功"
case_id = created.json()["id"]
created_ids.append(case_id)
second = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_payload(estate + "-新", photoFileIds=[photo_id]),
)
assert second.status_code == 200, second.text
created_ids.append(second.json()["id"])
hidden = client.get("/api/site/member/uploaded-cases", headers=headers)
assert hidden.status_code in (404, 405)
public = client.get("/api/site/about/articles/case_library")
assert estate not in public.text
searched = client.get("/api/site/about/articles/case_library", params={"q": estate})
assert estate not in searched.text
member_admin = client.get("/api/admin/uploaded-cases", headers=headers)
assert member_admin.status_code == 403
member_detail = client.get(f"/api/admin/uploaded-cases/{case_id}", headers=headers)
assert member_detail.status_code == 403
listed = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "residential"})
assert listed.status_code == 200, listed.text
names = [item["estateName"] for item in listed.json()["items"]]
assert names.index(estate + "-新") < names.index(estate)
newer = listed.json()["items"][names.index(estate + "-新")]
assert newer["memberEmail"] == email
older = next(item for item in listed.json()["items"] if item["estateName"] == estate)
assert "城关区" in older["address"]
matched = client.get(
"/api/admin/uploaded-cases",
headers=staff,
params={"kind": "residential", "q": estate + "-新"},
)
assert matched.status_code == 200, matched.text
matched_names = [item["estateName"] for item in matched.json()["items"]]
assert matched_names == [estate + "-新"]
by_email = client.get(
"/api/admin/uploaded-cases",
headers=staff,
params={"kind": "residential", "q": email},
)
assert by_email.status_code == 200, by_email.text
assert {item["estateName"] for item in by_email.json()["items"]} >= {estate, estate + "-新"}
wildcard = client.get(
"/api/admin/uploaded-cases",
headers=staff,
params={"kind": "residential", "q": "%"},
)
assert wildcard.status_code == 200, wildcard.text
assert estate not in [item["estateName"] for item in wildcard.json()["items"]]
detail = client.get(f"/api/admin/uploaded-cases/{case_id}", headers=staff)
assert detail.status_code == 200, detail.text
body = detail.json()
assert body["purpose"] == "普通住宅"
assert body["builtYear"] == date.today().year
assert body["floorNo"] == "-1"
assert body["photos"][0]["filename"] == "位置图.png"
assert body["memberEmail"] == email
other = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "commercial"})
assert other.status_code == 200
assert other.json()["items"] == []
from sqlalchemy import select
from app.models.uploaded_case import UploadedCase, UploadedCasePhoto
db = SessionLocal()
try:
for item_id in created_ids:
for photo in db.scalars(select(UploadedCasePhoto).where(UploadedCasePhoto.case_id == item_id)).all():
db.delete(photo)
row = db.get(UploadedCase, item_id)
if row is not None:
db.delete(row)
huge_row = db.get(AdminFile, huge_id)
if huge_row is not None:
db.delete(huge_row)
db.commit()
finally:
db.close()
def test_commercial_upload_stays_in_its_admin_tab(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
email = f"shop-{int(time.time() * 1000)}@example.com"
token = _register(client, email)
headers = {"Authorization": f"Bearer {token}"}
staff = {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
estate = f"商业上传样例-{int(time.time())}"
created_ids: list[int] = []
options = client.get("/api/site/uploaded-case-options")
assert options.status_code == 200, options.text
assert "commercial" in options.json()["openKinds"]
commercial = options.json()["commercial"]
assert commercial["layouts"] == ["大开间", "隔档"]
assert "单面临街" in commercial["streetFrontages"]
assert commercial["shopTypes"][0] == "住宅底商"
assert "餐饮" in commercial["businessFormats"]
uploaded = client.post(
"/api/site/member/files",
headers=headers,
files={"file": ("商铺.png", _png(), "image/png")},
)
assert uploaded.status_code == 200, uploaded.text
photo_id = uploaded.json()["id"]
extra = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_commercial_payload(estate, purpose="普通住宅", photoFileIds=[photo_id]),
)
assert extra.status_code == 400
assert "没有的字段" in extra.text
empty_formats = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_commercial_payload(estate, businessFormats=[], photoFileIds=[photo_id]),
)
assert empty_formats.status_code == 400
assert "经营业态" in empty_formats.text
too_many = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_commercial_payload(
estate,
businessFormats=["餐饮", "百货", "酒吧", "其他"],
photoFileIds=[photo_id],
),
)
assert too_many.status_code == 400
assert "经营业态" in too_many.text
created = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_commercial_payload(estate, businessFormats=["餐饮", "百货"], photoFileIds=[photo_id]),
)
assert created.status_code == 200, created.text
assert created.json()["message"] == "提交成功"
case_id = created.json()["id"]
created_ids.append(case_id)
hidden = client.get("/api/site/member/uploaded-cases", headers=headers)
assert hidden.status_code in (404, 405)
public = client.get("/api/site/about/articles/case_library")
assert estate not in public.text
shops = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "commercial"})
assert shops.status_code == 200, shops.text
assert any(item["estateName"] == estate and item["memberEmail"] == email for item in shops.json()["items"])
homes = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "residential"})
assert all(item["estateName"] != estate for item in homes.json()["items"])
detail = client.get(f"/api/admin/uploaded-cases/{case_id}", headers=staff)
assert detail.status_code == 200, detail.text
body = detail.json()
assert body["kind"] == "commercial"
assert body["layout"] == "大开间"
assert body["streetFrontage"] == "单面临街"
assert body["footTraffic"] == "一般"
assert body["shopType"] == "住宅底商"
assert body["businessFormats"] == ["餐饮", "百货"]
assert "purpose" not in body
assert body["photos"][0]["filename"] == "商铺.png"
from sqlalchemy import select
from app.db import SessionLocal
from app.models.uploaded_case import UploadedCase, UploadedCasePhoto
db = SessionLocal()
try:
for item_id in created_ids:
for photo in db.scalars(select(UploadedCasePhoto).where(UploadedCasePhoto.case_id == item_id)).all():
db.delete(photo)
row = db.get(UploadedCase, item_id)
if row is not None:
db.delete(row)
db.commit()
finally:
db.close()
def _office_payload(estate: str, **overrides) -> dict:
body = {
"kind": "office",
"caseType": "评估案例",
"province": "甘肃省",
"city": "兰州市",
"district": "城关区",
"estateName": estate,
"structure": "钢混",
"caseDate": "2025-04-18",
"location": "东岗西路 12 号",
"builtYear": date.today().year,
"totalFloors": "22",
"floorNo": "8",
"layoutStructure": "写字楼(大开间)",
"decoration": "中档",
"area": "360",
"orientation": "东南",
"unitPrice": "45",
"valueIncludes": [],
"remark": "",
"institutionName": "甘肃示例评估",
"photoFileIds": [],
}
body.update(overrides)
return body
def test_office_upload_stays_in_its_admin_tab(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
email = f"office-{int(time.time() * 1000)}@example.com"
token = _register(client, email)
headers = {"Authorization": f"Bearer {token}"}
staff = {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
estate = f"办公上传样例-{int(time.time())}"
created_ids: list[int] = []
options = client.get("/api/site/uploaded-case-options")
assert options.status_code == 200, options.text
assert "office" in options.json()["openKinds"]
office = options.json()["office"]
assert office["layoutStructures"] == ["办公楼(中间过道两边办公室)", "写字楼(大开间)"]
assert office["totalFloors"][-1] == "60"
assert office["floorNos"][0] == "-4"
assert "东南" in office["orientations"]
assert "layouts" not in office
uploaded = client.post(
"/api/site/member/files",
headers=headers,
files={"file": ("办公.png", _png(), "image/png")},
)
assert uploaded.status_code == 200, uploaded.text
photo_id = uploaded.json()["id"]
extra = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_office_payload(estate, layout="大开间", photoFileIds=[photo_id]),
)
assert extra.status_code == 400
assert "没有的字段" in extra.text
created = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_office_payload(estate, photoFileIds=[photo_id]),
)
assert created.status_code == 200, created.text
assert created.json()["message"] == "提交成功"
case_id = created.json()["id"]
created_ids.append(case_id)
hidden = client.get("/api/site/member/uploaded-cases", headers=headers)
assert hidden.status_code in (404, 405)
public = client.get("/api/site/about/articles/case_library")
assert estate not in public.text
offices = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "office"})
assert offices.status_code == 200, offices.text
assert any(item["estateName"] == estate and item["memberEmail"] == email for item in offices.json()["items"])
homes = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "residential"})
assert all(item["estateName"] != estate for item in homes.json()["items"])
shops = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "commercial"})
assert all(item["estateName"] != estate for item in shops.json()["items"])
detail = client.get(f"/api/admin/uploaded-cases/{case_id}", headers=staff)
assert detail.status_code == 200, detail.text
body = detail.json()
assert body["kind"] == "office"
assert body["layoutStructure"] == "写字楼(大开间)"
assert body["orientation"] == "东南"
assert body["totalFloors"] == 22
assert "layout" not in body
assert "purpose" not in body
assert "streetFrontage" not in body
assert body["photos"][0]["filename"] == "办公.png"
from sqlalchemy import select
from app.db import SessionLocal
from app.models.uploaded_case import UploadedCase, UploadedCasePhoto
db = SessionLocal()
try:
for item_id in created_ids:
for photo in db.scalars(select(UploadedCasePhoto).where(UploadedCasePhoto.case_id == item_id)).all():
db.delete(photo)
row = db.get(UploadedCase, item_id)
if row is not None:
db.delete(row)
db.commit()
finally:
db.close()
def _industrial_payload(estate: str, **overrides) -> dict:
body = {
"kind": "industrial",
"caseType": "买卖成交",
"province": "甘肃省",
"city": "兰州市",
"district": "西固区",
"estateName": estate,
"structure": "钢结构",
"caseDate": "2024-11-02",
"location": "西固工业园 3 号",
"builtYear": date.today().year,
"totalFloors": "3",
"layout": "开间",
"heading": "南北",
"decoration": "简易",
"roadFrontage": "主干道",
"area": "2400",
"orientation": "东西",
"industryType": "机械制造",
"unitPrice": "18",
"valueIncludes": ["装饰装修"],
"remark": "",
"institutionName": "甘肃示例评估",
"photoFileIds": [],
}
body.update(overrides)
return body
def test_industrial_upload_stays_in_its_admin_tab(client):
if not _minio_ready():
pytest.skip("MinIO 不可达")
email = f"plant-{int(time.time() * 1000)}@example.com"
token = _register(client, email)
headers = {"Authorization": f"Bearer {token}"}
staff = {"Authorization": f"Bearer {create_access_token('1', 'staff')}"}
estate = f"工业上传样例-{int(time.time())}"
created_ids: list[int] = []
options = client.get("/api/site/uploaded-case-options")
assert options.status_code == 200, options.text
assert "industrial" in options.json()["openKinds"]
industrial = options.json()["industrial"]
assert industrial["totalFloors"] == [str(item) for item in range(1, 9)]
assert industrial["layouts"] == ["开间"]
assert industrial["headings"] == ["南北", "东西"]
assert industrial["orientations"] == ["南北", "东西"]
assert industrial["roadFrontages"] == ["主干道", "次干道", "街巷"]
assert industrial["industryTypes"][0] == "食品饮料加工"
assert industrial["valueIncludes"] == ["装饰装修", "家具用具"]
assert "floorNos" not in industrial
uploaded = client.post(
"/api/site/member/files",
headers=headers,
files={"file": ("厂房.png", _png(), "image/png")},
)
assert uploaded.status_code == 200, uploaded.text
photo_id = uploaded.json()["id"]
extra = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_industrial_payload(estate, floorNo="1", photoFileIds=[photo_id]),
)
assert extra.status_code == 400
assert "没有的字段" in extra.text
too_tall = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_industrial_payload(estate, totalFloors="9", photoFileIds=[photo_id]),
)
assert too_tall.status_code == 400
assert "总层数" in too_tall.text
created = client.post(
"/api/site/member/uploaded-cases",
headers=headers,
json=_industrial_payload(estate, photoFileIds=[photo_id]),
)
assert created.status_code == 200, created.text
assert created.json()["message"] == "提交成功"
case_id = created.json()["id"]
created_ids.append(case_id)
hidden = client.get("/api/site/member/uploaded-cases", headers=headers)
assert hidden.status_code in (404, 405)
public = client.get("/api/site/about/articles/case_library")
assert estate not in public.text
plants = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": "industrial"})
assert plants.status_code == 200, plants.text
assert any(item["estateName"] == estate and item["memberEmail"] == email for item in plants.json()["items"])
for other in ("residential", "commercial", "office"):
listed = client.get("/api/admin/uploaded-cases", headers=staff, params={"kind": other})
assert all(item["estateName"] != estate for item in listed.json()["items"])
detail = client.get(f"/api/admin/uploaded-cases/{case_id}", headers=staff)
assert detail.status_code == 200, detail.text
body = detail.json()
assert body["kind"] == "industrial"
assert body["layout"] == "开间"
assert body["heading"] == "南北"
assert body["roadFrontage"] == "主干道"
assert body["orientation"] == "东西"
assert body["industryType"] == "机械制造"
assert body["totalFloors"] == 3
assert body["valueIncludes"] == ["装饰装修"]
assert "floorNo" not in body
assert "purpose" not in body
assert "streetFrontage" not in body
assert body["photos"][0]["filename"] == "厂房.png"
from sqlalchemy import select
from app.db import SessionLocal
from app.models.uploaded_case import UploadedCase, UploadedCasePhoto
db = SessionLocal()
try:
for item_id in created_ids:
for photo in db.scalars(select(UploadedCasePhoto).where(UploadedCasePhoto.case_id == item_id)).all():
db.delete(photo)
row = db.get(UploadedCase, item_id)
if row is not None:
db.delete(row)
db.commit()
finally:
db.close()