feat(auth): 支持企业微信重置密码

This commit is contained in:
sophie committed 2026-06-15 17:13:48 +08:00
1 parent 9bc4d1dd18
commit 6baeffba64
55 files changed
+2852 -546

No files matched your search

+264 -4
View File
@@ -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)