Co-authored-by: Cursor <cursoragent@cursor.com> # Conflicts: # backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py # backend/app/services/voucher_check/schedule_seed.py # docs/features/shipping-notice/technical.md # docs/tec.md # frontend/src/features/user/views/UserProfilePage.vue
632 lines
27 KiB
Python
632 lines
27 KiB
Python
"""
|
|
api/user/auth_support.py
|
|
|
|
用途:承载用户认证域的共享操作,包括 Casdoor 兼容适配、企微身份匹配、登录审计和短时状态。
|
|
依赖:services/auth、services/wecom_auth_service、models.User/LoginAudit/WecomCallbackAudit。
|
|
逻辑:auth_* 路由模块调用本文件完成领域协作;auth.py 兼容门面转发历史测试替身,不再保留路由实现。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from flask import request, jsonify, current_app
|
|
from app import db
|
|
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.agent_registry.serialization import serialize_registry_fields
|
|
from app.services.integrations.wecom.notify import mark_wecom_message_opened, send_wecom_event_message
|
|
from app.services.integrations.wecom.crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
|
from app.core.auth.jwt import get_current_user as _auth_current_user, issue_local_access_token
|
|
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
|
from sqlalchemy import and_, or_, inspect, insert
|
|
from datetime import datetime, timedelta
|
|
import uuid
|
|
import requests
|
|
from urllib.parse import quote
|
|
import re
|
|
import ast
|
|
from app.core.errors import (
|
|
AppError,
|
|
ConflictError,
|
|
ForbiddenError,
|
|
NotFoundError,
|
|
ServiceUnavailableError,
|
|
UnauthorizedError,
|
|
ValidationError,
|
|
raise_for_status,
|
|
)
|
|
from app.services.auth import casdoor_service as _casdoor_svc
|
|
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions
|
|
from app.services.auth.hxops.login_service import HxopsLoginService
|
|
from app.services.auth.hxops import casdoor_route_adapter as _casdoor_route_adapter
|
|
from app.services.auth import wecom_auth_service as _wecom_svc
|
|
_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'}
|
|
_LOGIN_AUDIT_COLUMNS_CACHE = None
|
|
|
|
|
|
def _token_brief(token: str) -> str:
|
|
if not token:
|
|
return 'empty'
|
|
text = str(token)
|
|
if len(text) <= 16:
|
|
return f'len={len(text)}:{text}'
|
|
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
|
|
|
def _is_users_pk_sequence_error(exc: Exception) -> bool:
|
|
message = str(exc)
|
|
return 'null value in column "id"' in message and 'relation "users"' in message
|
|
|
|
class WeComLoginError(AppError):
|
|
def __init__(self, error: str, error_code: str, status_code: int, reason: str = None, extra: dict = None):
|
|
details = dict(extra or {})
|
|
if reason:
|
|
details['reason'] = reason
|
|
super().__init__(code=error_code, message=error, http_status=status_code, details=details)
|
|
self.error = error
|
|
self.error_code = error_code
|
|
self.status_code = status_code
|
|
self.reason = reason
|
|
self.extra = extra or {}
|
|
|
|
def _write_login_audit(source: str, status: str, user: User=None, username: str=None, reason: str=None, wecom_userid: str=None, error_code: str=None, match_rules: list=None, match_operator: str=None, match_result: str=None):
|
|
payload = {'user_id': user.id if user else None, 'username': username or (user.username if user else None), 'source': source, 'status': status, 'reason': reason, 'error_code': error_code, 'match_rules': ','.join(match_rules) if isinstance(match_rules, list) else match_rules, 'match_operator': match_operator, 'match_result': match_result, 'wecom_userid': wecom_userid, 'ip': request.headers.get('X-Forwarded-For', request.remote_addr), 'user_agent': (request.user_agent.string or '')[:255], 'created_at': datetime.utcnow()}
|
|
try:
|
|
supported_columns = _get_login_audit_supported_columns()
|
|
if not supported_columns:
|
|
return
|
|
filtered_payload = {key: value for key, value in payload.items() if key in supported_columns}
|
|
if not filtered_payload:
|
|
return
|
|
_execute_login_audit_insert(filtered_payload)
|
|
except Exception:
|
|
pass
|
|
|
|
def _get_login_audit_supported_columns():
|
|
global _LOGIN_AUDIT_COLUMNS_CACHE
|
|
if _LOGIN_AUDIT_COLUMNS_CACHE is not None:
|
|
return _LOGIN_AUDIT_COLUMNS_CACHE
|
|
try:
|
|
columns = {column['name'] for column in inspect(db.engine).get_columns(LoginAudit.__tablename__)}
|
|
except Exception:
|
|
columns = set()
|
|
_LOGIN_AUDIT_COLUMNS_CACHE = columns
|
|
return columns
|
|
|
|
def _execute_login_audit_insert(payload: dict):
|
|
nested = db.session.begin_nested()
|
|
try:
|
|
db.session.execute(insert(LoginAudit.__table__).values(**payload))
|
|
db.session.flush()
|
|
nested.commit()
|
|
except Exception:
|
|
nested.rollback()
|
|
raise
|
|
|
|
def _get_current_user():
|
|
"""
|
|
Resolve current authenticated user for API handlers.
|
|
|
|
Behavior:
|
|
1) Prefer JWT Bearer token validation (Casdoor JWKS).
|
|
2) Optional legacy header fallback depends on AUTH_LEGACY_HEADER_ENABLED.
|
|
3) Returns None when authentication cannot be established.
|
|
"""
|
|
return _auth_current_user()
|
|
|
|
def _run_db_with_retry(operation, *, label: str):
|
|
try:
|
|
return operation()
|
|
except (OperationalError, DatabaseError) as exc:
|
|
current_app.logger.warning('%s failed on first attempt: %s', label, exc)
|
|
db.session.rollback()
|
|
db.session.remove()
|
|
try:
|
|
db.engine.dispose()
|
|
except Exception as dispose_exc:
|
|
current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc)
|
|
return operation()
|
|
|
|
def _get_wecom_config_missing_fields() -> list[str]:
|
|
return _wecom_svc.get_config_missing_fields()
|
|
|
|
|
|
def _is_wecom_configured() -> bool:
|
|
return _wecom_svc.is_configured()
|
|
|
|
def _issue_casdoor_state(redirect_uri: str):
|
|
"""兼容旧调用点:签发格式不变的 Casdoor state。"""
|
|
return _casdoor_route_adapter.issue_casdoor_state(redirect_uri)
|
|
|
|
def _consume_casdoor_state(state: str):
|
|
"""兼容旧调用点:校验 Casdoor state 并恢复签名绑定的 redirect_uri。"""
|
|
return _casdoor_route_adapter.consume_casdoor_state(state)
|
|
|
|
def _get_casdoor_oidc_metadata():
|
|
"""兼容旧调用点:委托公共 CasdoorClient 获取 discovery 文档。"""
|
|
return _casdoor_route_adapter.get_oidc_metadata()
|
|
|
|
|
|
def _build_casdoor_authorize_payload(options: CasdoorAuthorizeOptions) -> dict[str, str]:
|
|
"""兼容入口:使用旧 discovery/state 替换点构造 Casdoor 授权响应。"""
|
|
return _casdoor_route_adapter.build_authorize_payload(
|
|
options,
|
|
oidc_metadata=_get_casdoor_oidc_metadata,
|
|
issue_state=_issue_casdoor_state,
|
|
)
|
|
|
|
def _resolve_user_from_casdoor_claims(claims: dict):
|
|
"""兼容旧调用点:通过公共身份对象映射 HXOPS 用户。"""
|
|
from app.services.auth.casdoor.identity import identity_from_claims
|
|
from app.services.auth.common import IdentityValidationError
|
|
from app.services.auth.hxops.user_resolver import HxopsIdentityMappingError, resolve_hxops_user
|
|
|
|
try:
|
|
identity = identity_from_claims(
|
|
claims,
|
|
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
|
|
)
|
|
return resolve_hxops_user(identity)
|
|
except IdentityValidationError as exc:
|
|
raise AppError(
|
|
code='AUTH.CASDOOR_IDENTITY_INVALID',
|
|
message='Casdoor identity is missing issuer or subject',
|
|
http_status=401,
|
|
) from exc
|
|
except HxopsIdentityMappingError as exc:
|
|
raise WeComLoginError(error=str(exc), error_code=exc.code, status_code=exc.status) from exc
|
|
|
|
|
|
def _issue_casdoor_api_token(user: User, claims: dict) -> str:
|
|
"""
|
|
为已通过 Casdoor 认证的用户签发 HXOPS API 会话 JWT。
|
|
|
|
Args:
|
|
user: 已映射成功的 HXOPS 本地用户。
|
|
claims: Casdoor ID token 或 userinfo 返回的可信身份声明。
|
|
|
|
Returns:
|
|
HXOPS 本地签名 JWT,其中保留 Casdoor issuer/subject 供跨系统 SSO 使用。
|
|
|
|
Raises:
|
|
AppError: Casdoor 未返回稳定 subject,不能建立可复用身份。
|
|
"""
|
|
from app.services.auth.casdoor.identity import identity_from_claims
|
|
from app.services.auth.common import IdentityValidationError
|
|
from app.services.auth.hxops.session_token import issue_hxops_access_token
|
|
|
|
try:
|
|
identity = identity_from_claims(
|
|
claims,
|
|
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or claims.get('iss') or ''),
|
|
)
|
|
except IdentityValidationError as exc:
|
|
raise AppError(
|
|
code='AUTH.CASDOOR_IDENTITY_INVALID',
|
|
message='Casdoor identity is missing issuer or subject',
|
|
http_status=401,
|
|
) from exc
|
|
return issue_hxops_access_token(user, identity)
|
|
|
|
def _casdoor_exchange_code(code: str, redirect_uri: str):
|
|
"""兼容旧测试替换点:委托公共客户端执行 authorization code grant。"""
|
|
return _casdoor_route_adapter.authorization_code_login(code, redirect_uri)
|
|
|
|
def _casdoor_refresh_token(refresh_token: str):
|
|
"""兼容旧测试替换点:委托公共客户端执行 refresh grant。"""
|
|
return _casdoor_route_adapter.refresh_token(refresh_token)
|
|
|
|
def _casdoor_userinfo(access_token: str):
|
|
"""兼容旧测试替换点:委托公共客户端读取 userinfo。"""
|
|
return _casdoor_route_adapter.userinfo(access_token)
|
|
|
|
def _casdoor_password_login(username: str, password: str):
|
|
"""
|
|
Resource-owner password login against Casdoor token endpoint.
|
|
Requires the Casdoor application to enable password grant.
|
|
"""
|
|
return _casdoor_route_adapter.password_login(username, password)
|
|
|
|
|
|
def _hxops_login_service() -> HxopsLoginService:
|
|
"""创建使用当前兼容代理的登录服务,使既有 monkeypatch 测试和调用方式保持有效。"""
|
|
return _casdoor_route_adapter.create_login_service(
|
|
write_login_audit=_write_login_audit,
|
|
password_operation=_casdoor_password_login,
|
|
code_operation=_casdoor_exchange_code,
|
|
refresh_operation=_casdoor_refresh_token,
|
|
userinfo_operation=_casdoor_userinfo,
|
|
)
|
|
|
|
def _is_casdoor_login_mode() -> bool:
|
|
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
|
|
|
|
def _is_casdoor_configured() -> bool:
|
|
return _casdoor_svc.is_casdoor_configured()
|
|
|
|
def _casdoor_user_owner() -> str:
|
|
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):
|
|
return _casdoor_svc.casdoor_set_password(user_owner, user_name, old_password, new_password)
|
|
|
|
def _is_casdoor_user_exists_error(message: str) -> bool:
|
|
return _casdoor_svc.is_user_exists_error(message)
|
|
|
|
def _raise_casdoor_add_user_error(source) -> None:
|
|
_casdoor_svc.raise_add_user_error(source)
|
|
|
|
def _casdoor_add_user(user_payload: dict):
|
|
return _casdoor_svc.casdoor_add_user(user_payload)
|
|
|
|
def _sync_casdoor_create_user(*, username: str, password: str, email: str, employee_id: str | None = None, real_name=None, phone_number=None, status='active', department=None):
|
|
"""兼容入口:同步创建 Casdoor 用户,并传递认证主映射工号。"""
|
|
return _casdoor_svc.sync_create_user(username=username, password=password, employee_id=employee_id, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department)
|
|
|
|
def _raise_casdoor_update_user_error(source) -> None:
|
|
_casdoor_svc.raise_update_user_error(source)
|
|
|
|
def _casdoor_update_user(user_payload: dict):
|
|
return _casdoor_svc.casdoor_update_user(user_payload)
|
|
|
|
def _sync_casdoor_admin_set_password(user: User, new_password: str):
|
|
return _casdoor_svc.sync_admin_set_password(user, new_password)
|
|
|
|
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
|
|
return _casdoor_svc.sync_update_user(user, new_password=new_password)
|
|
|
|
def _is_casdoor_password_error(message: str) -> bool:
|
|
return _casdoor_svc.is_password_error(message)
|
|
|
|
def _is_casdoor_user_missing_error(message: str) -> bool:
|
|
return _casdoor_svc.is_user_missing_error(message)
|
|
|
|
def _raise_casdoor_user_not_in_idp(source=None) -> None:
|
|
_casdoor_svc.raise_user_not_in_idp(source)
|
|
|
|
def _extract_casdoor_error_payload(source) -> dict:
|
|
return _casdoor_svc.extract_error_payload(source)
|
|
|
|
def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
|
_casdoor_svc.raise_auth_error(source, context=context, status_code=status_code)
|
|
|
|
def _raise_casdoor_set_password_error(source) -> None:
|
|
_casdoor_svc.raise_set_password_error(source)
|
|
|
|
def _raise_incorrect_current_password():
|
|
raise AppError(
|
|
code='AUTH.INCORRECT_CURRENT_PASSWORD',
|
|
message='Incorrect current password',
|
|
http_status=403,
|
|
)
|
|
|
|
def _verify_current_password_for_change(user, current_password: str):
|
|
if user.check_password(current_password):
|
|
return
|
|
if not _is_casdoor_configured():
|
|
_raise_incorrect_current_password()
|
|
try:
|
|
_verify_casdoor_password(user.username, current_password)
|
|
except AppError as e:
|
|
if e.code == 'CASDOOR_INVALID_CREDENTIALS':
|
|
_raise_incorrect_current_password()
|
|
raise
|
|
except RuntimeError as e:
|
|
if _is_casdoor_password_error(str(e)):
|
|
_raise_incorrect_current_password()
|
|
raise
|
|
|
|
def _sync_casdoor_password(username: str, current_password: str, new_password: str):
|
|
"""将用户自助改密同步到 Casdoor;新密码未变化原样抛出,原密码错误转为 403。"""
|
|
if not _is_casdoor_configured():
|
|
return
|
|
user_owner = _casdoor_user_owner()
|
|
try:
|
|
_casdoor_set_password(user_owner, username, current_password, new_password)
|
|
except AppError as first_error:
|
|
if first_error.code == 'AUTH.PASSWORD_UNCHANGED':
|
|
raise
|
|
if first_error.code in ('CASDOOR_INVALID_CREDENTIALS', 'AUTH.INCORRECT_CURRENT_PASSWORD'):
|
|
_raise_incorrect_current_password()
|
|
raise
|
|
except RuntimeError as first_error:
|
|
if _is_casdoor_user_missing_error(str(first_error)):
|
|
_raise_casdoor_user_not_in_idp(first_error)
|
|
if _is_casdoor_password_error(str(first_error)):
|
|
_raise_incorrect_current_password()
|
|
try:
|
|
_casdoor_set_password(user_owner, username, '', new_password)
|
|
except RuntimeError:
|
|
raise first_error
|
|
|
|
def _cleanup_wecom_state_cache():
|
|
now = datetime.utcnow()
|
|
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
|
|
for k in expired:
|
|
_WECOM_STATE_CACHE.pop(k, None)
|
|
|
|
def _issue_wecom_state():
|
|
_cleanup_wecom_state_cache()
|
|
state = f'hxops_wecom_{uuid.uuid4().hex}'
|
|
_WECOM_STATE_CACHE[state] = datetime.utcnow() + timedelta(minutes=10)
|
|
return state
|
|
|
|
def _consume_wecom_state(state: str):
|
|
if not state:
|
|
return False
|
|
_cleanup_wecom_state_cache()
|
|
exp = _WECOM_STATE_CACHE.pop(state, None)
|
|
return bool(exp and exp > datetime.utcnow())
|
|
|
|
def _cleanup_wecom_bind_session_cache():
|
|
now = datetime.utcnow()
|
|
expired = [key for key, item in _WECOM_BIND_SESSION_CACHE.items() if not isinstance(item, dict) or not item.get('expires_at') or item['expires_at'] < now]
|
|
for key in expired:
|
|
_WECOM_BIND_SESSION_CACHE.pop(key, None)
|
|
|
|
def _issue_wecom_bind_session(identity: dict):
|
|
_cleanup_wecom_bind_session_cache()
|
|
token = f'hxops_wecom_bind_{uuid.uuid4().hex}'
|
|
_WECOM_BIND_SESSION_CACHE[token] = {'expires_at': datetime.utcnow() + timedelta(minutes=10), 'identity': dict(identity or {})}
|
|
return token
|
|
|
|
def _get_wecom_bind_session(token: str):
|
|
if not token:
|
|
return None
|
|
_cleanup_wecom_bind_session_cache()
|
|
item = _WECOM_BIND_SESSION_CACHE.get(token)
|
|
if not isinstance(item, dict):
|
|
return None
|
|
expires_at = item.get('expires_at')
|
|
if not expires_at or expires_at < datetime.utcnow():
|
|
_WECOM_BIND_SESSION_CACHE.pop(token, None)
|
|
return None
|
|
identity = item.get('identity')
|
|
return identity if isinstance(identity, dict) else None
|
|
|
|
def _consume_wecom_bind_session(token: str):
|
|
identity = _get_wecom_bind_session(token)
|
|
if identity is None:
|
|
return None
|
|
_WECOM_BIND_SESSION_CACHE.pop(token, None)
|
|
return identity
|
|
|
|
def _parse_wecom_field_list(raw_value, default_fields: list[str]):
|
|
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):
|
|
return False
|
|
expected = sha1_hex([token, str(timestamp or ''), str(nonce or ''), encrypt])
|
|
return expected == msg_signature
|
|
|
|
def _extract_xml_field(xml_text: str, tag: str):
|
|
if not xml_text:
|
|
return None
|
|
m = re.search(f'<{tag}><!\\[CDATA\\[(.*?)\\]\\]></{tag}>', xml_text, re.DOTALL)
|
|
if m:
|
|
return m.group(1).strip()
|
|
m2 = re.search(f'<{tag}>(.*?)</{tag}>', xml_text, re.DOTALL)
|
|
if m2:
|
|
return m2.group(1).strip()
|
|
return None
|
|
|
|
def _persist_wecom_callback_audit(*, msg_signature, timestamp, nonce, encrypt_raw, decrypted_xml=None, msg_type=None, event=None, from_user=None, agent_id=None, msg_id=None, error_message=None):
|
|
try:
|
|
row = WecomCallbackAudit(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_raw, decrypted_xml=decrypted_xml, msg_type=msg_type, event=event, from_user=from_user, agent_id=agent_id, msg_id=msg_id, error_message=error_message)
|
|
db.session.add(row)
|
|
db.session.commit()
|
|
except Exception:
|
|
db.session.rollback()
|
|
|
|
def _get_wecom_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,
|
|
**user.client_auth_fields(),
|
|
'source': source,
|
|
'access_token': issue_local_access_token(user),
|
|
'token_type': 'Bearer',
|
|
}
|
|
if bind_status:
|
|
payload['bind_status'] = bind_status
|
|
return payload
|
|
|
|
def _clean_str(value):
|
|
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_leave_int_flag(value, field_label: str):
|
|
if value in (0, 1):
|
|
return int(value)
|
|
text = _clean_str(value)
|
|
if text in ('0', '1'):
|
|
return int(text)
|
|
raise OALeaveWorkflowError(f'{field_label} 取值无效,应为 0 或 1。')
|
|
|
|
def _normalize_mobile(mobile: str):
|
|
mobile = _clean_str(mobile)
|
|
if not mobile:
|
|
return None
|
|
digits = re.sub('\\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_wecom_extattr_value(wecom_user: dict, key: str):
|
|
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_wecom_match_config():
|
|
return _wecom_svc.get_match_config()
|
|
|
|
def _get_wecom_first_login_bind_mode():
|
|
return _wecom_svc.get_first_login_bind_mode()
|
|
|
|
def _get_wecom_first_login_input_fields():
|
|
return _wecom_svc.get_first_login_input_fields()
|
|
|
|
def _extract_wecom_identity(wecom_user: dict):
|
|
return _wecom_svc.extract_identity(wecom_user)
|
|
|
|
def _mobile_candidates(identity: dict):
|
|
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_WECOM_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):
|
|
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')
|
|
wecom_unionid = identity.get('wecom_unionid')
|
|
if wecom_userid:
|
|
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
|
|
if dup:
|
|
raise WeComLoginError(error=f'Current WeCom account has been bound to user: {dup.username}', error_code='WECOM_BIND_CONFLICT', status_code=409, reason='bind_conflict')
|
|
if wecom_unionid:
|
|
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
|
|
if dup_union:
|
|
raise WeComLoginError(error=f'Current WeCom unionid has been bound to user: {dup_union.username}', error_code='WECOM_BIND_CONFLICT', status_code=409, reason='bind_conflict')
|
|
|
|
def _sync_user_from_wecom_identity(user: User, identity: dict):
|
|
_assert_wecom_binding_not_occupied(user, identity)
|
|
if identity.get('wecom_userid'):
|
|
user.wecom_userid = identity['wecom_userid']
|
|
if identity.get('wecom_unionid') and (not user.wecom_unionid):
|
|
user.wecom_unionid = identity['wecom_unionid']
|
|
if identity.get('name') and (not user.real_name):
|
|
user.real_name = identity['name']
|
|
if identity.get('email') and (not user.email):
|
|
dup_email = db.session.query(User).filter(User.email == identity['email'], User.id != user.id).first()
|
|
if not dup_email:
|
|
user.email = identity['email']
|
|
if identity.get('mobile') and (not user.phone_number):
|
|
candidates = _mobile_candidates(identity)
|
|
dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates), User.id != user.id).first()
|
|
if not dup_mobile:
|
|
user.phone_number = identity['mobile']
|
|
if identity.get('employee_id') and (not user.employee_id):
|
|
dup_employee = db.session.query(User).filter(User.employee_id == identity['employee_id'], User.id != user.id).first()
|
|
if not dup_employee:
|
|
user.employee_id = identity['employee_id']
|
|
|
|
def _create_user_from_wecom_identity(identity: dict) -> User:
|
|
base_username = (identity.get('wecom_userid') or identity.get('email') or identity.get('mobile') or f'wecom_{uuid.uuid4().hex[:8]}').replace('@', '_')
|
|
candidate = base_username
|
|
suffix = 1
|
|
while db.session.query(User).filter_by(username=candidate).first():
|
|
candidate = f'{base_username}_{suffix}'
|
|
suffix += 1
|
|
safe_email = identity.get('email') or f'{candidate}@wecom.local'
|
|
if db.session.query(User).filter_by(email=safe_email).first():
|
|
safe_email = f'{candidate}_{uuid.uuid4().hex[:6]}@wecom.local'
|
|
employee_id = identity.get('employee_id')
|
|
if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first():
|
|
employee_id = None
|
|
phone_number = identity.get('mobile')
|
|
if phone_number:
|
|
candidates = _mobile_candidates(identity)
|
|
dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates)).first()
|
|
if dup_mobile:
|
|
phone_number = None
|
|
user = User(username=candidate, email=safe_email, role='user', status='active', real_name=identity.get('name'), employee_id=employee_id, phone_number=phone_number, wecom_userid=identity.get('wecom_userid'), wecom_unionid=identity.get('wecom_unionid'))
|
|
user.set_password(uuid.uuid4().hex)
|
|
db.session.add(user)
|
|
return user
|
|
|
|
def _issue_wecom_input_bind_prompt(identity: dict):
|
|
allowed_fields = _get_wecom_first_login_input_fields()
|
|
binding_token = _issue_wecom_bind_session(identity)
|
|
raise WeComLoginError(error='First WeCom login requires verification input to bind a local account.', error_code='WECOM_BIND_INPUT_REQUIRED', status_code=409, reason='input_bind_required', extra={'binding_token': binding_token, 'allowed_fields': allowed_fields, 'wecom_name': identity.get('name'), 'wecom_userid': identity.get('wecom_userid')})
|
|
|
|
def _sync_or_create_user_from_wecom(wecom_user: dict):
|
|
identity = _extract_wecom_identity(wecom_user)
|
|
rules, operator = _get_wecom_match_config()
|
|
rule_info = {'operator': operator, 'fields': rules}
|
|
bind_mode = _get_wecom_first_login_bind_mode()
|
|
user = None
|
|
if identity.get('wecom_userid'):
|
|
user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first()
|
|
if user:
|
|
_sync_user_from_wecom_identity(user, identity)
|
|
return (user, 'already_bound', rule_info)
|
|
if bind_mode == 'input_verify':
|
|
_issue_wecom_input_bind_prompt(identity)
|
|
matched_users, missing_fields = _find_users_by_match_rules(identity, rules, operator)
|
|
if missing_fields:
|
|
missing_field = missing_fields[0]
|
|
raise WeComLoginError(error=f'Required match attribute missing: {missing_field}', error_code='WECOM_MATCH_ATTR_MISSING', status_code=422, reason=f'missing_attr:{missing_field}', extra={'missing_field': missing_field, 'match_rules': rule_info})
|
|
if len(matched_users) == 1:
|
|
user = matched_users[0]
|
|
_sync_user_from_wecom_identity(user, identity)
|
|
return (user, 'matched_and_bound', rule_info)
|
|
if len(matched_users) > 1:
|
|
raise WeComLoginError(error='Multiple local users matched', error_code='WECOM_MATCH_AMBIGUOUS', status_code=409, reason='ambiguous_match', extra={'candidate_count': len(matched_users), 'match_rules': rule_info})
|
|
if not current_app.config.get('WECOM_AUTO_CREATE_USER', True):
|
|
raise WeComLoginError(error='No linked account found. Contact admin to bind WeCom account.', error_code='WECOM_BIND_REQUIRED', status_code=403, reason='bind_required', extra={'match_rules': rule_info})
|
|
user = _create_user_from_wecom_identity(identity)
|
|
return (user, 'auto_created', rule_info)
|