feat(auth): 支持企业微信重置密码
This commit is contained in:
1 parent
9bc4d1dd18
commit
6baeffba64
55 files changed
+2852
-546
No files matched your search
+128
-4
@@ -11,7 +11,7 @@ from app.decorators import require_admin
|
||||
from app.config import Config
|
||||
from app import db
|
||||
from app.env_persistence import persist_env_settings
|
||||
from sqlalchemy import func, desc, inspect
|
||||
from sqlalchemy import func, desc, inspect, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from datetime import datetime, timedelta
|
||||
import csv
|
||||
@@ -20,6 +20,7 @@ import re
|
||||
import requests
|
||||
import uuid
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.wecom_directory_sync import sync_wecom_userids_from_directory
|
||||
from app.services.dify import DifyService
|
||||
from app.auth_jwt import get_current_user as _get_auth_user
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
@@ -839,14 +840,63 @@ def get_table_count(table):
|
||||
@require_admin
|
||||
def list_wecom_bindings():
|
||||
"""
|
||||
List users with optional filter for WeCom bindings.
|
||||
分页列出用户企微绑定,支持 keyword 模糊搜索与 bound_only 筛选。
|
||||
|
||||
Query: bound_only, keyword, page, page_size
|
||||
Returns: { items, total, page, page_size, pages }
|
||||
"""
|
||||
bound_only = request.args.get('bound_only', 'false').lower() == 'true'
|
||||
keyword = (request.args.get('keyword') or '').strip()
|
||||
page = request.args.get('page', type=int) or 1
|
||||
page_size = request.args.get('page_size', type=int) or 20
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(100, page_size))
|
||||
|
||||
query = db.session.query(User)
|
||||
if bound_only:
|
||||
query = query.filter(User.wecom_userid.isnot(None))
|
||||
users = query.order_by(User.id.asc()).all()
|
||||
return jsonify([{'id': u.id, 'username': u.username, 'real_name': u.real_name, 'email': u.email, 'role': u.role, 'status': u.status, 'wecom_userid': u.wecom_userid, 'wecom_unionid': u.wecom_unionid, 'bound': bool(u.wecom_userid)} for u in users])
|
||||
if keyword:
|
||||
pattern = f'%{keyword}%'
|
||||
query = query.filter(or_(
|
||||
User.username.ilike(pattern),
|
||||
User.real_name.ilike(pattern),
|
||||
User.employee_id.ilike(pattern),
|
||||
User.wecom_userid.ilike(pattern),
|
||||
))
|
||||
|
||||
total = query.count()
|
||||
pages = max(1, (total + page_size - 1) // page_size) if total else 1
|
||||
if page > pages:
|
||||
page = pages
|
||||
|
||||
users = (
|
||||
query.order_by(User.id.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
items = [
|
||||
{
|
||||
'id': u.id,
|
||||
'username': u.username,
|
||||
'real_name': u.real_name,
|
||||
'employee_id': u.employee_id,
|
||||
'email': u.email,
|
||||
'role': u.role,
|
||||
'status': u.status,
|
||||
'wecom_userid': u.wecom_userid,
|
||||
'wecom_unionid': u.wecom_unionid,
|
||||
'bound': bool(u.wecom_userid),
|
||||
}
|
||||
for u in users
|
||||
]
|
||||
return jsonify({
|
||||
'items': items,
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'pages': pages,
|
||||
})
|
||||
|
||||
@admin_bp.route('/guides/upload', methods=['POST'])
|
||||
@require_admin
|
||||
@@ -1177,3 +1227,77 @@ def wecom_notify_metrics():
|
||||
by_event[event_type] = {'sent': 0, 'failed': 0}
|
||||
by_event[event_type][status] = int(cnt)
|
||||
return jsonify({'window_days': 30, 'total': int(total), 'sent': int(sent), 'failed': int(total - sent), 'send_success_rate': round(sent / total * 100, 2) if total else 0, 'opened_24h': int(opened_24h), 'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0, 'by_event': by_event})
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/binding-stats', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_binding_stats():
|
||||
"""
|
||||
返回活跃用户的企微 userid 绑定统计,供管理端概览卡片使用。
|
||||
"""
|
||||
total_active = db.session.query(func.count(User.id)).filter(User.status == 'active').scalar() or 0
|
||||
bound = (
|
||||
db.session.query(func.count(User.id))
|
||||
.filter(User.status == 'active', User.wecom_userid.isnot(None), User.wecom_userid != '')
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
total_active = int(total_active)
|
||||
bound = int(bound)
|
||||
return jsonify(
|
||||
{
|
||||
'total_active': total_active,
|
||||
'bound': bound,
|
||||
'unbound': max(total_active - bound, 0),
|
||||
'bound_rate': round(bound / total_active * 100, 2) if total_active else 0,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/sync-userids', methods=['POST'])
|
||||
@require_admin
|
||||
def sync_wecom_userids_admin():
|
||||
"""
|
||||
从企微通讯录按工号同步 users.wecom_userid。
|
||||
Request JSON: { "apply": false, "department_id": 1 }
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
apply = bool(data.get('apply'))
|
||||
department_id = data.get('department_id')
|
||||
if department_id is not None and department_id != '':
|
||||
try:
|
||||
department_id = int(department_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('department_id must be an integer')
|
||||
else:
|
||||
department_id = None
|
||||
try:
|
||||
summary = sync_wecom_userids_from_directory(apply=apply, department_id=department_id)
|
||||
current_app.logger.info(
|
||||
'[wecom_sync] admin apply=%s updated=%s would_update=%s conflicts=%s',
|
||||
apply,
|
||||
summary.get('updated'),
|
||||
summary.get('would_update'),
|
||||
len(summary.get('conflicts') or []),
|
||||
)
|
||||
return jsonify(summary)
|
||||
except RuntimeError as exc:
|
||||
message = str(exc)
|
||||
if 'not configured' in message.lower():
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message=message,
|
||||
http_status=503,
|
||||
details={'error_code': 'WECOM_NOT_CONFIGURED'},
|
||||
)
|
||||
if 'conflicts detected' in message.lower():
|
||||
raise ConflictError(message, details={'error_code': 'WECOM_SYNC_CONFLICTS'})
|
||||
if 'department/list failed' in message.lower() or 'user/list failed' in message.lower():
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message='WeCom directory API failed. Check app contact read permissions.',
|
||||
http_status=502,
|
||||
details={'error_code': 'WECOM_DIRECTORY_API_FAILED', 'technical': message[:300]},
|
||||
)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=message, http_status=500)
|
||||
|
||||
+264
-4
@@ -22,6 +22,8 @@ user_bp = Blueprint('user', __name__)
|
||||
_WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None}
|
||||
_WECOM_STATE_CACHE = {}
|
||||
_WECOM_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
|
||||
_CASDOOR_OIDC_CACHE = {'value': None, 'expires_at': None}
|
||||
@@ -108,8 +110,27 @@ def _run_db_with_retry(operation, *, label: str):
|
||||
current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc)
|
||||
return operation()
|
||||
|
||||
def _is_wecom_configured():
|
||||
return all([current_app.config.get('WECOM_ENABLED'), current_app.config.get('WECOM_CORP_ID'), current_app.config.get('WECOM_AGENT_ID'), current_app.config.get('WECOM_SECRET')])
|
||||
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
|
||||
|
||||
|
||||
def _is_wecom_configured() -> bool:
|
||||
"""企微 Corp/Agent/Secret 与总开关均已配置时返回 True。"""
|
||||
return len(_get_wecom_config_missing_fields()) == 0
|
||||
|
||||
def _issue_casdoor_state(redirect_uri: str):
|
||||
exp_ts = int((datetime.utcnow() + timedelta(minutes=10)).timestamp())
|
||||
@@ -1560,6 +1581,231 @@ def change_password():
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
def _get_password_reset_public_base_url() -> str:
|
||||
"""
|
||||
解析密码重置外链基地址,优先公网入口配置。
|
||||
核心逻辑:依次读取 WECOM_PUBLIC_BASE_URL / PUBLIC_BASE_URL / WECOM_NOTIFY_BASE_URL。
|
||||
Returns:
|
||||
去掉尾斜杠的基地址;均未配置时返回空字符串。
|
||||
"""
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
base = _clean_str(current_app.config.get(key))
|
||||
if base:
|
||||
return base.rstrip('/')
|
||||
return ''
|
||||
|
||||
|
||||
def _build_password_reset_url(token: str) -> str:
|
||||
"""
|
||||
构造带 token 的密码重置页 URL。
|
||||
@param token: reset_token 明文
|
||||
Returns:
|
||||
完整重置链接
|
||||
Raises:
|
||||
RuntimeError: 公网基地址未配置
|
||||
"""
|
||||
base = _get_password_reset_public_base_url()
|
||||
if not base:
|
||||
raise RuntimeError('Password reset public base URL is not configured')
|
||||
return f'{base}/reset-password?token={token}'
|
||||
|
||||
|
||||
def _password_reset_rate_limit_state(key: str, *, window_seconds: int = 300) -> tuple[bool, int]:
|
||||
"""
|
||||
判断找回密码是否触发限流,并在允许时记录本次请求时间。
|
||||
@param key: 限流键,通常为 employee_id + IP
|
||||
@param window_seconds: 窗口秒数,默认 5 分钟
|
||||
Returns:
|
||||
(allowed, retry_after_seconds):allowed 为 False 时 retry_after_seconds 为剩余等待秒数
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
last = _PASSWORD_RESET_RATE_CACHE.get(key)
|
||||
if last:
|
||||
elapsed = (now - last).total_seconds()
|
||||
if elapsed < window_seconds:
|
||||
return False, max(1, int(window_seconds - elapsed))
|
||||
_PASSWORD_RESET_RATE_CACHE[key] = now
|
||||
return True, 0
|
||||
|
||||
|
||||
def _check_password_reset_rate_limit(key: str, *, window_seconds: int = 300) -> bool:
|
||||
"""
|
||||
简易内存限流,防止同工号/IP 频繁触发找回密码。
|
||||
@param key: 限流键,通常为 employee_id + IP
|
||||
@param window_seconds: 窗口秒数,默认 5 分钟
|
||||
Returns:
|
||||
True 表示允许继续;False 表示应拒绝
|
||||
"""
|
||||
allowed, _ = _password_reset_rate_limit_state(key, window_seconds=window_seconds)
|
||||
return allowed
|
||||
|
||||
|
||||
def _sync_casdoor_password_for_reset(user: User, new_password: str):
|
||||
"""
|
||||
Token 重置场景下将新密码同步至 Casdoor(无旧密码校验)。
|
||||
核心逻辑:Casdoor 已配置时调用 set-password,oldPassword 传空串(与 change-password fallback 一致)。
|
||||
@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)
|
||||
|
||||
|
||||
def _password_reset_rate_key(employee_id: str) -> str:
|
||||
"""
|
||||
生成找回密码限流键。
|
||||
@param employee_id: 工号
|
||||
Returns:
|
||||
employee_id 与客户端 IP 组合键
|
||||
"""
|
||||
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr) or 'unknown'
|
||||
return f'{employee_id}:{client_ip}'
|
||||
|
||||
|
||||
@user_bp.route('/reset-password-by-wecom', methods=['POST'])
|
||||
def reset_password_by_wecom():
|
||||
"""
|
||||
通过工号 + 用户名发起找回密码,并向已绑定 wecom_userid 发送 textcard 重置链接。
|
||||
Request JSON: { "employee_id": "...", "username": "..." }
|
||||
"""
|
||||
if not _is_wecom_configured():
|
||||
raise AppError(
|
||||
code='WECOM.RESET_NOT_CONFIGURED',
|
||||
message='WeCom password reset is not configured',
|
||||
http_status=503,
|
||||
details={
|
||||
'error_code': 'WECOM_RESET_NOT_CONFIGURED',
|
||||
'missing': _get_wecom_config_missing_fields(),
|
||||
},
|
||||
)
|
||||
if not bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)):
|
||||
raise AppError(
|
||||
code='WECOM.NOTIFY_DISABLED',
|
||||
message='WeCom notification is disabled',
|
||||
http_status=503,
|
||||
details={'error_code': 'WECOM_NOTIFY_DISABLED'},
|
||||
)
|
||||
if not _get_password_reset_public_base_url():
|
||||
raise AppError(
|
||||
code='WECOM.RESET_URL_NOT_CONFIGURED',
|
||||
message='Password reset public base URL is not configured',
|
||||
http_status=503,
|
||||
details={'error_code': 'PASSWORD_RESET_URL_NOT_CONFIGURED'},
|
||||
)
|
||||
|
||||
data = request.get_json() or {}
|
||||
employee_id = _clean_str(data.get('employee_id'))
|
||||
username = _clean_str(data.get('username'))
|
||||
if not employee_id:
|
||||
raise ValidationError('Employee ID is required')
|
||||
if not username:
|
||||
raise ValidationError('Username is required')
|
||||
|
||||
rate_key = _password_reset_rate_key(employee_id)
|
||||
allowed, retry_after_seconds = _password_reset_rate_limit_state(rate_key)
|
||||
if not allowed:
|
||||
retry_minutes = max(1, (retry_after_seconds + 59) // 60)
|
||||
current_app.logger.info(
|
||||
'[password_reset] rejected reason=rate_limited employee_id=%s retry_after_seconds=%s',
|
||||
employee_id,
|
||||
retry_after_seconds,
|
||||
)
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_RESET_RATE_LIMITED',
|
||||
message='Password reset requests are too frequent',
|
||||
http_status=429,
|
||||
details={
|
||||
'error_code': 'PASSWORD_RESET_RATE_LIMITED',
|
||||
'retry_after_seconds': retry_after_seconds,
|
||||
'retry_after_minutes': retry_minutes,
|
||||
},
|
||||
retryable=True,
|
||||
)
|
||||
|
||||
user = db.session.query(User).filter(User.employee_id == employee_id).first()
|
||||
if not user:
|
||||
current_app.logger.info(
|
||||
'[password_reset] noop reason=user_not_found employee_id=%s',
|
||||
employee_id,
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
if user.username != username:
|
||||
current_app.logger.info(
|
||||
'[password_reset] noop reason=username_mismatch employee_id=%s user_id=%s',
|
||||
employee_id,
|
||||
user.id,
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
if user.status != 'active':
|
||||
current_app.logger.info(
|
||||
'[password_reset] noop reason=account_inactive employee_id=%s user_id=%s',
|
||||
employee_id,
|
||||
user.id,
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
if not user.wecom_userid:
|
||||
current_app.logger.info(
|
||||
'[password_reset] noop reason=wecom_unbound employee_id=%s user_id=%s',
|
||||
employee_id,
|
||||
user.id,
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
|
||||
token = str(uuid.uuid4())
|
||||
user.reset_token = token
|
||||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||||
db.session.flush()
|
||||
|
||||
title = '和信AI智能工作台 密码重置'
|
||||
content = (
|
||||
'您发起了和信AI智能工作台密码重置请求。\n'
|
||||
'请在 1 小时内点击下方按钮设置新密码。\n'
|
||||
'如非本人操作,请忽略本消息。'
|
||||
)
|
||||
try:
|
||||
reset_jump_url = _build_password_reset_url(token)
|
||||
result = send_wecom_event_message(
|
||||
event_type='password_reset',
|
||||
user=user,
|
||||
title=title,
|
||||
content=content,
|
||||
jump_url=reset_jump_url,
|
||||
)
|
||||
if not result.get('ok'):
|
||||
db.session.rollback()
|
||||
current_app.logger.warning(
|
||||
'[password_reset] wecom send failed user_id=%s employee_id=%s reason=%s trace_id=%s raw=%s',
|
||||
user.id,
|
||||
employee_id,
|
||||
result.get('reason'),
|
||||
result.get('trace_id'),
|
||||
result.get('raw'),
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
|
||||
db.session.commit()
|
||||
current_app.logger.info(
|
||||
'[password_reset] reset link sent user_id=%s employee_id=%s trace_id=%s',
|
||||
user.id,
|
||||
employee_id,
|
||||
result.get('trace_id'),
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('[password_reset] unexpected failure user_id=%s: %s', user.id, exc)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Failed to request password reset', http_status=500)
|
||||
|
||||
|
||||
@user_bp.route('/reset-password-by-email', methods=['POST'])
|
||||
def reset_password_request():
|
||||
"""
|
||||
@@ -1590,19 +1836,33 @@ def reset_password_confirm():
|
||||
Reset password with token
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
token = data.get('token')
|
||||
token = _clean_str(data.get('token'))
|
||||
new_password = data.get('new_password')
|
||||
if not token or not new_password:
|
||||
raise ValidationError('Token and new password are required')
|
||||
user = db.session.query(User).filter_by(reset_token=token).first()
|
||||
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
|
||||
raise ValidationError('Invalid or expired token')
|
||||
current_app.logger.info(
|
||||
'[password_reset] confirm rejected reason=token_invalid token_prefix=%s found_user=%s',
|
||||
token[:8] if token else '',
|
||||
bool(user),
|
||||
)
|
||||
raise AppError(
|
||||
code='AUTH.RESET_TOKEN_INVALID',
|
||||
message='Invalid or expired token',
|
||||
http_status=400,
|
||||
details={'error_code': 'RESET_TOKEN_INVALID'},
|
||||
)
|
||||
try:
|
||||
_sync_casdoor_password_for_reset(user, new_password)
|
||||
user.set_password(new_password)
|
||||
user.reset_token = None
|
||||
user.reset_token_expiry = None
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Password has been reset successfully'})
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
@@ -188,7 +188,7 @@ class Config:
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
"""
|
||||
backend/app/services/wecom_directory_sync.py
|
||||
|
||||
用途:从企业微信通讯录拉取成员,按工号回填本地 users.wecom_userid。
|
||||
依赖:Flask current_app、SQLAlchemy db、wecom_notify._get_access_token、User 模型。
|
||||
逻辑:供 admin API 与 scripts/sync_wecom_userid_by_employee_id.py 共用;支持 dry-run 与 apply。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.wecom_notify import _get_access_token
|
||||
|
||||
_PREVIEW_LIMIT = 20
|
||||
|
||||
|
||||
def _clean_str(value) -> str | None:
|
||||
"""Trim string-like values; empty strings become None."""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _extract_wecom_extattr_value(wecom_user: dict, key: str) -> str | None:
|
||||
"""
|
||||
从企微成员 extattr.attrs 中读取指定扩展字段。
|
||||
@param wecom_user: user/list 返回的成员 dict
|
||||
@param key: 扩展属性名
|
||||
Returns:
|
||||
字段文本或 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 extract_employee_id_from_wecom_user(wecom_user: dict, employee_id_source: str) -> str | None:
|
||||
"""
|
||||
按 WECOM_EMPLOYEE_ID_SOURCE 从企微成员解析工号。
|
||||
核心逻辑:userid / extattr:xxx / 其它字段名,与 user.py _extract_wecom_identity 对齐。
|
||||
"""
|
||||
userid = _clean_str(wecom_user.get('userid'))
|
||||
source = _clean_str(employee_id_source) or 'userid'
|
||||
if source == 'userid':
|
||||
return userid
|
||||
if source.startswith('extattr:'):
|
||||
return _extract_wecom_extattr_value(wecom_user, source.split(':', 1)[1])
|
||||
return _clean_str(wecom_user.get(source))
|
||||
|
||||
|
||||
def fetch_wecom_departments(access_token: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取企业微信部门列表。
|
||||
Raises:
|
||||
RuntimeError: API 失败
|
||||
"""
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/department/list',
|
||||
params={'access_token': access_token},
|
||||
timeout=15,
|
||||
)
|
||||
data = resp.json() or {}
|
||||
if data.get('errcode') != 0:
|
||||
raise RuntimeError(f'department/list failed: {data}')
|
||||
departments = data.get('department') or []
|
||||
if not isinstance(departments, list):
|
||||
return []
|
||||
return [item for item in departments if isinstance(item, dict)]
|
||||
|
||||
|
||||
def fetch_wecom_users_in_department(access_token: str, department_id: int) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取指定部门(含子部门)成员简要列表。
|
||||
@param department_id: 企微部门 ID
|
||||
Returns:
|
||||
user/list 返回的 userlist
|
||||
"""
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/user/list',
|
||||
params={
|
||||
'access_token': access_token,
|
||||
'department_id': department_id,
|
||||
'fetch_child': 1,
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
data = resp.json() or {}
|
||||
if data.get('errcode') != 0:
|
||||
raise RuntimeError(f'user/list failed department_id={department_id}: {data}')
|
||||
userlist = data.get('userlist') or []
|
||||
if not isinstance(userlist, list):
|
||||
return []
|
||||
return [item for item in userlist if isinstance(item, dict)]
|
||||
|
||||
|
||||
def collect_wecom_users(access_token: str, department_ids: list[int]) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
汇总多个部门成员,按 wecom_userid 去重。
|
||||
Returns:
|
||||
key=userid, value=成员 dict
|
||||
"""
|
||||
merged: dict[str, dict[str, Any]] = {}
|
||||
for dept_id in department_ids:
|
||||
for user in fetch_wecom_users_in_department(access_token, dept_id):
|
||||
userid = _clean_str(user.get('userid'))
|
||||
if userid:
|
||||
merged[userid] = user
|
||||
return merged
|
||||
|
||||
|
||||
def sync_wecom_userids_from_directory(*, apply: bool, department_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
执行工号 → wecom_userid 同步。
|
||||
核心逻辑:拉企微成员 → 解析 employee_id → 匹配本地 User → dry-run 或写 wecom_userid/wecom_unionid。
|
||||
@param apply: True 时提交数据库;存在 conflicts 时不写入
|
||||
@param department_id: 指定根部门 ID;None 时使用全部部门
|
||||
Returns:
|
||||
统计摘要 dict(含 conflicts、pending_updates 预览)
|
||||
"""
|
||||
if not current_app.config.get('WECOM_CORP_ID') or not current_app.config.get('WECOM_SECRET'):
|
||||
raise RuntimeError('WECOM_CORP_ID / WECOM_SECRET is not configured')
|
||||
|
||||
employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
|
||||
token = _get_access_token()
|
||||
|
||||
if department_id is not None:
|
||||
department_ids = [department_id]
|
||||
else:
|
||||
departments = fetch_wecom_departments(token)
|
||||
department_ids = [int(item.get('id')) for item in departments if item.get('id') is not None]
|
||||
if not department_ids:
|
||||
department_ids = [1]
|
||||
|
||||
wecom_users = collect_wecom_users(token, department_ids)
|
||||
summary: dict[str, Any] = {
|
||||
'apply': apply,
|
||||
'employee_id_source': employee_id_source,
|
||||
'department_ids': department_ids,
|
||||
'wecom_users': len(wecom_users),
|
||||
'wecom_without_employee_id': 0,
|
||||
'local_matched': 0,
|
||||
'would_update': 0,
|
||||
'updated': 0,
|
||||
'already_bound': 0,
|
||||
'local_missing': 0,
|
||||
'conflicts': [],
|
||||
'missing_samples': [],
|
||||
'pending_updates': [],
|
||||
}
|
||||
|
||||
for wecom_user in wecom_users.values():
|
||||
wecom_userid = _clean_str(wecom_user.get('userid'))
|
||||
wecom_unionid = _clean_str(wecom_user.get('unionid'))
|
||||
employee_id = extract_employee_id_from_wecom_user(wecom_user, employee_id_source)
|
||||
if not employee_id:
|
||||
summary['wecom_without_employee_id'] += 1
|
||||
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
|
||||
summary['missing_samples'].append(
|
||||
{'wecom_userid': wecom_userid, 'name': _clean_str(wecom_user.get('name'))}
|
||||
)
|
||||
continue
|
||||
|
||||
local_user = db.session.query(User).filter(User.employee_id == employee_id).first()
|
||||
if not local_user:
|
||||
summary['local_missing'] += 1
|
||||
continue
|
||||
|
||||
summary['local_matched'] += 1
|
||||
|
||||
if local_user.wecom_userid == wecom_userid:
|
||||
summary['already_bound'] += 1
|
||||
continue
|
||||
|
||||
conflict = None
|
||||
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
|
||||
conflict = {
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'old_wecom_userid': local_user.wecom_userid,
|
||||
'new_wecom_userid': wecom_userid,
|
||||
}
|
||||
else:
|
||||
occupied = (
|
||||
db.session.query(User)
|
||||
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
|
||||
.first()
|
||||
)
|
||||
if occupied:
|
||||
conflict = {
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'new_wecom_userid': wecom_userid,
|
||||
'occupied_by_user_id': occupied.id,
|
||||
'occupied_by_username': occupied.username,
|
||||
}
|
||||
|
||||
if conflict:
|
||||
summary['conflicts'].append(conflict)
|
||||
continue
|
||||
|
||||
summary['would_update'] += 1
|
||||
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
|
||||
summary['pending_updates'].append(
|
||||
{
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'wecom_userid': wecom_userid,
|
||||
'name': _clean_str(wecom_user.get('name')),
|
||||
}
|
||||
)
|
||||
if apply:
|
||||
local_user.wecom_userid = wecom_userid
|
||||
if wecom_unionid:
|
||||
local_user.wecom_unionid = wecom_unionid
|
||||
summary['updated'] += 1
|
||||
|
||||
if summary['conflicts'] and apply:
|
||||
db.session.rollback()
|
||||
raise RuntimeError('Conflicts detected; resolve manually before apply')
|
||||
|
||||
if apply and summary['updated'] > 0:
|
||||
db.session.commit()
|
||||
elif apply:
|
||||
db.session.rollback()
|
||||
|
||||
return summary
|
||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from io import BytesIO
|
||||
from urllib.parse import urlencode
|
||||
from urllib.parse import urlencode, urlparse, parse_qsl, urlunparse
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
@@ -27,8 +27,22 @@ def _get_enabled_events() -> set[str]:
|
||||
return set()
|
||||
|
||||
|
||||
def _get_notify_base_url() -> str:
|
||||
"""
|
||||
解析企微 textcard 跳转基地址。
|
||||
核心逻辑:优先 WECOM_NOTIFY_BASE_URL,其次 WECOM_PUBLIC_BASE_URL。
|
||||
Returns:
|
||||
去掉尾斜杠的基地址;均未配置时返回空字符串。
|
||||
"""
|
||||
for key in ('WECOM_NOTIFY_BASE_URL', 'WECOM_PUBLIC_BASE_URL'):
|
||||
raw = current_app.config.get(key)
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
return raw.strip().rstrip('/')
|
||||
return ''
|
||||
|
||||
|
||||
def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str:
|
||||
base = current_app.config.get('WECOM_NOTIFY_BASE_URL') or ''
|
||||
base = _get_notify_base_url()
|
||||
if not base:
|
||||
return ''
|
||||
base = base.rstrip('/')
|
||||
@@ -133,7 +147,7 @@ def send_wecom_textcard_message(
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'description': (description or '')[:1024],
|
||||
'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'),
|
||||
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
||||
'btntxt': '查看详情',
|
||||
},
|
||||
'safe': 0,
|
||||
@@ -147,6 +161,21 @@ def send_wecom_textcard_message(
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _append_query_param(url: str, key: str, value: str) -> str:
|
||||
"""
|
||||
向 URL 追加单个 query 参数,保留已有参数。
|
||||
@param url: 原始 URL
|
||||
@param key: 参数名
|
||||
@param value: 参数值
|
||||
Returns:
|
||||
追加参数后的 URL
|
||||
"""
|
||||
parsed = urlparse(url)
|
||||
pairs = parse_qsl(parsed.query, keep_blank_values=True)
|
||||
pairs.append((key, value))
|
||||
return urlunparse(parsed._replace(query=urlencode(pairs)))
|
||||
|
||||
|
||||
def send_wecom_event_message(
|
||||
*,
|
||||
event_type: str,
|
||||
@@ -155,7 +184,11 @@ def send_wecom_event_message(
|
||||
content: str,
|
||||
jump_path: str = '/workspace',
|
||||
jump_params: dict | None = None,
|
||||
jump_url: str | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
发送企微事件 textcard;可选 jump_url 覆盖默认跳转(如密码重置外链)。
|
||||
"""
|
||||
trace_id = uuid.uuid4().hex
|
||||
audit = _create_audit(event_type, user, title, content, trace_id)
|
||||
|
||||
@@ -175,9 +208,12 @@ def send_wecom_event_message(
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
|
||||
|
||||
try:
|
||||
jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = jump_url
|
||||
data = send_wecom_textcard_message(user.wecom_userid, title, content, jump_url)
|
||||
if jump_url:
|
||||
final_jump_url = _append_query_param(jump_url, 'wecom_trace', trace_id)
|
||||
else:
|
||||
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = final_jump_url
|
||||
data = send_wecom_textcard_message(user.wecom_userid, title, content, final_jump_url)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
backend/scripts/sync_wecom_userid_by_employee_id.py
|
||||
|
||||
用途:从企业微信通讯录拉取成员,按工号(employee_id)回填本地 users.wecom_userid。
|
||||
依赖:app.create_app、wecom_directory_sync.sync_wecom_userids_from_directory。
|
||||
逻辑:运维 CLI;默认 dry-run,--apply 才写库。
|
||||
|
||||
Usage:
|
||||
cd backend
|
||||
python scripts/sync_wecom_userid_by_employee_id.py
|
||||
python scripts/sync_wecom_userid_by_employee_id.py --apply
|
||||
python scripts/sync_wecom_userid_by_employee_id.py --apply --department-id 1
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND_ROOT))
|
||||
|
||||
from app import create_app # noqa: E402
|
||||
from app.services.wecom_directory_sync import sync_wecom_userids_from_directory # noqa: E402
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""CLI 入口:解析参数并打印同步摘要 JSON。"""
|
||||
parser = argparse.ArgumentParser(description='Sync User.wecom_userid from WeCom directory by employee_id.')
|
||||
parser.add_argument('--apply', action='store_true', help='Persist changes (default: dry-run).')
|
||||
parser.add_argument('--department-id', type=int, default=None, help='Root department id (default: all departments).')
|
||||
args = parser.parse_args()
|
||||
|
||||
env = os.getenv('FLASK_ENV', 'production')
|
||||
app = create_app(env)
|
||||
with app.app_context():
|
||||
summary = sync_wecom_userids_from_directory(apply=args.apply, department_id=args.department_id)
|
||||
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if summary.get('conflicts'):
|
||||
print('\nConflicts detected; resolve manually before --apply.', file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user