refactor(backend): 重构后端代码 wave 3
This commit is contained in:
1 parent
affe139bf9
commit
8415653365
97 files changed
+4673
-6164
No files matched your search
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
api/user/__init__.py
|
||||
|
||||
用途:导出用户域与认证域 Blueprint,并维护历史测试替身兼容入口。
|
||||
依赖:handlers、auth 及其共享认证操作。
|
||||
逻辑:register_blueprints 将两个 Blueprint 挂载到 `/api/user`;兼容代理确保迁包前的替身点仍然生效。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import ModuleType
|
||||
|
||||
from . import handlers
|
||||
from . import auth
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
user_bp = handlers.user_bp
|
||||
|
||||
# The documented Wave 3 compatibility export supports existing tests and callers.
|
||||
_get_current_user = handlers._get_current_user
|
||||
|
||||
|
||||
class _UserApiCompatModule(ModuleType):
|
||||
"""Forward historic private test replacement points to the canonical handlers."""
|
||||
|
||||
def __setattr__(self, name: str, value: object) -> None:
|
||||
super().__setattr__(name, value)
|
||||
if hasattr(handlers, name):
|
||||
setattr(handlers, name, value)
|
||||
if hasattr(auth, name):
|
||||
setattr(auth, name, value)
|
||||
|
||||
|
||||
sys.modules[__name__].__class__ = _UserApiCompatModule
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
"""Expose historic test symbols from their formal auth or user module."""
|
||||
if hasattr(auth, name):
|
||||
return getattr(auth, name)
|
||||
return getattr(handlers, name)
|
||||
|
||||
|
||||
__all__ = ['auth_bp', 'user_bp']
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
api/user/auth.py
|
||||
|
||||
用途:用户认证 Blueprint 的兼容门面与路由装配入口。
|
||||
依赖:auth_local、auth_casdoor、auth_wecom、auth_password_reset、auth_support。
|
||||
逻辑:api/user/__init__.py 从此模块导出 auth_bp;各职责路由在独立模块注册,历史测试仍可替换本模块私有符号。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import ModuleType
|
||||
|
||||
from flask import Blueprint
|
||||
|
||||
from . import auth_support as _support
|
||||
|
||||
auth_bp = Blueprint('user_auth', __name__)
|
||||
|
||||
|
||||
class _AuthCompatModule(ModuleType):
|
||||
"""将历史 monkeypatch 同步到共享认证操作,保持测试替身入口稳定。"""
|
||||
|
||||
def __setattr__(self, name: str, value: object) -> None:
|
||||
super().__setattr__(name, value)
|
||||
if hasattr(_support, name):
|
||||
setattr(_support, name, value)
|
||||
|
||||
|
||||
sys.modules[__name__].__class__ = _AuthCompatModule
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
"""兼容导出共享认证操作与历史测试替身点。"""
|
||||
return getattr(_support, name)
|
||||
|
||||
|
||||
# Importing modules registers their narrow route groups on the shared Blueprint.
|
||||
from . import auth_casdoor, auth_local, auth_password_reset, auth_wecom # noqa: E402, F401
|
||||
|
||||
__all__ = ['auth_bp']
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
api/user/auth_casdoor.py
|
||||
|
||||
用途:Casdoor 密码、授权码与刷新令牌认证路由。
|
||||
依赖:auth.auth_bp、auth_support 兼容操作、services/auth/hxops。
|
||||
逻辑:HTTP 参数与公开 URL 在本模块分组;登录编排仍复用已有 Casdoor 服务适配器。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, UnauthorizedError, ValidationError
|
||||
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
@auth_bp.post('/casdoor/password-login', endpoint='casdoor_password_login')
|
||||
def password_login():
|
||||
"""使用 Casdoor password grant 登录,并返回 HXOPS 本地 API 会话。"""
|
||||
if (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() != 'casdoor':
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_PASSWORD_LOGIN_DISABLED',
|
||||
message='Casdoor password login is disabled by AUTH_LOGIN_MODE',
|
||||
http_status=403,
|
||||
)
|
||||
data = request.get_json() or {}
|
||||
username = _compat._clean_str(data.get('username'))
|
||||
password = data.get('password') or ''
|
||||
if not username or not password:
|
||||
raise ValidationError('Username and password are required')
|
||||
try:
|
||||
result = _compat._hxops_login_service().password(username, password)
|
||||
db.session.commit()
|
||||
return jsonify(result.login_payload())
|
||||
except _compat.WeComLoginError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
_compat._raise_casdoor_auth_error(exc, context='password')
|
||||
|
||||
|
||||
@auth_bp.get('/casdoor/authorize-url', endpoint='casdoor_authorize_url')
|
||||
def authorize_url():
|
||||
"""生成包含状态参数的 Casdoor 授权码登录地址。"""
|
||||
try:
|
||||
options = CasdoorAuthorizeOptions(
|
||||
redirect_uri=request.args.get('redirect_uri'),
|
||||
provider_hint=request.args.get('provider_hint'),
|
||||
default_provider=request.args.get('default_provider'),
|
||||
silent_signin=request.args.get('silent_signin'),
|
||||
)
|
||||
return jsonify(_compat._build_casdoor_authorize_payload(options))
|
||||
except Exception as exc:
|
||||
raise AppError(
|
||||
code='SYSTEM.INTERNAL_ERROR',
|
||||
message=f'Failed to build Casdoor authorize url: {exc}',
|
||||
http_status=500,
|
||||
) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/casdoor/login', endpoint='casdoor_login')
|
||||
def authorization_code_login():
|
||||
"""交换授权码、映射本地用户并签发 HXOPS API 会话。"""
|
||||
data = request.get_json() or {}
|
||||
code = _compat._clean_str(data.get('code'))
|
||||
state = _compat._clean_str(data.get('state'))
|
||||
if not code:
|
||||
raise ValidationError('code is required')
|
||||
current_app.logger.info('[casdoor_login] start code_len=%s state=%s', len(code), state[:24] if state else '')
|
||||
redirect_uri = _compat._consume_casdoor_state(state)
|
||||
if not redirect_uri:
|
||||
current_app.logger.warning('[casdoor_login] invalid_state state=%s', state[:24] if state else '')
|
||||
raise ValidationError('Invalid or expired Casdoor state')
|
||||
try:
|
||||
result = _compat._hxops_login_service().authorization_code(code, redirect_uri)
|
||||
current_app.logger.info('[casdoor_login] user_resolved username=%s id=%s', result.user.username, result.user.id)
|
||||
db.session.commit()
|
||||
return jsonify(result.login_payload())
|
||||
except _compat.WeComLoginError:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('[casdoor_login] business_reject')
|
||||
raise
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('[casdoor_login] failed state=%s redirect_uri=%s', state[:24] if state else '', redirect_uri)
|
||||
_compat._raise_casdoor_auth_error(exc, context='code')
|
||||
|
||||
|
||||
@auth_bp.post('/casdoor/refresh', endpoint='casdoor_refresh')
|
||||
def refresh():
|
||||
"""以 Casdoor refresh token 换取新的 HXOPS API 会话。"""
|
||||
data = request.get_json() or {}
|
||||
refresh_token = _compat._clean_str(data.get('refresh_token'))
|
||||
if not refresh_token:
|
||||
raise ValidationError('refresh_token is required')
|
||||
current_app.logger.info('[casdoor_refresh] start refresh=%s', _compat._token_brief(refresh_token))
|
||||
try:
|
||||
result = _compat._hxops_login_service().refresh(refresh_token)
|
||||
current_app.logger.info(
|
||||
'[casdoor_refresh] token_refresh_ok next_refresh=%s user_id=%s',
|
||||
_compat._token_brief(result.refresh_token), result.user.id,
|
||||
)
|
||||
return jsonify(result.refresh_payload())
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
message = str(exc)
|
||||
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||||
message='Casdoor refresh token is not supported by current application config',
|
||||
http_status=400,
|
||||
) from exc
|
||||
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _compat._token_brief(refresh_token))
|
||||
raise UnauthorizedError(f'Casdoor refresh failed: {exc}') from exc
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
api/user/auth_local.py
|
||||
|
||||
用途:注册、传统密码登录与改密 HTTP 路由。
|
||||
依赖:auth.auth_bp、auth_support 的共享认证操作。
|
||||
逻辑:本模块仅装配本地密码职责;业务处理暂由兼容实现承接,后续迁移不改变公开 URL。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
@auth_bp.post('/register', endpoint='register')
|
||||
def register():
|
||||
"""校验必填和唯一字段后创建本地用户,保持原有注册响应。"""
|
||||
data = request.get_json() or {}
|
||||
required_fields = ['username', 'password', 'email', 'real_name', 'employee_id', 'phone_number']
|
||||
for field in required_fields:
|
||||
if not data.get(field):
|
||||
raise ValidationError(f'{field} is required')
|
||||
if db.session.query(_compat.User).filter_by(username=data['username']).first():
|
||||
raise ValidationError('Username already exists')
|
||||
if db.session.query(_compat.User).filter_by(email=data['email']).first():
|
||||
raise ValidationError('Email already exists')
|
||||
if db.session.query(_compat.User).filter_by(employee_id=data['employee_id']).first():
|
||||
raise ValidationError('Employee ID already exists')
|
||||
try:
|
||||
user = _compat.User(
|
||||
username=data['username'], email=data['email'], real_name=data['real_name'],
|
||||
employee_id=data['employee_id'], phone_number=data['phone_number'],
|
||||
department=data.get('department'), role='user', status='active',
|
||||
)
|
||||
user.set_password(data['password'])
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Registration successful', 'id': user.id}), 201
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/login', endpoint='login')
|
||||
def login():
|
||||
"""处理兼容的本地用户名密码登录;委托原有审计与重试逻辑。"""
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', True)):
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_LOGIN_DISABLED',
|
||||
message='Password login is disabled. Please use Casdoor login.',
|
||||
http_status=403,
|
||||
)
|
||||
|
||||
def attempt_login():
|
||||
"""校验本地密码并写入登录审计;用于可恢复数据库失败的一次重试。"""
|
||||
data = request.get_json() or {}
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
if not username or not password:
|
||||
_compat._write_login_audit('password', 'failed', username=username, reason='missing_credentials')
|
||||
raise ValidationError('Username and password are required')
|
||||
user = db.session.query(_compat.User).filter_by(username=username).first()
|
||||
if not user:
|
||||
_compat._write_login_audit('password', 'failed', username=username, reason='user_not_found')
|
||||
db.session.commit()
|
||||
raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404)
|
||||
if not user.check_password(password):
|
||||
_compat._write_login_audit('password', 'failed', user=user, reason='incorrect_password')
|
||||
db.session.commit()
|
||||
raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401)
|
||||
if user.status != 'active':
|
||||
_compat._write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
||||
db.session.commit()
|
||||
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
|
||||
_compat._write_login_audit('password', 'success', user=user)
|
||||
db.session.commit()
|
||||
return jsonify(_compat._build_login_payload(user, 'password'))
|
||||
|
||||
try:
|
||||
return attempt_login()
|
||||
except (OperationalError, DatabaseError):
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
return attempt_login()
|
||||
except (OperationalError, DatabaseError) as retry_exc:
|
||||
current_app.logger.warning('Password login retry failed: %s', retry_exc)
|
||||
raise ServiceUnavailableError('Database connection failed') from retry_exc
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('Login error: %s', exc)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Internal server error', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/change-password', endpoint='change_password')
|
||||
def change_password():
|
||||
"""校验当前身份并同步更新本地与 Casdoor 密码。"""
|
||||
user = _compat._get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
current_password = data.get('current_password')
|
||||
new_password = data.get('new_password')
|
||||
if not current_password or not new_password:
|
||||
raise ValidationError('Current and new password are required')
|
||||
try:
|
||||
_compat._verify_current_password_for_change(user, current_password)
|
||||
_compat._sync_casdoor_password(user.username, current_password, new_password)
|
||||
user.set_password(new_password)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Password changed successfully'})
|
||||
except AppError:
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
db.session.rollback()
|
||||
if _compat._is_casdoor_password_error(str(exc)):
|
||||
_compat._raise_incorrect_current_password()
|
||||
_compat._raise_casdoor_set_password_error(exc)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
|
||||
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
api/user/auth_password_reset.py
|
||||
|
||||
用途:密码找回与确认重置 HTTP 路由。
|
||||
依赖:auth.auth_bp、auth_support 的企微配置与 Casdoor 密码同步操作。
|
||||
逻辑:密码重置从常规登录路由分离;保留原有 URL、通用提示语和令牌有效期语义。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import uuid
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
_RATE_CACHE: dict[str, datetime] = {}
|
||||
_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
|
||||
|
||||
|
||||
def _base_url() -> str:
|
||||
"""读取密码重置的公网基地址,避免将内部服务地址发给企业微信用户。"""
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
base = _compat._clean_str(current_app.config.get(key))
|
||||
if base:
|
||||
return base.rstrip('/')
|
||||
return ''
|
||||
|
||||
|
||||
def _rate_limit(employee_id: str, *, window_seconds: int = 300) -> tuple[bool, int]:
|
||||
"""按工号和来源 IP 限制找回请求,返回是否允许及剩余等待秒数。"""
|
||||
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr) or 'unknown'
|
||||
key = f'{employee_id}:{client_ip}'
|
||||
now = datetime.utcnow()
|
||||
last = _RATE_CACHE.get(key)
|
||||
if last:
|
||||
elapsed = (now - last).total_seconds()
|
||||
if elapsed < window_seconds:
|
||||
return False, max(1, int(window_seconds - elapsed))
|
||||
_RATE_CACHE[key] = now
|
||||
return True, 0
|
||||
|
||||
|
||||
def _sync_casdoor_password(user, new_password: str) -> None:
|
||||
"""令牌重置无需旧密码;Casdoor 启用时仍须同步 IdP 密码。"""
|
||||
if not _compat._is_casdoor_configured():
|
||||
return
|
||||
try:
|
||||
_compat._casdoor_set_password(_compat._casdoor_user_owner(), user.username, '', new_password)
|
||||
except RuntimeError as exc:
|
||||
if _compat._is_casdoor_user_missing_error(str(exc)):
|
||||
_compat._raise_casdoor_user_not_in_idp(exc)
|
||||
_compat._raise_casdoor_set_password_error(exc)
|
||||
|
||||
|
||||
@auth_bp.post('/reset-password-by-wecom', endpoint='reset_password_by_wecom')
|
||||
def request_by_wecom():
|
||||
"""向已绑定企业微信的用户发送限时重置链接。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise AppError(code='WECOM.RESET_NOT_CONFIGURED', message='WeCom password reset is not configured', http_status=503, details={'missing': _compat._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)
|
||||
base_url = _base_url()
|
||||
if not base_url:
|
||||
raise AppError(code='WECOM.RESET_URL_NOT_CONFIGURED', message='Password reset public base URL is not configured', http_status=503)
|
||||
data = request.get_json() or {}
|
||||
employee_id = _compat._clean_str(data.get('employee_id'))
|
||||
username = _compat._clean_str(data.get('username'))
|
||||
if not employee_id:
|
||||
raise ValidationError('Employee ID is required')
|
||||
if not username:
|
||||
raise ValidationError('Username is required')
|
||||
allowed, retry_after_seconds = _rate_limit(employee_id)
|
||||
if not allowed:
|
||||
raise AppError(code='AUTH.PASSWORD_RESET_RATE_LIMITED', message='Password reset requests are too frequent', http_status=429, details={'retry_after_seconds': retry_after_seconds, 'retry_after_minutes': max(1, (retry_after_seconds + 59) // 60)}, retryable=True)
|
||||
user = db.session.query(_compat.User).filter(_compat.User.employee_id == employee_id).first()
|
||||
if not user or user.username != username or user.status != 'active' or not user.wecom_userid:
|
||||
return jsonify({'message': _GENERIC_MESSAGE})
|
||||
token = str(uuid.uuid4())
|
||||
user.reset_token = token
|
||||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||||
db.session.flush()
|
||||
try:
|
||||
result = send_wecom_event_message(event_type='password_reset', user=user, title='和信AI智能工作台 密码重置', content='您发起了和信AI智能工作台密码重置请求。\n请在 1 小时内点击下方按钮设置新密码。\n如非本人操作,请忽略本消息。', jump_url=f'{base_url}/reset-password?token={token}')
|
||||
if not result.get('ok'):
|
||||
db.session.rollback()
|
||||
return jsonify({'message': _GENERIC_MESSAGE})
|
||||
db.session.commit()
|
||||
return jsonify({'message': _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) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/reset-password-by-email', endpoint='reset_password_request')
|
||||
def request_by_email():
|
||||
"""保留邮件找回兼容接口及其既有响应格式。"""
|
||||
data = request.get_json() or {}
|
||||
email = data.get('email')
|
||||
if not email:
|
||||
raise ValidationError('Email is required')
|
||||
user = db.session.query(_compat.User).filter_by(email=email).first()
|
||||
if not user:
|
||||
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||||
user.reset_token = str(uuid.uuid4())
|
||||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||||
db.session.commit()
|
||||
# Legacy development contract: the email channel is mocked by logging its reset link.
|
||||
reset_link = f'http://localhost:5173/reset-password?token={user.reset_token}'
|
||||
print('============================================')
|
||||
print(f'MOCK EMAIL TO: {email}')
|
||||
print('SUBJECT: Password Reset Request')
|
||||
print(f'LINK: {reset_link}')
|
||||
print('============================================')
|
||||
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||||
|
||||
|
||||
@auth_bp.post('/reset-password-confirm', endpoint='reset_password_confirm')
|
||||
def confirm():
|
||||
"""校验重置令牌后同步更新本地与 Casdoor 密码。"""
|
||||
data = request.get_json() or {}
|
||||
token = _compat._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(_compat.User).filter_by(reset_token=token).first()
|
||||
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
|
||||
raise AppError(code='AUTH.RESET_TOKEN_INVALID', message='Invalid or expired token', http_status=400)
|
||||
try:
|
||||
_sync_casdoor_password(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 exc:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
|
||||
@@ -0,0 +1,628 @@
|
||||
"""
|
||||
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.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
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):
|
||||
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 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,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
'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)
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
api/user/auth_wecom.py
|
||||
|
||||
用途:企业微信 OAuth、绑定与回调 HTTP 路由。
|
||||
依赖:auth.auth_bp、auth_support 的企微签名、身份匹配和审计操作。
|
||||
逻辑:将企微认证入口同本地/Casdoor 路由隔离,保持企业微信回调 URL 不变。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.services.wecom_crypto import decrypt_wecom_aes, extract_encrypt_field
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
@auth_bp.get('/wecom/authorize-url', endpoint='wecom_authorize_url')
|
||||
def authorize_url():
|
||||
"""生成企业微信 OAuth 授权地址。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
redirect_uri = request.args.get('redirect_uri') or current_app.config.get('WECOM_REDIRECT_URI')
|
||||
if not redirect_uri:
|
||||
raise ValidationError('redirect_uri is required')
|
||||
state = _compat._issue_wecom_state()
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
agent_id = current_app.config.get('WECOM_AGENT_ID')
|
||||
url = f"https://open.weixin.qq.com/connect/oauth2/authorize?appid={corp_id}&redirect_uri={quote(redirect_uri, safe='')}&response_type=code&scope=snsapi_base&state={quote(state, safe='')}&agentid={agent_id}#wechat_redirect"
|
||||
return jsonify({'url': url, 'state': state})
|
||||
|
||||
|
||||
@auth_bp.post('/wecom/login', endpoint='wecom_login')
|
||||
def login():
|
||||
"""完成企业微信 OAuth 登录并映射或绑定本地用户。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
data = request.get_json() or {}
|
||||
code, state = data.get('code'), data.get('state')
|
||||
if not code:
|
||||
_compat._write_login_audit('wecom', 'failed', reason='missing_code')
|
||||
db.session.commit()
|
||||
raise ValidationError('code is required')
|
||||
if not _compat._consume_wecom_state(state):
|
||||
_compat._write_login_audit('wecom', 'failed', reason='invalid_state')
|
||||
db.session.commit()
|
||||
raise ValidationError('Invalid or expired WeCom state')
|
||||
wecom_userid = None
|
||||
try:
|
||||
access_token = _compat._get_wecom_access_token()
|
||||
info = requests.get('https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo', params={'access_token': access_token, 'code': code}, timeout=8).json()
|
||||
wecom_userid = info.get('userid') or info.get('UserId')
|
||||
if info.get('errcode') != 0:
|
||||
raise UnauthorizedError(f"WeCom auth failed: {info.get('errmsg', 'unknown error')}")
|
||||
if not wecom_userid:
|
||||
raise AppError(code='WECOM_NOT_IN_AGENT_SCOPE', message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。', http_status=401)
|
||||
wecom_user = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': wecom_userid}, timeout=8).json()
|
||||
if wecom_user.get('errcode') != 0:
|
||||
raise UnauthorizedError(f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}")
|
||||
user, bind_status, rule_info = _compat._sync_or_create_user_from_wecom(wecom_user)
|
||||
if user.status != 'active':
|
||||
raise ForbiddenError('Account is disabled')
|
||||
_compat._write_login_audit('wecom', 'success', user=user, wecom_userid=wecom_userid, match_rules=rule_info.get('fields'), match_operator=rule_info.get('operator'), match_result=bind_status)
|
||||
db.session.commit()
|
||||
return jsonify(_compat._build_login_payload(user, 'wecom', bind_status=bind_status))
|
||||
except _compat.WeComLoginError as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', reason=exc.reason or 'wecom_login_error', wecom_userid=wecom_userid, error_code=exc.error_code)
|
||||
db.session.commit()
|
||||
raise
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', reason=str(exc)[:160], wecom_userid=wecom_userid, error_code=exc.code)
|
||||
db.session.commit()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if _compat._is_users_pk_sequence_error(exc):
|
||||
_compat._write_login_audit('wecom', 'failed', reason='db_sequence_misconfig', wecom_userid=wecom_userid, error_code='DB_SEQUENCE_MISCONFIG')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.DB_SEQUENCE_MISCONFIG', message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。', http_status=500) from exc
|
||||
_compat._write_login_audit('wecom', 'failed', reason=f'exception:{str(exc)[:160]}', wecom_userid=wecom_userid)
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom login failed: {exc}', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/wecom/complete-bind', endpoint='wecom_complete_bind')
|
||||
def complete_bind():
|
||||
"""提交首登人工绑定信息并完成企业微信账号绑定。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
data = request.get_json() or {}
|
||||
token, field, value = _compat._clean_str(data.get('binding_token')), _compat._clean_str(data.get('field')), data.get('value')
|
||||
identity = _compat._get_wecom_bind_session(token)
|
||||
if not identity:
|
||||
raise AppError(code='WECOM_BIND_SESSION_EXPIRED', message='WeCom binding session expired. Please restart WeCom login.', http_status=400)
|
||||
allowed_fields = _compat._get_wecom_first_login_input_fields()
|
||||
if field not in allowed_fields:
|
||||
raise AppError(code='WECOM_BIND_FIELD_NOT_ALLOWED', message='Selected bind field is not allowed', http_status=400, details={'allowed_fields': allowed_fields})
|
||||
matched_users, missing_field = _compat._find_users_by_input_field(field, value)
|
||||
if missing_field:
|
||||
raise AppError(code='WECOM_BIND_INPUT_VALUE_REQUIRED', message=f'{field} is required', http_status=400, details={'field': field})
|
||||
if not matched_users:
|
||||
raise AppError(code='WECOM_BIND_INPUT_NOT_FOUND', message='No local account matched the verification value.', http_status=404, details={'field': field})
|
||||
if len(matched_users) > 1:
|
||||
raise ConflictError('Multiple local accounts matched the verification value.', code='WECOM_BIND_INPUT_AMBIGUOUS', details={'field': field, 'candidate_count': len(matched_users)})
|
||||
user = matched_users[0]
|
||||
if user.status != 'active':
|
||||
raise ForbiddenError('Account is disabled')
|
||||
try:
|
||||
_compat._sync_user_from_wecom_identity(user, identity)
|
||||
_compat._write_login_audit('wecom', 'success', user=user, wecom_userid=identity.get('wecom_userid'), match_rules=[field], match_operator='AND', match_result='input_verified_and_bound')
|
||||
db.session.commit()
|
||||
_compat._WECOM_BIND_SESSION_CACHE.pop(token, None)
|
||||
return jsonify(_compat._build_login_payload(user, 'wecom', bind_status='input_verified_and_bound'))
|
||||
except _compat.WeComLoginError as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', user=user, reason=exc.reason or 'wecom_input_bind_error', wecom_userid=identity.get('wecom_userid'), error_code=exc.error_code, match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', user=user, reason=f'exception:{str(exc)[:160]}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_EXCEPTION', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom bind failed: {exc}', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.route('/wecom/callback', methods=['GET', 'POST'], endpoint='wecom_callback')
|
||||
def callback():
|
||||
"""处理企业微信 URL 验证及加密事件回调。"""
|
||||
signature = request.args.get('msg_signature') or request.args.get('signature')
|
||||
timestamp, nonce = request.args.get('timestamp', ''), request.args.get('nonce', '')
|
||||
token = current_app.config.get('WECOM_CALLBACK_TOKEN') or ''
|
||||
aes_key, corp_id = current_app.config.get('WECOM_ENCODING_AES_KEY') or '', current_app.config.get('WECOM_CORP_ID') or ''
|
||||
if not token:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='callback token not configured', http_status=500)
|
||||
if request.method == 'GET':
|
||||
echostr = request.args.get('echostr', '') or ''
|
||||
if not _compat._verify_wecom_msg_signature(signature, token, timestamp, nonce, echostr):
|
||||
raise ForbiddenError('invalid callback signature')
|
||||
try:
|
||||
plain = decrypt_wecom_aes(echostr, aes_key, corp_id) if aes_key else echostr
|
||||
except Exception as exc:
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, error_message=f'decrypt_failed:{str(exc)[:200]}')
|
||||
raise ValidationError('decrypt failed') from exc
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, decrypted_xml=plain, msg_type='url_verify' if aes_key else 'url_verify_plain')
|
||||
return plain, 200, {'Content-Type': 'text/plain; charset=utf-8'}
|
||||
payload = request.get_data(as_text=True) or ''
|
||||
encrypt_field = extract_encrypt_field(payload) or ''
|
||||
if not encrypt_field:
|
||||
raise ValidationError('missing Encrypt field')
|
||||
if not _compat._verify_wecom_msg_signature(signature, token, timestamp, nonce, encrypt_field):
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message='invalid_msg_signature')
|
||||
raise ForbiddenError('invalid callback signature')
|
||||
decrypted = None
|
||||
if aes_key:
|
||||
try:
|
||||
decrypted = decrypt_wecom_aes(encrypt_field, aes_key, corp_id)
|
||||
except Exception as exc:
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message=f'decrypt_failed:{str(exc)[:200]}')
|
||||
raise ValidationError('decrypt failed') from exc
|
||||
_compat._persist_wecom_callback_audit(
|
||||
msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field,
|
||||
decrypted_xml=decrypted, msg_type=_compat._extract_xml_field(decrypted, 'MsgType') if decrypted else None,
|
||||
event=_compat._extract_xml_field(decrypted, 'Event') if decrypted else None,
|
||||
from_user=_compat._extract_xml_field(decrypted, 'FromUserName') if decrypted else None,
|
||||
agent_id=_compat._extract_xml_field(decrypted, 'AgentID') if decrypted else None,
|
||||
msg_id=_compat._extract_xml_field(decrypted, 'MsgId') if decrypted else None,
|
||||
)
|
||||
return 'success', 200, {'Content-Type': 'text/plain; charset=utf-8'}
|
||||
|
||||
|
||||
@auth_bp.get('/wecom/binding', endpoint='get_wecom_binding')
|
||||
def binding():
|
||||
"""返回当前用户的企业微信绑定状态。"""
|
||||
user = _compat._get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
return jsonify({'bound': bool(user.wecom_userid), 'wecom_userid': user.wecom_userid, 'wecom_unionid': user.wecom_unionid})
|
||||
|
||||
|
||||
@auth_bp.post('/wecom/unbind', endpoint='unbind_wecom_self')
|
||||
def unbind():
|
||||
"""解除当前用户与企业微信账号的绑定。"""
|
||||
user = _compat._get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
user.wecom_userid = None
|
||||
user.wecom_unionid = None
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'message': 'WeCom account unbound'})
|
||||
@@ -0,0 +1,380 @@
|
||||
"""
|
||||
backend/app/api/user/handlers.py
|
||||
|
||||
用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、models、wecom/dify 相关 services。
|
||||
逻辑:薄路由层鉴权与参数校验;Casdoor/企微 OAuth 委托 services/auth/*。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, 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.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
import re
|
||||
import ast
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from .auth import (
|
||||
_clean_str,
|
||||
_get_current_user,
|
||||
_parse_leave_int_flag,
|
||||
_run_db_with_retry,
|
||||
)
|
||||
user_bp = Blueprint('user', __name__)
|
||||
|
||||
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
||||
def mark_wecom_deeplink_opened():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
trace_id = _clean_str(data.get('trace_id'))
|
||||
if not trace_id:
|
||||
raise ValidationError('trace_id is required')
|
||||
ok = mark_wecom_message_opened(trace_id)
|
||||
if not ok:
|
||||
raise NotFoundError('trace_id not found')
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/wecom/task-complete', methods=['POST'])
|
||||
def wecom_task_complete():
|
||||
"""
|
||||
Lightweight endpoint for sending task completion WeCom message.
|
||||
Can be called by frontend after long-running task is done.
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
title = _clean_str(data.get('title')) or 'AI 任务已完成'
|
||||
content = _clean_str(data.get('content')) or '你发起的 AI 任务已完成,点击查看详情。'
|
||||
agent_id = data.get('agent_id')
|
||||
jump_path = '/workspace'
|
||||
jump_params = {}
|
||||
if agent_id:
|
||||
jump_path = f'/chat/{int(agent_id)}'
|
||||
result = send_wecom_event_message(event_type='task_completed', user=user, title=title, content=content, jump_path=jump_path, jump_params=jump_params)
|
||||
db.session.commit()
|
||||
return (jsonify(result), 200 if result.get('ok') else 202)
|
||||
|
||||
@user_bp.route('/leave-balance', methods=['GET'])
|
||||
def get_leave_balance():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
leave_type_code = _clean_str(request.args.get('leave_type'))
|
||||
if leave_type_code not in ('010', '408'):
|
||||
raise ValidationError('仅支持查询年假(010)和育儿假(408)的余额')
|
||||
try:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
employee_code = HRLeaveSQLServerService._get_employee_code(user)
|
||||
now_year = datetime.now().year
|
||||
if leave_type_code == '010':
|
||||
_, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D044', year_column='D044001', total_column='D044005', used_column='D044006', remaining_column='D044007', employee_code=employee_code, year=now_year)
|
||||
label = '年假'
|
||||
else:
|
||||
_, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D072', year_column='d072001', total_column='d072002', used_column='d072003', remaining_column='d072004', employee_code=employee_code, year=now_year)
|
||||
label = '育儿假'
|
||||
remaining = record.get('remaining_hours') if record else None
|
||||
try:
|
||||
has_balance = remaining is not None and float(remaining) > 0
|
||||
except (TypeError, ValueError):
|
||||
has_balance = False
|
||||
return jsonify({'leave_type_code': leave_type_code, 'leave_type_label': label, 'year': record.get('leave_year', now_year) if record else now_year, 'total_hours': record.get('total_hours') if record else None, 'used_hours': record.get('used_hours') if record else None, 'remaining_hours': remaining, 'has_balance': has_balance})
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[leave-balance] query failed user_id=%s', getattr(user, 'id', None))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'假期余额查询失败:{exc}', http_status=500)
|
||||
|
||||
@user_bp.route('/leave-workflow/submit', methods=['POST'])
|
||||
def submit_leave_workflow():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
form_data = {'applicantName': _clean_str(data.get('applicantName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)), 'employeeId': _clean_str(data.get('employeeId')) or _clean_str(getattr(user, 'employee_id', None)) or _clean_str(getattr(user, 'username', None)), 'applicantJobTitle': _clean_str(data.get('applicantJobTitle')), 'applicantDepartmentId': _clean_str(data.get('applicantDepartmentId')), 'applicantSubCompanyId1': _clean_str(data.get('applicantSubCompanyId1')), 'applyTime': _clean_str(data.get('applyTime')), 'fillerName': _clean_str(data.get('fillerName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)), 'agentUid': _clean_str(data.get('agentUid')), 'agentEmployeeId': _clean_str(data.get('agentEmployeeId')), 'agentName': _clean_str(data.get('agentName')), 'agentJobTitle': _clean_str(data.get('agentJobTitle')), 'agentDepartmentId': _clean_str(data.get('agentDepartmentId')), 'agentSubCompanyId1': _clean_str(data.get('agentSubCompanyId1')), 'leaveType': _clean_str(data.get('leaveType')), 'startTime': _clean_str(data.get('startTime')), 'endTime': _clean_str(data.get('endTime')), 'durationHours': data.get('durationHours'), 'isOutOfOffice': _parse_leave_int_flag(data.get('isOutOfOffice'), '是否外出'), 'isWorkInjury': _parse_leave_int_flag(data.get('isWorkInjury'), '是否为工伤'), 'remark': _clean_str(data.get('remark')) or ''}
|
||||
required_fields = {'applicantName': '请假人', 'employeeId': '工号', 'fillerName': '填单人', 'agentUid': '代理人UID', 'agentEmployeeId': '代理人工号', 'agentName': '代理人姓名', 'leaveType': '假别', 'startTime': '开始时间', 'endTime': '结束时间'}
|
||||
for key, label in required_fields.items():
|
||||
if not form_data.get(key):
|
||||
raise ValidationError(f'{label}不能为空。')
|
||||
try:
|
||||
from app.services.oa_leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
|
||||
result = OALeaveWorkflowService.submit_leave_request(form_data, user)
|
||||
except OALeaveWorkflowError as exc:
|
||||
current_app.logger.warning('[oa-leave] submit failed user_id=%s employee_id=%s err=%s', getattr(user, 'id', None), form_data.get('employeeId'), exc)
|
||||
raise ValidationError(str(exc))
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[oa-leave] unexpected submit failure user_id=%s', getattr(user, 'id', None))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'OA 请假提交失败:{exc}', http_status=500)
|
||||
current_app.logger.info('[oa-leave] submit success user_id=%s employee_id=%s request_id=%s workflow_id=%s', getattr(user, 'id', None), form_data.get('employeeId'), result.get('request_id'), result.get('workflow_id'))
|
||||
return jsonify(result)
|
||||
|
||||
@user_bp.route('/feedback', methods=['POST'])
|
||||
def submit_general_feedback():
|
||||
"""
|
||||
通用意见反馈接口(与 /api/chat/feedback 的对话评分接口不同
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
feedback_type = _clean_str(data.get('feedback_type'))
|
||||
feedback_module = _clean_str(data.get('feedback_module'))
|
||||
content = _clean_str(data.get('content'))
|
||||
source_page = _clean_str(data.get('source_page'))
|
||||
raw_chat_log_id = data.get('chat_log_id')
|
||||
chat_log_id = None
|
||||
if raw_chat_log_id not in (None, ''):
|
||||
try:
|
||||
chat_log_id = int(raw_chat_log_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('chat_log_id must be an integer')
|
||||
if chat_log_id <= 0:
|
||||
raise ValidationError('chat_log_id must be a positive integer')
|
||||
if not feedback_type:
|
||||
raise ValidationError('feedback_type is required')
|
||||
if not feedback_module:
|
||||
raise ValidationError('feedback_module is required')
|
||||
if len(feedback_type) > 32:
|
||||
raise ValidationError('feedback_type is too long')
|
||||
if len(feedback_module) > 32:
|
||||
raise ValidationError('feedback_module is too long')
|
||||
if not content:
|
||||
raise ValidationError('content is required')
|
||||
if len(content) > 2000:
|
||||
raise ValidationError('content is too long')
|
||||
if source_page != 'chat':
|
||||
chat_log_id = None
|
||||
if chat_log_id is not None:
|
||||
chat_log = db.session.get(ChatLog, chat_log_id)
|
||||
if not chat_log:
|
||||
raise ValidationError('chat_log_id not found')
|
||||
if chat_log.user_id != user.id:
|
||||
raise ForbiddenError('chat_log_id is not owned by current user')
|
||||
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
notify_result = send_feedback_group_notification(row, user)
|
||||
if notify_result.get('ok'):
|
||||
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
||||
elif not notify_result.get('skipped'):
|
||||
current_app.logger.warning(
|
||||
'[feedback] group notification failed feedback_id=%s reason=%s',
|
||||
row.id,
|
||||
notify_result.get('reason'),
|
||||
)
|
||||
return jsonify({'status': 'ok', 'id': row.id})
|
||||
|
||||
@user_bp.route('/home', methods=['GET'])
|
||||
def home():
|
||||
"""
|
||||
Get user homepage data
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
agent_rows = sort_agent_rows(agent_rows)
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
or_(
|
||||
QuickQuestion.user_id == user.id,
|
||||
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
|
||||
)
|
||||
).all()
|
||||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
layout = layout_config.layout if layout_config else {}
|
||||
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
embedded_agents = []
|
||||
for rel in embedded_rel:
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
registry = serialize_registry_fields(agent)
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': registry.get('iframe_url'),
|
||||
'runtime_provider': registry.get('runtime_provider'),
|
||||
'conversation_mode': registry.get('conversation_mode'),
|
||||
})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('user.home retry failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
|
||||
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
|
||||
def toggle_favorite(agent_id: int):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'POST':
|
||||
exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first()
|
||||
if not exists:
|
||||
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
|
||||
db.session.add(fav)
|
||||
else:
|
||||
db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).delete()
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/quick-questions', methods=['POST'])
|
||||
def add_quick_question():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
|
||||
raise ValidationError('Missing fields')
|
||||
qq = QuickQuestion(user_id=user.id, title=data['title'], question=data['question'], agent_id=data['agent_id'])
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
return (jsonify({'message': 'Added', 'id': qq.id}), 201)
|
||||
|
||||
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT', 'DELETE'])
|
||||
def update_quick_question(qq_id: int):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
|
||||
if not qq:
|
||||
raise NotFoundError('QuickQuestion not found or permission denied')
|
||||
if request.method == 'DELETE':
|
||||
db.session.delete(qq)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
data = request.get_json() or {}
|
||||
if 'title' in data:
|
||||
qq.title = data['title']
|
||||
if 'question' in data:
|
||||
qq.question = data['question']
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/homepage-layout', methods=['PUT'])
|
||||
def update_layout():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
layout = data.get('layout', {})
|
||||
config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
if not config:
|
||||
config = UserHomepageConfig(user_id=user.id, layout=layout)
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.layout = layout
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/profile', methods=['GET', 'PUT'])
|
||||
def user_profile():
|
||||
"""
|
||||
User profile management
|
||||
GET: Get details
|
||||
PUT: Update basic info
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'GET':
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
data = request.get_json() or {}
|
||||
|
||||
def _update_profile():
|
||||
if 'real_name' in data:
|
||||
user.real_name = data['real_name']
|
||||
if 'phone_number' in data:
|
||||
user.phone_number = data['phone_number']
|
||||
if 'language' in data:
|
||||
user.language = data['language']
|
||||
if 'theme_preference' in data:
|
||||
if data['theme_preference'] not in ['light', 'dark', 'system']:
|
||||
raise ValidationError('Invalid theme preference')
|
||||
user.theme_preference = data['theme_preference']
|
||||
if 'email' in data:
|
||||
if data['email']:
|
||||
existing = db.session.query(User).filter_by(email=data['email']).first()
|
||||
if existing and existing.id != user.id:
|
||||
raise ValidationError('Email already exists')
|
||||
user.email = data['email']
|
||||
if 'employee_id' in data:
|
||||
if data['employee_id']:
|
||||
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
|
||||
if existing and existing.id != user.id:
|
||||
raise ValidationError('Employee ID already exists')
|
||||
user.employee_id = data['employee_id']
|
||||
if 'department' in data:
|
||||
user.department = data['department']
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Profile updated successfully'})
|
||||
try:
|
||||
return _run_db_with_retry(_update_profile, label='user.profile.update')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('user.profile.update retry failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
@user_bp.route('/agents/<int:id>', methods=['GET'])
|
||||
def get_agent_details(id):
|
||||
"""
|
||||
Get agent details with permission check
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
if user.role != 'admin':
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_user_detail
|
||||
|
||||
dify_parameters = None
|
||||
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
|
||||
from app.services.dify import DifyService
|
||||
|
||||
try:
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
if isinstance(params, dict):
|
||||
dify_parameters = {
|
||||
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
|
||||
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
|
||||
}
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
|
||||
|
||||
return jsonify(serialize_agent_for_user_detail(
|
||||
agent,
|
||||
dify_parameters=dify_parameters,
|
||||
))
|
||||
|
||||
@user_bp.route('/db', methods=['GET'])
|
||||
def get_db():
|
||||
from app.models import User
|
||||
from app import db
|
||||
u = db.session.query(User).filter_by(username='26040006').first()
|
||||
return jsonify({'db': current_app.config.get('SQLALCHEMY_DATABASE_URI'), 'user': u.username if u else None})
|
||||
Reference in new issue
Block a user