refactor(backend): 重构后端admin和schedule部分
This commit is contained in:
1 parent
9f5493185d
commit
4a14960e01
74 files changed
+5937
-3644
No files matched your search
+33
-455
@@ -3,11 +3,11 @@ backend/app/api/user.py
|
||||
|
||||
用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、models、wecom/dify 相关 services。
|
||||
逻辑:薄路由层鉴权与参数校验;业务编排仍在本文件(Wave 3 拆至 api/user/* + services/user/*)。
|
||||
逻辑:薄路由层鉴权与参数校验;Casdoor/企微 OAuth 委托 services/auth/*。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
@@ -36,10 +36,12 @@ from app.core.errors import (
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.auth import casdoor_service as _casdoor_svc
|
||||
from app.services.auth import wecom_auth_service as _wecom_svc
|
||||
user_bp = Blueprint('user', __name__)
|
||||
_WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None}
|
||||
_WECOM_STATE_CACHE = {}
|
||||
_WECOM_BIND_SESSION_CACHE = {}
|
||||
_WECOM_ACCESS_TOKEN_CACHE = _wecom_svc.ACCESS_TOKEN_CACHE
|
||||
_WECOM_STATE_CACHE = _wecom_svc.STATE_CACHE
|
||||
_WECOM_BIND_SESSION_CACHE = _wecom_svc.BIND_SESSION_CACHE
|
||||
_PASSWORD_RESET_RATE_CACHE = {}
|
||||
_PASSWORD_RESET_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
|
||||
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
|
||||
@@ -129,26 +131,11 @@ def _run_db_with_retry(operation, *, label: str):
|
||||
return operation()
|
||||
|
||||
def _get_wecom_config_missing_fields() -> list[str]:
|
||||
"""
|
||||
列出企微集成尚未配置的环境项。
|
||||
Returns:
|
||||
缺失的配置键名列表,如 WECOM_ENABLED、WECOM_CORP_ID 等。
|
||||
"""
|
||||
missing: list[str] = []
|
||||
if not current_app.config.get('WECOM_ENABLED'):
|
||||
missing.append('WECOM_ENABLED')
|
||||
if not _clean_str(current_app.config.get('WECOM_CORP_ID')):
|
||||
missing.append('WECOM_CORP_ID')
|
||||
if not _clean_str(current_app.config.get('WECOM_AGENT_ID')):
|
||||
missing.append('WECOM_AGENT_ID')
|
||||
if not _clean_str(current_app.config.get('WECOM_SECRET')):
|
||||
missing.append('WECOM_SECRET')
|
||||
return missing
|
||||
return _wecom_svc.get_config_missing_fields()
|
||||
|
||||
|
||||
def _is_wecom_configured() -> bool:
|
||||
"""企微 Corp/Agent/Secret 与总开关均已配置时返回 True。"""
|
||||
return len(_get_wecom_config_missing_fields()) == 0
|
||||
return _wecom_svc.is_configured()
|
||||
|
||||
def _issue_casdoor_state(redirect_uri: str):
|
||||
exp_ts = int((datetime.utcnow() + timedelta(minutes=10)).timestamp())
|
||||
@@ -269,330 +256,58 @@ def _is_casdoor_login_mode() -> bool:
|
||||
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
|
||||
|
||||
def _is_casdoor_configured() -> bool:
|
||||
if not _clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
|
||||
return False
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
return bool(base and client_id and client_secret)
|
||||
return _casdoor_svc.is_casdoor_configured()
|
||||
|
||||
def _casdoor_user_owner() -> str:
|
||||
owner = _clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
|
||||
if not owner:
|
||||
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
|
||||
return owner
|
||||
return _casdoor_svc.casdoor_user_owner()
|
||||
|
||||
def _verify_casdoor_password(username: str, password: str):
|
||||
_casdoor_password_login(username, password)
|
||||
|
||||
def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str):
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
if not base or not client_id or not client_secret:
|
||||
raise RuntimeError('Casdoor is not configured')
|
||||
url = f'{base}/api/set-password'
|
||||
resp = requests.post(url, files={'userOwner': (None, user_owner), 'userName': (None, user_name), 'oldPassword': (None, old_password), 'newPassword': (None, new_password)}, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_set_password_error(data)
|
||||
return _casdoor_svc.casdoor_set_password(user_owner, user_name, old_password, new_password)
|
||||
|
||||
def _is_casdoor_user_exists_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
|
||||
return _casdoor_svc.is_user_exists_error(message)
|
||||
|
||||
def _raise_casdoor_add_user_error(source) -> None:
|
||||
"""
|
||||
将 Casdoor add-user 失败映射为稳定业务错误码,供管理端创建用户时展示。
|
||||
@param source: Casdoor JSON 响应、RuntimeError 文本或其它异常来源
|
||||
Raises:
|
||||
ConflictError: Casdoor 侧用户名/邮箱已存在
|
||||
AppError: 密码策略或 IdP 同步失败
|
||||
"""
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
lowered = (msg_text or str(source or '')).lower()
|
||||
if _is_casdoor_user_exists_error(lowered):
|
||||
raise ConflictError('Username already exists in Casdoor', code='USER.USERNAME_EXISTS', details={'field': 'username', 'technical': msg_text})
|
||||
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
|
||||
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
|
||||
raise AppError(code='CASDOOR_ADD_USER_FAILED', message='Failed to create user in authentication system. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source or '')[:300]})
|
||||
|
||||
def _build_casdoor_user_profile_payload(*, username: str, email: str, real_name=None, phone_number=None, status='active', department=None) -> dict:
|
||||
"""
|
||||
组装 Casdoor 用户资料字段(create/update 共用),不含 password。
|
||||
@param username: Casdoor name(与本地 username 一致)
|
||||
@param email: 邮箱
|
||||
@param real_name: 显示名/真实姓名
|
||||
@param phone_number: 手机号
|
||||
@param status: 本地账号状态;非 active 时 Casdoor 设为禁用
|
||||
@param department: 部门,映射至 affiliation
|
||||
Returns:
|
||||
Casdoor User JSON 对象(资料部分)
|
||||
"""
|
||||
display_name = _clean_str(real_name) or username
|
||||
payload = {
|
||||
'owner': _casdoor_user_owner(),
|
||||
'name': username,
|
||||
'email': email or '',
|
||||
'displayName': display_name,
|
||||
'realName': _clean_str(real_name) or '',
|
||||
'phone': _clean_str(phone_number) or '',
|
||||
'isForbidden': _clean_str(status) not in (None, 'active'),
|
||||
}
|
||||
department_value = _clean_str(department)
|
||||
if department_value:
|
||||
payload['affiliation'] = department_value
|
||||
return payload
|
||||
|
||||
def _build_casdoor_user_payload(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None) -> dict:
|
||||
"""
|
||||
组装 Casdoor add-user 请求体,字段与本地 User 模型对齐。
|
||||
@param username: Casdoor name(与本地 username 一致)
|
||||
@param password: 初始明文密码
|
||||
@param email: 邮箱
|
||||
@param real_name: 显示名/真实姓名
|
||||
@param phone_number: 手机号
|
||||
@param status: 本地账号状态;非 active 时 Casdoor 设为禁用
|
||||
@param department: 部门,映射至 affiliation
|
||||
Returns:
|
||||
Casdoor User JSON 对象
|
||||
"""
|
||||
payload = _build_casdoor_user_profile_payload(
|
||||
username=username,
|
||||
email=email,
|
||||
real_name=real_name,
|
||||
phone_number=phone_number,
|
||||
status=status,
|
||||
department=department,
|
||||
)
|
||||
payload['password'] = password
|
||||
return payload
|
||||
_casdoor_svc.raise_add_user_error(source)
|
||||
|
||||
def _casdoor_add_user(user_payload: dict):
|
||||
"""
|
||||
调用 Casdoor /api/add-user 创建 IdP 用户。
|
||||
核心逻辑:使用 Client ID/Secret Basic Auth,与 set-password 管理 API 一致。
|
||||
@param user_payload: Casdoor User 对象(owner/name/password 等)
|
||||
Raises:
|
||||
RuntimeError: HTTP 或配置异常
|
||||
AppError: Casdoor 返回业务错误(经 _raise_casdoor_add_user_error 映射)
|
||||
"""
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
if not base or not client_id or not client_secret:
|
||||
raise RuntimeError('Casdoor is not configured')
|
||||
url = f'{base}/api/add-user'
|
||||
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_add_user_error(data)
|
||||
return _casdoor_svc.casdoor_add_user(user_payload)
|
||||
|
||||
def _sync_casdoor_create_user(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None):
|
||||
"""
|
||||
管理端创建用户时同步至 Casdoor,与改密逻辑一致:Casdoor 已配置则必须成功,否则跳过。
|
||||
核心逻辑:构建 add-user payload → 调 _casdoor_add_user;本地库 commit 由调用方负责。
|
||||
@param username: 本地 username,同步为 Casdoor name
|
||||
@param password: 初始明文密码
|
||||
@param email: 邮箱
|
||||
@param real_name: 真实姓名
|
||||
@param phone_number: 手机号
|
||||
@param status: 本地账号状态
|
||||
@param department: 部门
|
||||
Raises:
|
||||
AppError / ConflictError: Casdoor 创建失败
|
||||
"""
|
||||
if not _is_casdoor_configured():
|
||||
return
|
||||
payload = _build_casdoor_user_payload(
|
||||
username=username,
|
||||
password=password,
|
||||
email=email,
|
||||
real_name=real_name,
|
||||
phone_number=phone_number,
|
||||
status=status,
|
||||
department=department,
|
||||
)
|
||||
_casdoor_add_user(payload)
|
||||
return _casdoor_svc.sync_create_user(username=username, password=password, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department)
|
||||
|
||||
def _raise_casdoor_update_user_error(source) -> None:
|
||||
"""
|
||||
将 Casdoor update-user 失败映射为稳定业务错误码,供管理端编辑用户时展示。
|
||||
@param source: Casdoor JSON 响应、RuntimeError 文本或其它异常来源
|
||||
Raises:
|
||||
ConflictError: Casdoor 侧邮箱等唯一字段冲突
|
||||
AppError: IdP 同步失败
|
||||
"""
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
lowered = (msg_text or str(source or '')).lower()
|
||||
if _is_casdoor_user_missing_error(lowered):
|
||||
_raise_casdoor_user_not_in_idp(source)
|
||||
if _is_casdoor_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
|
||||
raise ConflictError('Email already exists in Casdoor', code='USER.EMAIL_EXISTS', details={'field': 'email', 'technical': msg_text})
|
||||
raise AppError(code='CASDOOR_UPDATE_USER_FAILED', message='Failed to update user in authentication system. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source or '')[:300]})
|
||||
_casdoor_svc.raise_update_user_error(source)
|
||||
|
||||
def _casdoor_update_user(user_payload: dict):
|
||||
"""
|
||||
调用 Casdoor /api/update-user 更新 IdP 用户资料。
|
||||
核心逻辑:使用 Client ID/Secret Basic Auth,与 add-user/set-password 管理 API 一致。
|
||||
@param user_payload: Casdoor User 对象(owner/name 及待更新字段)
|
||||
Raises:
|
||||
RuntimeError: HTTP 或配置异常
|
||||
AppError: Casdoor 返回业务错误(经 _raise_casdoor_update_user_error 映射)
|
||||
"""
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
if not base or not client_id or not client_secret:
|
||||
raise RuntimeError('Casdoor is not configured')
|
||||
url = f'{base}/api/update-user'
|
||||
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_update_user_error(data)
|
||||
return _casdoor_svc.casdoor_update_user(user_payload)
|
||||
|
||||
def _sync_casdoor_admin_set_password(user: User, new_password: str):
|
||||
"""
|
||||
管理端重设密码时同步 Casdoor(无旧密码,与 token 重置一致)。
|
||||
IdP 用户不存在时抛出 CASDOOR_USER_NOT_IN_IDP,由上层决定是否 fallback add-user。
|
||||
@param user: 本地用户
|
||||
@param new_password: 新密码明文
|
||||
Raises:
|
||||
AppError: Casdoor 策略或 IdP 同步失败
|
||||
"""
|
||||
if not _is_casdoor_configured():
|
||||
return
|
||||
user_owner = _casdoor_user_owner()
|
||||
try:
|
||||
_casdoor_set_password(user_owner, user.username, '', new_password)
|
||||
except RuntimeError as exc:
|
||||
if _is_casdoor_user_missing_error(str(exc)):
|
||||
_raise_casdoor_user_not_in_idp(exc)
|
||||
_raise_casdoor_set_password_error(exc)
|
||||
return _casdoor_svc.sync_admin_set_password(user, new_password)
|
||||
|
||||
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
|
||||
"""
|
||||
管理端编辑用户时同步 Casdoor:仅改密时 set-password;IdP 无账号则 add-user 补建。
|
||||
核心逻辑:资料字段只写本地库,不调用 update-user;无新密码则跳过 Casdoor。
|
||||
@param user: 已应用本地变更但未 commit 的 User 实例
|
||||
@param new_password: 管理员设置的新密码;None 表示不改密
|
||||
Raises:
|
||||
AppError / ConflictError: Casdoor 改密或补建失败
|
||||
"""
|
||||
if not _is_casdoor_configured() or not new_password:
|
||||
return
|
||||
|
||||
def _provision_missing_user_in_casdoor():
|
||||
_sync_casdoor_create_user(
|
||||
username=user.username,
|
||||
password=new_password,
|
||||
email=user.email,
|
||||
real_name=user.real_name,
|
||||
phone_number=user.phone_number,
|
||||
status=user.status,
|
||||
department=user.department,
|
||||
)
|
||||
|
||||
try:
|
||||
_sync_casdoor_admin_set_password(user, new_password)
|
||||
except AppError as exc:
|
||||
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
|
||||
_provision_missing_user_in_casdoor()
|
||||
return
|
||||
raise
|
||||
return _casdoor_svc.sync_update_user(user, new_password=new_password)
|
||||
|
||||
def _is_casdoor_password_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
|
||||
return _casdoor_svc.is_password_error(message)
|
||||
|
||||
def _is_casdoor_user_missing_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return (
|
||||
"doesn't exist" in lowered
|
||||
or 'does not exist' in lowered
|
||||
or 'user not found' in lowered
|
||||
or 'no such user' in lowered
|
||||
)
|
||||
return _casdoor_svc.is_user_missing_error(message)
|
||||
|
||||
def _raise_casdoor_user_not_in_idp(source=None) -> None:
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
raise AppError(
|
||||
code='CASDOOR_USER_NOT_IN_IDP',
|
||||
message='Your account has not been registered in the authentication system. Please contact the administrator.',
|
||||
http_status=409,
|
||||
details={'technical': msg_text or str(source or '')[:300]},
|
||||
)
|
||||
_casdoor_svc.raise_user_not_in_idp(source)
|
||||
|
||||
def _extract_casdoor_error_payload(source) -> dict:
|
||||
if isinstance(source, dict):
|
||||
return source
|
||||
text = str(source or '')
|
||||
match = re.search(r'\{.*\}', text, re.DOTALL)
|
||||
if match:
|
||||
try:
|
||||
parsed = ast.literal_eval(match.group(0))
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
except (SyntaxError, ValueError):
|
||||
pass
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
return {}
|
||||
return _casdoor_svc.extract_error_payload(source)
|
||||
|
||||
def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||||
"""
|
||||
Map Casdoor OAuth/API failures to stable business error codes for frontend i18n.
|
||||
context: password | verify | code | refresh
|
||||
"""
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
raw = str(source or '')
|
||||
oauth_error = _clean_str(data.get('error')).lower()
|
||||
if not oauth_error and 'invalid_grant' in raw.lower():
|
||||
oauth_error = 'invalid_grant'
|
||||
if not oauth_error and 'invalid_client' in raw.lower():
|
||||
oauth_error = 'invalid_client'
|
||||
if oauth_error == 'invalid_grant' or _is_casdoor_password_error(raw):
|
||||
if context in ('password', 'verify'):
|
||||
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
|
||||
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
|
||||
if oauth_error in ('invalid_client', 'unauthorized_client'):
|
||||
raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is misconfigured. Please contact the administrator.', http_status=503, details={'casdoor_error': oauth_error})
|
||||
if oauth_error == 'access_denied':
|
||||
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
|
||||
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
|
||||
raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is not configured. Please contact the administrator.', http_status=503)
|
||||
if 'invalid or expired casdoor state' in raw.lower():
|
||||
raise ValidationError('Invalid or expired Casdoor state')
|
||||
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
|
||||
raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=status_code, details={'casdoor_error': oauth_error or None, 'technical': raw[:300]})
|
||||
_casdoor_svc.raise_auth_error(source, context=context, status_code=status_code)
|
||||
|
||||
def _raise_casdoor_set_password_error(source) -> None:
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
lowered = (msg_text or str(source or '')).lower()
|
||||
if _is_casdoor_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
|
||||
_raise_incorrect_current_password()
|
||||
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
|
||||
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
|
||||
if _is_casdoor_user_missing_error(lowered):
|
||||
_raise_casdoor_user_not_in_idp(source)
|
||||
raise AppError(code='CASDOOR_SET_PASSWORD_FAILED', message='Failed to change password. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source)[:300]})
|
||||
_casdoor_svc.raise_set_password_error(source)
|
||||
|
||||
def _raise_incorrect_current_password():
|
||||
raise AppError(
|
||||
@@ -690,17 +405,7 @@ def _consume_wecom_bind_session(token: str):
|
||||
return identity
|
||||
|
||||
def _parse_wecom_field_list(raw_value, default_fields: list[str]):
|
||||
if isinstance(raw_value, str):
|
||||
pieces = [item.strip().lower() for item in raw_value.split(',')]
|
||||
elif isinstance(raw_value, (list, tuple)):
|
||||
pieces = [str(item).strip().lower() for item in raw_value]
|
||||
else:
|
||||
pieces = []
|
||||
result = []
|
||||
for piece in pieces:
|
||||
if piece in _ALLOWED_WECOM_MATCH_FIELDS and piece not in result:
|
||||
result.append(piece)
|
||||
return result or list(default_fields)
|
||||
return _wecom_svc.parse_field_list(raw_value, default_fields)
|
||||
|
||||
def _verify_wecom_msg_signature(msg_signature: str, token: str, timestamp: str, nonce: str, encrypt: str) -> bool:
|
||||
if not msg_signature or not token or (not encrypt):
|
||||
@@ -728,21 +433,7 @@ def _persist_wecom_callback_audit(*, msg_signature, timestamp, nonce, encrypt_ra
|
||||
db.session.rollback()
|
||||
|
||||
def _get_wecom_access_token():
|
||||
now = datetime.utcnow()
|
||||
token = _WECOM_ACCESS_TOKEN_CACHE.get('token')
|
||||
expires_at = _WECOM_ACCESS_TOKEN_CACHE.get('expires_at')
|
||||
if token and expires_at and (now < expires_at):
|
||||
return token
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
secret = current_app.config.get('WECOM_SECRET')
|
||||
token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
|
||||
resp = requests.get(token_url, params={'corpid': corp_id, 'corpsecret': secret}, timeout=8)
|
||||
data = resp.json()
|
||||
if data.get('errcode') != 0 or not data.get('access_token'):
|
||||
raise RuntimeError(f'Failed to fetch WeCom token: {data}')
|
||||
_WECOM_ACCESS_TOKEN_CACHE['token'] = data['access_token']
|
||||
_WECOM_ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||||
return data['access_token']
|
||||
return _wecom_svc.get_access_token()
|
||||
|
||||
def _build_login_payload(user: User, source: str='password', bind_status: str=None):
|
||||
payload = {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': source, 'access_token': issue_local_access_token(user), 'token_type': 'Bearer'}
|
||||
@@ -796,39 +487,16 @@ def _extract_wecom_extattr_value(wecom_user: dict, key: str):
|
||||
return None
|
||||
|
||||
def _get_wecom_match_config():
|
||||
raw_rules = current_app.config.get('WECOM_MATCH_RULES', 'employee_id,mobile')
|
||||
rules = _parse_wecom_field_list(raw_rules, ['employee_id', 'mobile'])
|
||||
operator = str(current_app.config.get('WECOM_MATCH_OPERATOR', 'AND')).upper()
|
||||
if operator not in {'AND', 'OR'}:
|
||||
operator = 'AND'
|
||||
return (rules, operator)
|
||||
return _wecom_svc.get_match_config()
|
||||
|
||||
def _get_wecom_first_login_bind_mode():
|
||||
mode = _clean_str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE')) or 'match_rules'
|
||||
mode = mode.lower()
|
||||
if mode not in {'match_rules', 'input_verify'}:
|
||||
mode = 'match_rules'
|
||||
return mode
|
||||
return _wecom_svc.get_first_login_bind_mode()
|
||||
|
||||
def _get_wecom_first_login_input_fields():
|
||||
raw_fields = current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email')
|
||||
return _parse_wecom_field_list(raw_fields, ['employee_id', 'mobile', 'email'])
|
||||
return _wecom_svc.get_first_login_input_fields()
|
||||
|
||||
def _extract_wecom_identity(wecom_user: dict):
|
||||
userid = _clean_str(wecom_user.get('userid'))
|
||||
unionid = _clean_str(wecom_user.get('unionid'))
|
||||
email = _clean_str(wecom_user.get('email'))
|
||||
mobile_raw = _clean_str(wecom_user.get('mobile'))
|
||||
normalize_mobile = bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True))
|
||||
mobile = _normalize_mobile(mobile_raw) if normalize_mobile else mobile_raw
|
||||
employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
|
||||
if employee_id_source == 'userid':
|
||||
employee_id = userid
|
||||
elif employee_id_source.startswith('extattr:'):
|
||||
employee_id = _extract_wecom_extattr_value(wecom_user, employee_id_source.split(':', 1)[1])
|
||||
else:
|
||||
employee_id = _clean_str(wecom_user.get(employee_id_source))
|
||||
return {'wecom_userid': userid, 'wecom_unionid': unionid, 'name': _clean_str(wecom_user.get('name')) or userid or 'wecom_user', 'email': email, 'mobile': mobile, 'mobile_raw': mobile_raw, 'employee_id': employee_id}
|
||||
return _wecom_svc.extract_identity(wecom_user)
|
||||
|
||||
def _mobile_candidates(identity: dict):
|
||||
values = []
|
||||
@@ -866,34 +534,7 @@ def _find_users_by_input_field(field: str, value):
|
||||
return ([], 'invalid_field')
|
||||
|
||||
def _find_users_by_match_rules(identity: dict, rules: list, operator: str):
|
||||
filters = []
|
||||
missing = []
|
||||
for rule in rules:
|
||||
if rule == 'employee_id':
|
||||
employee_id = _clean_str(identity.get('employee_id'))
|
||||
if not employee_id:
|
||||
missing.append('employee_id')
|
||||
else:
|
||||
filters.append(User.employee_id == employee_id)
|
||||
elif rule == 'mobile':
|
||||
candidates = _mobile_candidates(identity)
|
||||
if not candidates:
|
||||
missing.append('mobile')
|
||||
else:
|
||||
filters.append(User.phone_number.in_(candidates))
|
||||
elif rule == 'email':
|
||||
email = _clean_str(identity.get('email'))
|
||||
if not email:
|
||||
missing.append('email')
|
||||
else:
|
||||
filters.append(User.email == email)
|
||||
if missing:
|
||||
return ([], missing)
|
||||
if not filters:
|
||||
return ([], ['match_rules'])
|
||||
clause = and_(*filters) if operator == 'AND' else or_(*filters)
|
||||
users = db.session.query(User).filter(clause).all()
|
||||
return (users, [])
|
||||
return _wecom_svc.find_users_by_match_rules(identity, rules, operator)
|
||||
|
||||
def _assert_wecom_binding_not_occupied(user: User, identity: dict):
|
||||
wecom_userid = identity.get('wecom_userid')
|
||||
@@ -2168,66 +1809,3 @@ def get_db():
|
||||
from app import db
|
||||
u = db.session.query(User).filter_by(username='26040006').first()
|
||||
return jsonify({'db': current_app.config.get('SQLALCHEMY_DATABASE_URI'), 'user': u.username if u else None})
|
||||
|
||||
@user_bp.route('/announcements', methods=['GET'])
|
||||
def get_announcements():
|
||||
"""
|
||||
Get active announcements (Public)
|
||||
"""
|
||||
|
||||
def _load_announcements():
|
||||
anns = db.session.query(Announcement.id, Announcement.title, Announcement.content, Announcement.created_at).filter(Announcement.is_active.is_(True)).order_by(Announcement.created_at.desc()).all()
|
||||
return jsonify([{'id': a.id, 'title': a.title, 'content': a.content, 'created_at': a.created_at.isoformat()} for a in anns])
|
||||
try:
|
||||
return _run_db_with_retry(_load_announcements, label='user.announcements')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('user.announcements retry failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
|
||||
@user_bp.route('/announcements', methods=['POST'])
|
||||
def create_announcement():
|
||||
"""
|
||||
Create announcement (Admin only)
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user or user.role != 'admin':
|
||||
raise ForbiddenError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('content'):
|
||||
raise ValidationError('Missing fields')
|
||||
ann = Announcement(title=data['title'], content=data['content'], is_active=True)
|
||||
db.session.add(ann)
|
||||
db.session.commit()
|
||||
return (jsonify({'message': 'Created', 'id': ann.id}), 201)
|
||||
|
||||
@user_bp.route('/announcements/<int:id>', methods=['PUT'])
|
||||
def update_announcement(id):
|
||||
"""
|
||||
更新公告(仅管理员)。
|
||||
|
||||
核心逻辑:校验 title/content 非空后更新 Announcement 记录。
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user or user.role != 'admin':
|
||||
raise ForbiddenError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('content'):
|
||||
raise ValidationError('Missing fields')
|
||||
ann = db.session.get(Announcement, id)
|
||||
if not ann:
|
||||
raise NotFoundError('Not found')
|
||||
ann.title = data['title']
|
||||
ann.content = data['content']
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Updated'})
|
||||
|
||||
@user_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
||||
def delete_announcement(id):
|
||||
user = _get_current_user()
|
||||
if not user or user.role != 'admin':
|
||||
raise ForbiddenError('Unauthorized')
|
||||
ann = db.session.get(Announcement, id)
|
||||
if ann:
|
||||
db.session.delete(ann)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Deleted'})
|
||||
Reference in new issue
Block a user