feat: 重构管理后台前端架构并新增完整功能
This commit is contained in:
commit
93304a1803
88 files changed
+9941
-6500
No files matched your search
+87
-14
@@ -154,19 +154,84 @@ def debug_wecom_user_by_code():
|
||||
payload['match_preview'] = _build_wecom_match_preview(identity, rules, operator)
|
||||
return jsonify(payload)
|
||||
|
||||
def _compute_dashboard_summary():
|
||||
"""
|
||||
聚合仪表盘四张卡片所需的统计值(仅 COUNT/AVG,不返回列表)。
|
||||
|
||||
返回字段:
|
||||
- agent_count: 启用中的 Agent 数量
|
||||
- user_count: 用户总数
|
||||
- total_conversations: 对话日志总数
|
||||
- avg_score: 反馈平均分(保留 1 位小数)
|
||||
"""
|
||||
total_users = db.session.query(func.count(User.id)).scalar() or 0
|
||||
active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() or 0
|
||||
total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0
|
||||
avg_score = db.session.query(func.avg(Feedback.score)).scalar()
|
||||
avg_score = round(float(avg_score), 1) if avg_score else 0.0
|
||||
return {
|
||||
'agent_count': active_agents,
|
||||
'user_count': total_users,
|
||||
'total_conversations': total_conversations,
|
||||
'avg_score': avg_score,
|
||||
}
|
||||
|
||||
def _compute_dashboard_badges():
|
||||
"""
|
||||
聚合侧栏角标所需的待办数量(仅 COUNT,不拉 users / permission_requests 全表)。
|
||||
|
||||
返回字段:
|
||||
- pending_approvals: status=pending 的注册用户数量(「用户审批」角标)
|
||||
- pending_requests: status=pending 的权限申请数量(「权限申请」角标)
|
||||
"""
|
||||
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0
|
||||
pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0
|
||||
return {
|
||||
'pending_approvals': pending_approvals,
|
||||
'pending_requests': pending_requests,
|
||||
}
|
||||
|
||||
@admin_bp.route('/dashboard/summary', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_summary():
|
||||
"""
|
||||
管理后台仪表盘概览(供 Dashboard 页单次请求)。
|
||||
|
||||
GET /api/admin/dashboard/summary
|
||||
响应示例:{"agent_count": 5, "user_count": 120, "total_conversations": 3000, "avg_score": 4.2}
|
||||
"""
|
||||
return jsonify(_compute_dashboard_summary())
|
||||
|
||||
@admin_bp.route('/dashboard/badges', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_badges():
|
||||
"""
|
||||
管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。
|
||||
|
||||
GET /api/admin/dashboard/badges
|
||||
响应示例:{"pending_approvals": 2, "pending_requests": 5}
|
||||
"""
|
||||
return jsonify(_compute_dashboard_badges())
|
||||
|
||||
@admin_bp.route('/dashboard', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_stats():
|
||||
"""
|
||||
Dashboard statistics
|
||||
仪表盘统计(遗留接口,字段名与早期前端兼容;新代码请用 /dashboard/summary 与 /dashboard/badges)。
|
||||
|
||||
GET /api/admin/dashboard
|
||||
响应含 summary 四指标 + pending_approvals / pending_requests。
|
||||
"""
|
||||
total_users = db.session.query(func.count(User.id)).scalar()
|
||||
active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar()
|
||||
total_conversations = db.session.query(func.count(ChatLog.id)).scalar()
|
||||
avg_score = db.session.query(func.avg(Feedback.score)).scalar()
|
||||
avg_score = float(avg_score) if avg_score else 0.0
|
||||
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar()
|
||||
return jsonify({'total_users': total_users, 'active_agents': active_agents, 'total_conversations': total_conversations, 'avg_score': round(avg_score, 1), 'pending_approvals': pending_approvals})
|
||||
summary = _compute_dashboard_summary()
|
||||
badges = _compute_dashboard_badges()
|
||||
return jsonify({
|
||||
'total_users': summary['user_count'],
|
||||
'active_agents': summary['agent_count'],
|
||||
'total_conversations': summary['total_conversations'],
|
||||
'avg_score': summary['avg_score'],
|
||||
'pending_approvals': badges['pending_approvals'],
|
||||
'pending_requests': badges['pending_requests'],
|
||||
})
|
||||
|
||||
@admin_bp.route('/departments', methods=['GET'])
|
||||
@require_admin
|
||||
@@ -303,7 +368,7 @@ def test_agent(id):
|
||||
payload = {'inputs': {'query': '系统连通性测试,请简短回复OK。'}, 'response_mode': 'blocking', 'user': 'admin_test'}
|
||||
else:
|
||||
request_url = DifyService._build_chat_messages_url(base_url)
|
||||
payload = {'inputs': {}, 'query': '系统连通性测试,请简短回复OK。', 'response_mode': 'blocking', 'conversation_id': '', 'user': 'admin_test'}
|
||||
payload = {'inputs': {}, 'query': '系统连通性测试,请简短回复OK。', 'response_mode': 'blocking', 'user': 'admin_test'}
|
||||
headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'}
|
||||
try:
|
||||
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
|
||||
@@ -397,16 +462,24 @@ def list_users():
|
||||
@require_admin
|
||||
def create_user():
|
||||
data = request.get_json() or {}
|
||||
if not data.get('username'):
|
||||
raise AppError(code='USER.USERNAME_REQUIRED', message='Username is required', http_status=400, details={'field': 'username'})
|
||||
required_field_errors = (
|
||||
('username', 'USER.USERNAME_REQUIRED', 'Username is required'),
|
||||
('password', 'USER.PASSWORD_REQUIRED', 'Password is required'),
|
||||
('email', 'USER.EMAIL_REQUIRED', 'Email is required'),
|
||||
('real_name', 'USER.REAL_NAME_REQUIRED', 'Real name is required'),
|
||||
('employee_id', 'USER.EMPLOYEE_ID_REQUIRED', 'Employee ID is required'),
|
||||
('phone_number', 'USER.PHONE_REQUIRED', 'Phone number is required'),
|
||||
)
|
||||
for field, code, message in required_field_errors:
|
||||
if _empty_to_none(data.get(field)) is None:
|
||||
raise AppError(code=code, message=message, http_status=400, details={'field': field})
|
||||
if db.session.query(User).filter_by(username=data['username']).first():
|
||||
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS', details={'field': 'username'})
|
||||
email = _empty_to_none(data.get('email'))
|
||||
if email is not None and (not _is_valid_email(email)):
|
||||
if not _is_valid_email(email):
|
||||
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
|
||||
user = User(username=data['username'], email=email, department=_empty_to_none(data.get('department')), role=data.get('role', 'user'), status=data.get('status', 'active'), real_name=_empty_to_none(data.get('real_name')), employee_id=_empty_to_none(data.get('employee_id')), phone_number=_empty_to_none(data.get('phone_number')))
|
||||
if data.get('password'):
|
||||
user.set_password(data['password'])
|
||||
user.set_password(data['password'])
|
||||
if data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
|
||||
+32
-20
@@ -246,10 +246,13 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first()
|
||||
if log and log.retriever_resources:
|
||||
for r in log.retriever_resources:
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
source_url = str(r.get('source_download_url') or '')
|
||||
if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]):
|
||||
dataset_id = dataset_id or str(r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') or '').strip()
|
||||
remote_document_id = remote_document_id or str(r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or '').strip()
|
||||
resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r)
|
||||
dataset_id = dataset_id or str(resolved_dataset_id or '').strip()
|
||||
remote_document_id = remote_document_id or str(resolved_remote_document_id or '').strip()
|
||||
if dataset_id and remote_document_id:
|
||||
break
|
||||
except Exception as e:
|
||||
@@ -300,12 +303,26 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower()
|
||||
if resp.status_code == 401:
|
||||
return True
|
||||
if resp.status_code in (403, 404) and 'token=' in file_url:
|
||||
return True
|
||||
if ctype == 'application/json':
|
||||
body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower()
|
||||
if 'unauthorized' in body or '"error"' in body:
|
||||
return True
|
||||
return False
|
||||
if base_url and file_url.startswith(base_url) and ('token=' in file_url):
|
||||
|
||||
def _retry_with_refreshed_url(raw_url: str):
|
||||
refreshed_url = _resolve_latest_integration_url(raw_url)
|
||||
if not refreshed_url or refreshed_url == raw_url:
|
||||
return None, raw_url
|
||||
retry_headers = _build_headers(refreshed_url)
|
||||
try:
|
||||
return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
|
||||
return None, refreshed_url
|
||||
|
||||
if 'token=' in file_url:
|
||||
try:
|
||||
parsed = urlparse(file_url)
|
||||
qs = parse_qs(parsed.query)
|
||||
@@ -327,18 +344,20 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning('[file-preview] upstream request failed: %s', e)
|
||||
return (None, None, ('failed to fetch source file', 502))
|
||||
if base_url and file_url.startswith(base_url) and ('token=' in file_url) and _should_refresh_from_response(upstream):
|
||||
refreshed_url = _resolve_latest_integration_url(file_url)
|
||||
if refreshed_url != file_url:
|
||||
headers = _build_headers(refreshed_url)
|
||||
try:
|
||||
upstream = requests.get(refreshed_url, headers=headers, timeout=(5, 20))
|
||||
file_url = refreshed_url
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
|
||||
return (None, None, ('failed to fetch source file', 502))
|
||||
if 'token=' in file_url and _should_refresh_from_response(upstream):
|
||||
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
|
||||
if refreshed_upstream is not None:
|
||||
upstream = refreshed_upstream
|
||||
file_url = refreshed_url
|
||||
if upstream.status_code != 200:
|
||||
if 'token=' in file_url:
|
||||
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
|
||||
if refreshed_upstream is not None:
|
||||
upstream = refreshed_upstream
|
||||
file_url = refreshed_url
|
||||
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
|
||||
if upstream.status_code == 404:
|
||||
return None, None, ('source file not found', 404)
|
||||
return None, None, (f'upstream returned status {upstream.status_code}', 502)
|
||||
|
||||
content = upstream.content or b''
|
||||
@@ -1411,12 +1430,6 @@ def resolve_source_file():
|
||||
|
||||
source_ext = str(payload.get('source_ext') or '').strip().lower()
|
||||
source_download_url = payload.get('source_download_url')
|
||||
if source_ext in {'txt', 'md', 'markdown', 'csv', 'vtt', 'properties', 'html', 'htm'}:
|
||||
current_agent = getattr(g, 'current_agent', None)
|
||||
source_download_url = (
|
||||
f"{request.host_url.rstrip('/')}/api/chat/source-file-text"
|
||||
f"?agent_id={getattr(current_agent, 'id', '')}&dataset_id={dataset_id}&remote_document_id={remote_document_id}"
|
||||
)
|
||||
|
||||
return jsonify({
|
||||
'dataset_id': dataset_id,
|
||||
@@ -1649,7 +1662,6 @@ def preview_file_raw():
|
||||
# 避免在服务端走旧版转换链路导致长时间卡住。
|
||||
needs_pdf_conversion = (
|
||||
request.args.get('download') != '1'
|
||||
and original_ext in ('doc', 'ppt', 'pptx')
|
||||
and ext in ('doc', 'ppt', 'pptx')
|
||||
)
|
||||
if needs_pdf_conversion:
|
||||
|
||||
+117
-19
@@ -12,6 +12,95 @@ from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
integration_bp = Blueprint('integration', __name__)
|
||||
|
||||
|
||||
def _integration_token_secret() -> str:
|
||||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
return configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||||
|
||||
|
||||
def _decode_integration_token(token: str | None) -> dict | None:
|
||||
normalized_token = str(token or '').strip()
|
||||
if not normalized_token:
|
||||
return None
|
||||
try:
|
||||
import jwt
|
||||
payload = jwt.decode(
|
||||
normalized_token,
|
||||
_integration_token_secret(),
|
||||
algorithms=['HS256'],
|
||||
)
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"Integration API token validation failed: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def _build_download_url(document_id: int, *, kind: str, version_id: int | None = None) -> str:
|
||||
base_url = _integration_base_url()
|
||||
url = f'{base_url}/api/integration/files/{document_id}/download?kind={kind}'
|
||||
if version_id is not None:
|
||||
url += f'&version_id={version_id}'
|
||||
return url
|
||||
|
||||
|
||||
def _version_query():
|
||||
return (
|
||||
db.session.query(KbDocumentVersion)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.filter(KbDocument.is_deleted.is_(False))
|
||||
)
|
||||
|
||||
|
||||
def _resolve_requested_version(file_id: int) -> tuple[KbDocumentVersion | None, KbDocument | None]:
|
||||
requested_version_id = request.args.get('version_id', type=int)
|
||||
token_payload = _decode_integration_token(request.args.get('token'))
|
||||
if isinstance(token_payload, dict):
|
||||
token_version_id = token_payload.get('version_id')
|
||||
if token_version_id is not None:
|
||||
try:
|
||||
requested_version_id = int(token_version_id)
|
||||
except (TypeError, ValueError):
|
||||
current_app.logger.warning(
|
||||
'Integration API token carried invalid version_id: %r',
|
||||
token_version_id,
|
||||
)
|
||||
dataset_id = str(token_payload.get('dataset_id') or '').strip()
|
||||
remote_document_id = str(token_payload.get('remote_document_id') or '').strip()
|
||||
if dataset_id and remote_document_id:
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document))
|
||||
.filter(
|
||||
KbDocument.is_deleted.is_(False),
|
||||
KbDocument.id == file_id,
|
||||
KbDifySyncRecord.dataset_id == dataset_id,
|
||||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if record and record.document_version and record.document_version.document:
|
||||
return record.document_version, record.document_version.document
|
||||
|
||||
if requested_version_id is not None:
|
||||
version = (
|
||||
_version_query()
|
||||
.filter(
|
||||
KbDocumentVersion.id == requested_version_id,
|
||||
KbDocumentVersion.document_id == file_id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if version:
|
||||
return version, version.document
|
||||
|
||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||
if not document:
|
||||
return None, None
|
||||
return _current_version(document), document
|
||||
|
||||
def _require_integration_key():
|
||||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
@@ -24,15 +113,8 @@ def _require_integration_key():
|
||||
return None
|
||||
|
||||
token = request.args.get('token')
|
||||
if token:
|
||||
try:
|
||||
import jwt
|
||||
secret = configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||||
jwt.decode(token, secret, algorithms=['HS256'])
|
||||
return None
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"Integration API token validation failed: {e}")
|
||||
pass
|
||||
if token and _decode_integration_token(token):
|
||||
return None
|
||||
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
@@ -43,6 +125,23 @@ def _integration_base_url() -> str:
|
||||
return explicit
|
||||
return request.host_url.rstrip('/')
|
||||
|
||||
def _kb_storage_root() -> Path:
|
||||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
def _resolve_storage_path(path_value: str | None) -> Path | None:
|
||||
if not path_value:
|
||||
return None
|
||||
raw_path = Path(str(path_value))
|
||||
candidate = (raw_path if raw_path.is_absolute() else (_kb_storage_root() / raw_path)).resolve()
|
||||
root = _kb_storage_root()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
return candidate
|
||||
|
||||
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
@@ -57,9 +156,8 @@ def _serialize_integration_document(document: KbDocument, *, version: KbDocument
|
||||
if not version:
|
||||
abort(404, description='No current version found.')
|
||||
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
|
||||
base_url = _integration_base_url()
|
||||
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source'
|
||||
markdown_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=md' if version.cleaned_file_path or version.cleaned_preview_path else None
|
||||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||
markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None
|
||||
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
|
||||
|
||||
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
|
||||
@@ -86,15 +184,16 @@ def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: in
|
||||
|
||||
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
||||
if kind == 'source':
|
||||
path = Path(version.source_file_path)
|
||||
path = _resolve_storage_path(version.source_file_path)
|
||||
if path is None:
|
||||
raise NotFoundError('File not found on disk.')
|
||||
filename = version.source_file_name or f'document-{version.document_id}'
|
||||
return (path, filename)
|
||||
preferred = version.cleaned_file_path or version.cleaned_preview_path
|
||||
preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path)
|
||||
if not preferred:
|
||||
abort(409, description='Markdown not ready.')
|
||||
path = Path(preferred)
|
||||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||
return (path, filename)
|
||||
return (preferred, filename)
|
||||
|
||||
@integration_bp.before_request
|
||||
def _verify_integration_access():
|
||||
@@ -189,13 +288,12 @@ def resolve_files_by_dify():
|
||||
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
||||
def download_file(file_id: int):
|
||||
kind = str(request.args.get('kind') or 'md').strip().lower()
|
||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||
version, document = _resolve_requested_version(file_id)
|
||||
if not document:
|
||||
raise NotFoundError('Document not found.')
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
raise NotFoundError('No version found.')
|
||||
path, filename = _resolve_download_path(version, kind)
|
||||
if not path.exists():
|
||||
raise NotFoundError('File not found on disk.')
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
@@ -26,12 +26,9 @@ def _safe_upload_filename(raw_filename: str | None) -> str:
|
||||
original_name = Path(raw_filename or '').name.strip()
|
||||
if not original_name:
|
||||
return 'uploaded_file'
|
||||
original_path = Path(original_name)
|
||||
safe_stem = secure_filename(original_path.stem)
|
||||
suffix = original_path.suffix.lower()
|
||||
if not safe_stem:
|
||||
safe_stem = 'uploaded_file'
|
||||
return f'{safe_stem}{suffix}'
|
||||
import re
|
||||
safe_name = re.sub(r'[\\/*?:"<>|]', '_', original_name)
|
||||
return safe_name or 'uploaded_file'
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
|
||||
@@ -632,15 +632,15 @@ def login():
|
||||
if not user:
|
||||
_write_login_audit('password', 'failed', username=username, reason='user_not_found')
|
||||
db.session.commit()
|
||||
raise NotFoundError('User not found')
|
||||
raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404)
|
||||
if not user.check_password(password):
|
||||
_write_login_audit('password', 'failed', user=user, reason='incorrect_password')
|
||||
db.session.commit()
|
||||
raise UnauthorizedError('Incorrect password')
|
||||
raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401)
|
||||
if user.status != 'active':
|
||||
_write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
||||
db.session.commit()
|
||||
raise ForbiddenError('Account is disabled')
|
||||
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
|
||||
_write_login_audit('password', 'success', user=user)
|
||||
db.session.commit()
|
||||
return jsonify(_build_login_payload(user, 'password'))
|
||||
@@ -662,6 +662,8 @@ def login():
|
||||
except (OperationalError, DatabaseError) as retry_exc:
|
||||
current_app.logger.warning('Password login retry failed: %s', retry_exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('Login error: %s', e)
|
||||
|
||||
Reference in new issue
Block a user