Merge branch 'dev' into hugo
This commit is contained in:
commit
29a7704d46
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)
|
||||
|
||||
Reference in new issue
Block a user