refactor(backend): 重构后端
This commit is contained in:
1 parent
c8054476c1
commit
bba6e6f221
32 files changed
+252
-296
No files matched your search
@@ -60,8 +60,6 @@ def create_app(config_name='default'):
|
||||
start_scheduler(app)
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
from app.cli.faq_commands import init_app as init_faq_cli
|
||||
init_faq_cli(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
|
||||
+54
-18
@@ -672,7 +672,11 @@ def login():
|
||||
Can be disabled via AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=false.
|
||||
"""
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', True)):
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Password login is disabled. Please use Casdoor login.', http_status=403, details={'error_code': 'PASSWORD_LOGIN_DISABLED'})
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_LOGIN_DISABLED',
|
||||
message='Password login is disabled. Please use Casdoor login.',
|
||||
http_status=403,
|
||||
)
|
||||
|
||||
def _attempt_login():
|
||||
data = request.get_json() or {}
|
||||
@@ -728,7 +732,11 @@ def casdoor_password_login():
|
||||
Direct login with username/password against Casdoor (no browser redirect).
|
||||
"""
|
||||
if (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() != 'casdoor':
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Casdoor password login is disabled by AUTH_LOGIN_MODE', http_status=403, details={'error_code': 'CASDOOR_PASSWORD_LOGIN_DISABLED'})
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_PASSWORD_LOGIN_DISABLED',
|
||||
message='Casdoor password login is disabled by AUTH_LOGIN_MODE',
|
||||
http_status=403,
|
||||
)
|
||||
data = request.get_json() or {}
|
||||
username = _clean_str(data.get('username'))
|
||||
password = data.get('password') or ''
|
||||
@@ -939,7 +947,11 @@ def casdoor_refresh():
|
||||
except Exception as e:
|
||||
message = str(e)
|
||||
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Casdoor refresh token is not supported by current application config', http_status=400, details={'error_code': 'CASDOOR_REFRESH_UNSUPPORTED'})
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||||
message='Casdoor refresh token is not supported by current application config',
|
||||
http_status=400,
|
||||
)
|
||||
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _token_brief(refresh_token))
|
||||
raise UnauthorizedError(f'Casdoor refresh failed: {str(e)}')
|
||||
|
||||
@@ -986,7 +998,11 @@ def wecom_login():
|
||||
if not wecom_userid_value:
|
||||
_write_login_audit('wecom', 'failed', reason=f"not_in_agent_scope:openid={wecom_openid_value or ''}", error_code='WECOM_NOT_IN_AGENT_SCOPE')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。', http_status=401, details={'error_code': 'WECOM_NOT_IN_AGENT_SCOPE'})
|
||||
raise AppError(
|
||||
code='WECOM_NOT_IN_AGENT_SCOPE',
|
||||
message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。',
|
||||
http_status=401,
|
||||
)
|
||||
user_resp = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': wecom_userid_value}, timeout=8)
|
||||
wecom_user = user_resp.json()
|
||||
wecom_userid_for_audit = wecom_user.get('userid') or wecom_userid_for_audit
|
||||
@@ -1012,7 +1028,11 @@ def wecom_login():
|
||||
if _is_users_pk_sequence_error(e):
|
||||
_write_login_audit('wecom', 'failed', reason='db_sequence_misconfig', wecom_userid=wecom_userid_for_audit, error_code='DB_SEQUENCE_MISCONFIG')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。', http_status=500, details={'error_code': 'DB_SEQUENCE_MISCONFIG'})
|
||||
raise AppError(
|
||||
code='SYSTEM.DB_SEQUENCE_MISCONFIG',
|
||||
message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。',
|
||||
http_status=500,
|
||||
)
|
||||
_write_login_audit('wecom', 'failed', reason=f'exception:{str(e)[:160]}')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom login failed: {str(e)}', http_status=500)
|
||||
@@ -1027,21 +1047,44 @@ def wecom_complete_bind():
|
||||
value = data.get('value')
|
||||
identity = _get_wecom_bind_session(binding_token)
|
||||
if not identity:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='WeCom binding session expired. Please restart WeCom login.', http_status=400, details={'error_code': 'WECOM_BIND_SESSION_EXPIRED'})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_SESSION_EXPIRED',
|
||||
message='WeCom binding session expired. Please restart WeCom login.',
|
||||
http_status=400,
|
||||
)
|
||||
allowed_fields = _get_wecom_first_login_input_fields()
|
||||
if field not in allowed_fields:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Selected bind field is not allowed', http_status=400, details={'error_code': 'WECOM_BIND_FIELD_NOT_ALLOWED', 'allowed_fields': allowed_fields})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_FIELD_NOT_ALLOWED',
|
||||
message='Selected bind field is not allowed',
|
||||
http_status=400,
|
||||
details={'allowed_fields': allowed_fields},
|
||||
)
|
||||
matched_users, missing_field = _find_users_by_input_field(field, value)
|
||||
if missing_field:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=f'{field} is required', http_status=400, details={'error_code': 'WECOM_BIND_INPUT_VALUE_REQUIRED', 'field': field})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_INPUT_VALUE_REQUIRED',
|
||||
message=f'{field} is required',
|
||||
http_status=400,
|
||||
details={'field': field},
|
||||
)
|
||||
if len(matched_users) == 0:
|
||||
_write_login_audit('wecom', 'failed', reason=f'input_bind_not_found:{field}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_NOT_FOUND', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='No local account matched the verification value.', http_status=404, details={'error_code': 'WECOM_BIND_INPUT_NOT_FOUND', 'field': field})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_INPUT_NOT_FOUND',
|
||||
message='No local account matched the verification value.',
|
||||
http_status=404,
|
||||
details={'field': field},
|
||||
)
|
||||
if len(matched_users) > 1:
|
||||
_write_login_audit('wecom', 'failed', reason=f'input_bind_ambiguous:{field}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_AMBIGUOUS', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise ConflictError('Multiple local accounts matched the verification value.', details={'error_code': 'WECOM_BIND_INPUT_AMBIGUOUS', 'field': field, 'candidate_count': len(matched_users)})
|
||||
raise ConflictError(
|
||||
'Multiple local accounts matched the verification value.',
|
||||
code='WECOM_BIND_INPUT_AMBIGUOUS',
|
||||
details={'field': field, 'candidate_count': len(matched_users)},
|
||||
)
|
||||
user = matched_users[0]
|
||||
if user.status != 'active':
|
||||
_write_login_audit('wecom', 'failed', user=user, reason='account_disabled', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_ACCOUNT_DISABLED', match_rules=[field], match_operator='AND')
|
||||
@@ -1568,24 +1611,19 @@ def reset_password_by_wecom():
|
||||
code='WECOM.RESET_NOT_CONFIGURED',
|
||||
message='WeCom password reset is not configured',
|
||||
http_status=503,
|
||||
details={
|
||||
'error_code': 'WECOM_RESET_NOT_CONFIGURED',
|
||||
'missing': _get_wecom_config_missing_fields(),
|
||||
},
|
||||
details={'missing': _get_wecom_config_missing_fields()},
|
||||
)
|
||||
if not bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)):
|
||||
raise AppError(
|
||||
code='WECOM.NOTIFY_DISABLED',
|
||||
message='WeCom notification is disabled',
|
||||
http_status=503,
|
||||
details={'error_code': 'WECOM_NOTIFY_DISABLED'},
|
||||
)
|
||||
if not _get_password_reset_public_base_url():
|
||||
raise AppError(
|
||||
code='WECOM.RESET_URL_NOT_CONFIGURED',
|
||||
message='Password reset public base URL is not configured',
|
||||
http_status=503,
|
||||
details={'error_code': 'PASSWORD_RESET_URL_NOT_CONFIGURED'},
|
||||
)
|
||||
|
||||
data = request.get_json() or {}
|
||||
@@ -1610,7 +1648,6 @@ def reset_password_by_wecom():
|
||||
message='Password reset requests are too frequent',
|
||||
http_status=429,
|
||||
details={
|
||||
'error_code': 'PASSWORD_RESET_RATE_LIMITED',
|
||||
'retry_after_seconds': retry_after_seconds,
|
||||
'retry_after_minutes': retry_minutes,
|
||||
},
|
||||
@@ -1737,7 +1774,6 @@ def reset_password_confirm():
|
||||
code='AUTH.RESET_TOKEN_INVALID',
|
||||
message='Invalid or expired token',
|
||||
http_status=400,
|
||||
details={'error_code': 'RESET_TOKEN_INVALID'},
|
||||
)
|
||||
try:
|
||||
_sync_casdoor_password_for_reset(user, new_password)
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
"""
|
||||
backend/app/auth_jwt.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.auth.jwt。
|
||||
依赖:app.core.auth.jwt。
|
||||
逻辑:Casdoor JWKS 校验与 get_current_user;新代码请 from app.core.auth.jwt import ...。
|
||||
"""
|
||||
|
||||
from app.core.auth.jwt import get_current_user, issue_local_access_token # noqa: F401
|
||||
|
||||
__all__ = ['get_current_user', 'issue_local_access_token']
|
||||
@@ -1 +0,0 @@
|
||||
"""FAQ CLI 包。"""
|
||||
@@ -1,44 +0,0 @@
|
||||
"""
|
||||
backend/app/cli/faq_commands.py
|
||||
|
||||
用途:FAQ 相关 Flask CLI 命令注册。
|
||||
依赖:HotFaqAggregator、Flask click。
|
||||
逻辑:create_app 时 init_app 注册 faq-aggregate-hot 命令。
|
||||
"""
|
||||
import click
|
||||
from flask.cli import with_appcontext
|
||||
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
|
||||
@click.command('faq-aggregate-hot')
|
||||
@click.option('--agent-id', type=int, default=None, help='仅聚合指定 Agent')
|
||||
@click.option('--dry-run', is_flag=True, help='只统计不写 PostgreSQL')
|
||||
@with_appcontext
|
||||
def faq_aggregate_hot(agent_id: int | None, dry_run: bool):
|
||||
"""
|
||||
离线聚合 ChatLog 热点 FAQ 候选并写入 faq_hot_candidates 表。
|
||||
核心逻辑:委托 HotFaqAggregator.aggregate_hot_faq_candidates。
|
||||
"""
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
||||
if not result.get('enabled'):
|
||||
click.echo(result.get('message', 'FAQ hot aggregation disabled'))
|
||||
return
|
||||
|
||||
click.echo(
|
||||
f"scanned={result['scanned_logs']} groups={result['group_count']} "
|
||||
f"promoted={result['promoted_count']} skipped={result['skipped_count']} dry_run={dry_run}"
|
||||
)
|
||||
for item in result.get('candidates', [])[:20]:
|
||||
click.echo(
|
||||
f" [{item.get('agent_name')}] {item.get('canonical_query')} "
|
||||
f"asks={item.get('ask_count_7d')} users={item.get('user_count_7d')} "
|
||||
f"dominance={item.get('answer_dominance')}"
|
||||
)
|
||||
if len(result.get('candidates', [])) > 20:
|
||||
click.echo(f" ... and {len(result['candidates']) - 20} more")
|
||||
|
||||
|
||||
def init_app(app):
|
||||
"""向 Flask app 注册 FAQ CLI 命令。"""
|
||||
app.cli.add_command(faq_aggregate_hot)
|
||||
@@ -1,25 +0,0 @@
|
||||
"""
|
||||
backend/app/config.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.config.settings。
|
||||
依赖:app.core.config.settings。
|
||||
逻辑:环境文件加载与 Config 类;新代码请 from app.core.config.settings import config。
|
||||
"""
|
||||
|
||||
from app.core.config.settings import ( # noqa: F401
|
||||
ACTIVE_ENV_NAME,
|
||||
Config,
|
||||
DevelopmentConfig,
|
||||
ProductionConfig,
|
||||
TestingConfig,
|
||||
config,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'ACTIVE_ENV_NAME',
|
||||
'Config',
|
||||
'DevelopmentConfig',
|
||||
'ProductionConfig',
|
||||
'TestingConfig',
|
||||
'config',
|
||||
]
|
||||
@@ -2,8 +2,7 @@
|
||||
backend/app/core/__init__.py
|
||||
|
||||
用途:横切能力包入口(errors、response、auth、config、decorators)。
|
||||
逻辑:业务代码优先 from app.core.errors / app.core.auth.jwt 等子模块 import;
|
||||
app/errors.py 等根路径 shim 仅作存量兼容。
|
||||
逻辑:业务代码 from app.core.errors / app.core.auth.jwt 等子模块 import。
|
||||
"""
|
||||
|
||||
from app.core.errors import AppError # noqa: F401
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/core/auth/jwt.py
|
||||
|
||||
用途:Casdoor JWT 校验、legacy header 回退与当前用户解析。
|
||||
依赖:app.extensions.db、app.models.User、PyJWT、requests。
|
||||
逻辑:api 层与 decorators 调用 get_current_user();旧路径 app.auth_jwt 为兼容 shim。
|
||||
逻辑:api 层与 decorators 调用 get_current_user()。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/core/decorators.py
|
||||
|
||||
用途:API 路由权限装饰器(admin、agent 权限)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.models。
|
||||
逻辑:api 路由使用 @require_admin、@require_agent_permission;旧路径 app.decorators 为兼容 shim。
|
||||
逻辑:api 路由使用 @require_admin、@require_agent_permission。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/core/errors.py
|
||||
|
||||
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||
依赖:无 Flask 依赖。
|
||||
逻辑:业务层 raise AppError 子类;create_app 注册全局 handler;旧路径 app.errors 为兼容 shim。
|
||||
逻辑:业务层 raise AppError 子类;create_app 注册全局 handler。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
"""
|
||||
backend/app/decorators.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.decorators。
|
||||
依赖:app.core.decorators。
|
||||
逻辑:@require_admin / @require_agent_permission;新代码请 from app.core.decorators import ...。
|
||||
"""
|
||||
|
||||
from app.core.decorators import ( # noqa: F401
|
||||
_get_current_user,
|
||||
require_admin,
|
||||
require_agent_permission,
|
||||
)
|
||||
|
||||
__all__ = ['require_admin', 'require_agent_permission', '_get_current_user']
|
||||
@@ -1,23 +0,0 @@
|
||||
"""
|
||||
backend/app/env_persistence.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.config.env_persistence。
|
||||
依赖:app.core.config.env_persistence。
|
||||
逻辑:WeCom 等运行时配置 DB 持久化;create_app before_request 调用 apply_env_settings。
|
||||
"""
|
||||
|
||||
from app.core.config.env_persistence import ( # noqa: F401
|
||||
BACKEND_ENV_PATH,
|
||||
LEGACY_BACKEND_ENV_PATH,
|
||||
ROOT_ENV_LOCAL_PATH,
|
||||
apply_env_settings,
|
||||
persist_env_settings,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'BACKEND_ENV_PATH',
|
||||
'LEGACY_BACKEND_ENV_PATH',
|
||||
'ROOT_ENV_LOCAL_PATH',
|
||||
'apply_env_settings',
|
||||
'persist_env_settings',
|
||||
]
|
||||
@@ -1,9 +0,0 @@
|
||||
"""
|
||||
backend/app/errors.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.errors。
|
||||
依赖:app.core.errors。
|
||||
逻辑:存量代码 from app.errors import ... 仍可用;新代码请改用 app.core.errors。
|
||||
"""
|
||||
|
||||
from app.core.errors import * # noqa: F403
|
||||
@@ -1,11 +0,0 @@
|
||||
"""
|
||||
backend/app/response_utils.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.response。
|
||||
依赖:app.core.response。
|
||||
逻辑:create_app 全局 handler 使用 error_payload;新代码请 from app.core.response import ...。
|
||||
"""
|
||||
|
||||
from app.core.response import error_payload, ok, utc_iso, utc_iso_now # noqa: F401
|
||||
|
||||
__all__ = ['error_payload', 'ok', 'utc_iso', 'utc_iso_now']
|
||||
@@ -3,7 +3,7 @@ backend/app/services/hot_faq_aggregator.py
|
||||
|
||||
用途:从 ChatLog 离线聚合热点 FAQ 候选,写入 PostgreSQL 候选表(不含在线命中)。
|
||||
依赖:ChatLog、Feedback、QuickQuestion、faq_text_utils、hot_faq_candidate_store。
|
||||
逻辑:CLI `flask faq-aggregate-hot` 与管理端「刷新」调用 aggregate_hot_faq_candidates。
|
||||
逻辑:管理端「刷新聚合」调用 aggregate_hot_faq_candidates。
|
||||
|
||||
## 热点选取规则(HOT_FAQ_SELECTION_RULES)
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str
|
||||
|
||||
def run_faq_hot_aggregate_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行 FAQ 热点离线聚合(等同 flask faq-aggregate-hot,非 dry-run)。
|
||||
执行 FAQ 热点离线聚合(非 dry-run)。
|
||||
核心逻辑:委托 HotFaqAggregator;可选 dify_agent_id 限定 Agent。
|
||||
@param task - 排程任务;dify_agent_id 可选作 agent_id 过滤
|
||||
@param run - 当前执行批次(未写入 run 字段,由 scheduler_service 汇总)
|
||||
|
||||
Reference in new issue
Block a user