refactor(backend): 重构后端admin和schedule部分

This commit is contained in:
sophie committed 2026-07-01 13:34:29 +08:00
1 parent 9f5493185d
commit 4a14960e01
74 files changed
+5937 -3644

No files matched your search

+4 -1
View File
@@ -2,5 +2,8 @@
backend/app/services/auth/__init__.py
用途:认证域业务(Casdoor OIDC、企微 OAuth)。
逻辑:Wave 3 从 api/user/_legacy auth 相关路由抽取。
逻辑:Wave 3 从 api/user 抽取;api/user 保留薄 re-export 兼容旧测试。
"""
from . import casdoor_service, wecom_auth_service
__all__ = ['casdoor_service', 'wecom_auth_service']
+369 -1
View File
@@ -1,5 +1,373 @@
"""
backend/app/services/auth/casdoor_service.py
用途:Casdoor OIDC 登录、token 交换、用户同步业务逻辑。
用途:Casdoor IdP 用户同步与 OAuth 错误映射(管理端创建/改密、用户域登录共用)。
依赖:flask.current_app、requests、app.core.errors。
逻辑:由 services/admin/user_service、api/user 登录路由调用。
"""
from __future__ import annotations
import ast
import json
import re
from typing import Any
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError, ValidationError
from app.models import User
def clean_str(value) -> str | None:
"""Trim 字符串;空串返回 None。"""
if value is None:
return None
if isinstance(value, str):
value = value.strip()
return value or None
return str(value).strip() or None
def is_casdoor_configured() -> bool:
"""Casdoor 基础配置是否齐全。"""
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)
def casdoor_user_owner() -> str:
"""返回 Casdoor organization owner。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def extract_error_payload(source) -> dict:
"""从 Casdoor 响应或异常文本解析 JSON 错误体。"""
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 {}
def is_user_exists_error(message: str) -> bool:
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_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
def is_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
)
def raise_user_not_in_idp(source=None) -> None:
data = extract_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]},
)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_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_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 raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_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_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_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]},
)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_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_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
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_user_missing_error(lowered):
raise_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]},
)
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""Map Casdoor OAuth/API failures to stable business error codes."""
data = extract_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_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]},
)
def build_user_profile_payload(
*,
username: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor 用户资料字段(不含 password)。"""
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_user_payload(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor add-user 请求体。"""
payload = build_user_profile_payload(
username=username,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def casdoor_add_user(user_payload: dict) -> None:
"""调用 Casdoor /api/add-user 创建 IdP 用户。"""
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_add_user_error(data)
def casdoor_update_user(user_payload: dict) -> None:
"""调用 Casdoor /api/update-user 更新 IdP 用户资料。"""
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_update_user_error(data)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor /api/set-password。"""
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_set_password_error(data)
def sync_create_user(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> None:
"""管理端创建用户时同步至 Casdoor。"""
if not is_casdoor_configured():
return
payload = build_user_payload(
username=username,
password=password,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
casdoor_add_user(payload)
def sync_admin_set_password(user: User, new_password: str) -> None:
"""管理端重设密码时同步 Casdoor(无旧密码)。"""
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_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
def sync_update_user(user: User, *, new_password: str | None = None) -> None:
"""管理端编辑用户时同步 Casdoor:仅改密;IdP 无账号则 add-user 补建。"""
if not is_casdoor_configured() or not new_password:
return
def _provision_missing_user_in_casdoor():
sync_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_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
+231 -1
View File
@@ -1,5 +1,235 @@
"""
backend/app/services/auth/wecom_auth_service.py
用途:企业微信 OAuth、绑定、解绑业务逻辑。
用途:企业微信 OAuth 身份解析、匹配规则与 access_token 缓存。
依赖:flask.current_app、requests、models.User。
逻辑:由 api/user 企微登录路由、services/admin/wecom_admin_service 调用。
"""
from __future__ import annotations
import re
from datetime import datetime, timedelta
import requests
from flask import current_app
from sqlalchemy import and_, or_
from app import db
from app.models import User
ACCESS_TOKEN_CACHE: dict = {'token': None, 'expires_at': None}
STATE_CACHE: dict = {}
BIND_SESSION_CACHE: dict = {}
ALLOWED_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
def clean_str(value) -> str | None:
if value is None:
return None
if isinstance(value, str):
value = value.strip()
return value or None
return str(value).strip() or None
def parse_field_list(raw_value, default_fields: list[str]) -> 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_MATCH_FIELDS and piece not in result:
result.append(piece)
return result or list(default_fields)
def get_config_missing_fields() -> list[str]:
"""返回缺失的企微登录配置键名。"""
missing = []
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
def is_configured() -> bool:
return len(get_config_missing_fields()) == 0
def get_access_token() -> str:
"""获取企微 access_token(带进程内缓存)。"""
now = datetime.utcnow()
token = ACCESS_TOKEN_CACHE.get('token')
expires_at = 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')
resp = requests.get(
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
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}')
ACCESS_TOKEN_CACHE['token'] = data['access_token']
ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
return data['access_token']
def normalize_mobile(mobile: str) -> str | None:
mobile = clean_str(mobile)
if not mobile:
return None
digits = re.sub(r'\D', '', mobile)
if not digits:
return mobile
if digits.startswith('0086'):
digits = digits[4:]
elif digits.startswith('86') and len(digits) > 11:
digits = digits[2:]
return digits
def extract_extattr_value(wecom_user: dict, key: str) -> str | None:
extattr = wecom_user.get('extattr') or {}
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
if not isinstance(attrs, list):
return None
for attr in attrs:
if not isinstance(attr, dict):
continue
if clean_str(attr.get('name')) != key:
continue
raw = attr.get('value')
if isinstance(raw, dict):
raw = raw.get('text') or raw.get('web') or raw.get('value')
return clean_str(raw)
return None
def get_match_config() -> tuple[list[str], str]:
raw_rules = current_app.config.get('WECOM_MATCH_RULES', 'employee_id,mobile')
rules = parse_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
def get_first_login_bind_mode() -> str:
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
def get_first_login_input_fields() -> list[str]:
raw_fields = current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email')
return parse_field_list(raw_fields, ['employee_id', 'mobile', 'email'])
def extract_identity(wecom_user: dict) -> dict:
"""从企微 user/get 响应提取标准化身份字段。"""
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_flag = bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True))
mobile = normalize_mobile(mobile_raw) if normalize_flag 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_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,
}
def _mobile_candidates(identity: dict) -> list[str]:
values = []
for item in [identity.get('mobile'), identity.get('mobile_raw')]:
item = clean_str(item)
if item and item not in values:
values.append(item)
return values
def find_users_by_input_field(field: str, value):
field = clean_str(field)
if field not in ALLOWED_MATCH_FIELDS:
return [], 'invalid_field'
if field == 'employee_id':
needle = clean_str(value)
if not needle:
return [], 'employee_id'
return db.session.query(User).filter(User.employee_id == needle).all(), None
if field == 'email':
needle = clean_str(value)
if not needle:
return [], 'email'
return db.session.query(User).filter(User.email == needle).all(), None
if field == 'mobile':
raw_mobile = clean_str(value)
normalized_mobile = normalize_mobile(raw_mobile)
candidates = []
for item in [normalized_mobile, raw_mobile]:
item = clean_str(item)
if item and item not in candidates:
candidates.append(item)
if not candidates:
return [], 'mobile'
return db.session.query(User).filter(User.phone_number.in_(candidates)).all(), None
return [], 'invalid_field'
def find_users_by_match_rules(identity: dict, rules: list, operator: str) -> tuple[list[User], list[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, []