fix(auth): 重构登录认证,并支持跳转到关联服务如图纸标注

This commit is contained in:
sophie committed 2026-07-29 13:22:31 +08:00
1 parent ce1fd59f61
commit affe139bf9
51 files changed
+1939 -132

No files matched your search

+2
View File
@@ -27,6 +27,7 @@ def register_blueprints(app: Flask) -> None:
from app.api.maintenance import maintenance_bp
from app.api.speech import speech_bp
from app.api.sso import sso_bp, sso_well_known_bp
from app.api.linked_services import linked_services_bp
from app.api.training import training_admin_bp, training_user_bp
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
@@ -63,6 +64,7 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
app.register_blueprint(sso_bp, url_prefix='/api/sso')
app.register_blueprint(linked_services_bp, url_prefix='/api')
app.register_blueprint(sso_well_known_bp)
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
app.register_blueprint(files_bp, url_prefix='/api/files')
+1
View File
@@ -19,6 +19,7 @@ import app.api.admin.permissions # noqa: F401
import app.api.admin.users # noqa: F401
import app.api.admin.wecom # noqa: F401
import app.api.admin.announcements # noqa: F401
import app.api.admin.linked_services # noqa: F401
import app.api.admin.procurement_contract # noqa: F401
__all__ = ['admin_bp']
+44
View File
@@ -0,0 +1,44 @@
"""
backend/app/api/admin/linked_services.py
用途:管理后台关联服务 CRUD API(薄路由层)。
依赖:admin.blueprint、services/admin/linked_service_service。
逻辑:/linked-services* 路由;侧栏只读见 api/linked_services.py。
"""
from flask import jsonify, request
from app.api.admin.blueprint import admin_bp
from app.core.decorators import require_admin
from app.services.admin import linked_service_service
@admin_bp.route('/linked-services', methods=['GET'])
@require_admin
def list_linked_services():
"""列出全部关联服务(含停用)。"""
return jsonify(linked_service_service.list_linked_services())
@admin_bp.route('/linked-services', methods=['POST'])
@require_admin
def create_linked_service():
"""创建关联服务。"""
data = request.get_json() or {}
payload = linked_service_service.create_linked_service(data)
return jsonify(payload), 201
@admin_bp.route('/linked-services/<int:id>', methods=['PUT'])
@require_admin
def update_linked_service(id: int):
"""更新关联服务。"""
data = request.get_json() or {}
return jsonify(linked_service_service.update_linked_service(id, data))
@admin_bp.route('/linked-services/<int:id>', methods=['DELETE'])
@require_admin
def delete_linked_service(id: int):
"""删除关联服务。"""
return jsonify(linked_service_service.delete_linked_service(id))
+39
View File
@@ -0,0 +1,39 @@
"""
backend/app/api/linked_services.py
用途:已登录用户读取启用中的关联服务,供 Chat/工作台侧栏入口展示。
依赖:JWT current-user、linked_service_service。
逻辑:仅返回 is_enabled=true;目录失败时由前端静默隐藏入口。
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, UnauthorizedError
from app.services.admin import linked_service_service
linked_services_bp = Blueprint('linked_services', __name__)
def _require_active_user():
"""解析 Bearer 登录用户;未登录或停用账号时拒绝。"""
authorization = str(request.headers.get('Authorization') or '').strip()
scheme, _, token = authorization.partition(' ')
if scheme.lower() != 'bearer' or not token.strip():
raise UnauthorizedError('Bearer token is required')
user = get_current_user()
if user is None:
raise UnauthorizedError('Unauthorized')
if user.status != 'active':
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
return user
@linked_services_bp.route('/linked-services', methods=['GET'])
def list_enabled_linked_services():
"""返回当前用户可见的已启用关联服务。"""
_require_active_user()
return jsonify({'items': linked_service_service.list_enabled_linked_services()})
+35 -72
View File
@@ -20,10 +20,6 @@ from datetime import datetime, timedelta
import uuid
import requests
from urllib.parse import quote
import hashlib
import hmac
import base64
import json
import re
import ast
from app.core.errors import (
@@ -37,8 +33,9 @@ from app.core.errors import (
raise_for_status,
)
from app.services.auth import casdoor_service as _casdoor_svc
from app.services.auth.casdoor import get_casdoor_client
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
user_bp = Blueprint('user', __name__)
_WECOM_ACCESS_TOKEN_CACHE = _wecom_svc.ACCESS_TOKEN_CACHE
@@ -139,43 +136,25 @@ def _is_wecom_configured() -> bool:
return _wecom_svc.is_configured()
def _issue_casdoor_state(redirect_uri: str):
exp_ts = int((datetime.utcnow() + timedelta(minutes=10)).timestamp())
nonce = uuid.uuid4().hex
payload = {'v': 1, 'exp': exp_ts, 'nonce': nonce, 'redirect_uri': redirect_uri}
payload_json = json.dumps(payload, separators=(',', ':'))
payload_b64 = base64.urlsafe_b64encode(payload_json.encode('utf-8')).decode('ascii').rstrip('=')
secret = str(current_app.config.get('SECRET_KEY') or '')
sign = hmac.new(secret.encode('utf-8'), payload_b64.encode('ascii'), hashlib.sha256).digest()
sign_b64 = base64.urlsafe_b64encode(sign).decode('ascii').rstrip('=')
return f'hxops_casdoor_v1.{payload_b64}.{sign_b64}'
"""兼容旧调用点:签发格式不变的 Casdoor state。"""
return _casdoor_route_adapter.issue_casdoor_state(redirect_uri)
def _consume_casdoor_state(state: str):
if not state:
return None
try:
parts = state.split('.')
if len(parts) != 3 or parts[0] != 'hxops_casdoor_v1':
return None
payload_b64 = parts[1]
sign_b64 = parts[2]
secret = str(current_app.config.get('SECRET_KEY') or '')
expected_sign = hmac.new(secret.encode('utf-8'), payload_b64.encode('ascii'), hashlib.sha256).digest()
expected_b64 = base64.urlsafe_b64encode(expected_sign).decode('ascii').rstrip('=')
if not hmac.compare_digest(expected_b64, sign_b64):
return None
padded = payload_b64 + '=' * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode('ascii')).decode('utf-8'))
except Exception:
return None
exp = int(payload.get('exp') or 0)
now_ts = int(datetime.utcnow().timestamp())
if exp <= now_ts:
return None
return _clean_str(payload.get('redirect_uri'))
"""兼容旧调用点:校验 Casdoor state 并恢复签名绑定的 redirect_uri。"""
return _casdoor_route_adapter.consume_casdoor_state(state)
def _get_casdoor_oidc_metadata():
"""兼容旧调用点:委托公共 CasdoorClient 获取 discovery 文档。"""
return get_casdoor_client().oidc_metadata()
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 用户。"""
@@ -232,32 +211,32 @@ def _issue_casdoor_api_token(user: User, claims: dict) -> str:
def _casdoor_exchange_code(code: str, redirect_uri: str):
"""兼容旧测试替换点:委托公共客户端执行 authorization code grant。"""
return get_casdoor_client().authorization_code_login(code, redirect_uri).as_dict()
return _casdoor_route_adapter.authorization_code_login(code, redirect_uri)
def _casdoor_refresh_token(refresh_token: str):
"""兼容旧测试替换点:委托公共客户端执行 refresh grant。"""
return get_casdoor_client().refresh(refresh_token).as_dict()
return _casdoor_route_adapter.refresh_token(refresh_token)
def _casdoor_userinfo(access_token: str):
"""兼容旧测试替换点:委托公共客户端读取 userinfo。"""
return get_casdoor_client().userinfo(access_token)
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 get_casdoor_client().password_login(username, password).as_dict()
return _casdoor_route_adapter.password_login(username, password)
def _hxops_login_service() -> HxopsLoginService:
"""创建使用当前兼容代理的登录服务,使既有 monkeypatch 测试和调用方式保持有效。"""
return HxopsLoginService(
password_login=_casdoor_password_login,
authorization_code_login=_casdoor_exchange_code,
refresh_token=_casdoor_refresh_token,
userinfo=_casdoor_userinfo,
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:
@@ -284,8 +263,9 @@ def _raise_casdoor_add_user_error(source) -> None:
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, real_name=None, phone_number=None, status='active', department=None):
return _casdoor_svc.sync_create_user(username=username, password=password, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department)
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)
@@ -798,30 +778,13 @@ def casdoor_authorize_url():
- Failed to build Casdoor authorize url: <detail>
"""
try:
meta = _get_casdoor_oidc_metadata()
authorize_endpoint = meta.get('authorization_endpoint')
if not authorize_endpoint:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Casdoor authorization endpoint missing', http_status=500)
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
redirect_uri = _clean_str(request.args.get('redirect_uri')) or (current_app.config.get('CASDOOR_REDIRECT_URI') or '')
scope = current_app.config.get('CASDOOR_SCOPE') or 'openid profile email'
if not client_id or not redirect_uri:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Casdoor client config is incomplete', http_status=500)
default_provider = (_clean_str(request.args.get('default_provider')) or '').lower()
provider_hint = _clean_str(request.args.get('provider_hint'))
if not provider_hint and default_provider == 'wecom':
provider_hint = current_app.config.get('CASDOOR_WECOM_PROVIDER_HINT') or ''
silent_raw = (_clean_str(request.args.get('silent_signin')) or '').lower()
silent_signin = silent_raw in ('1', 'true', 'yes')
if not silent_signin and default_provider == 'wecom':
silent_signin = bool(current_app.config.get('CASDOOR_WECOM_SILENT_SIGNIN'))
state = _issue_casdoor_state(redirect_uri)
url = f"{authorize_endpoint}?client_id={quote(client_id, safe='')}&response_type=code&redirect_uri={quote(redirect_uri, safe='')}&scope={quote(scope, safe='')}&state={quote(state, safe='')}"
if provider_hint:
url += f"&provider_hint={quote(provider_hint, safe='')}"
if silent_signin:
url += '&silentSignin=1'
return jsonify({'url': url, 'state': state, 'redirect_uri': redirect_uri})
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(_build_casdoor_authorize_payload(options))
except Exception as e:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'Failed to build Casdoor authorize url: {str(e)}', http_status=500)
+2
View File
@@ -11,6 +11,7 @@ from app.models.base import Base, user_agent_permissions
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
from app.models.department import Department
from app.models.linked_service import LinkedService
from app.models.job import Job
from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, KbJob
from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, MaintenanceRecord
@@ -52,6 +53,7 @@ __all__ = [
'QuickQuestion',
'FaqHotCandidate',
'Announcement',
'LinkedService',
'LoginAudit',
'WecomNotifyAudit',
'AppSetting',
+35
View File
@@ -0,0 +1,35 @@
"""
backend/app/models/linked_service.py
用途:管理台可配置的关联服务(名称 + URL),供 Chat/工作台侧栏入口展示。
依赖:models.base.Base。
逻辑:admin CRUD 写入本表;已登录用户只读启用项,由 ExternalSystemLinks 渲染。
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import Boolean, DateTime, Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
class LinkedService(Base):
"""
关联服务表
用途:存储产品内其它服务的显示名称与访问地址。
"""
__tablename__ = 'linked_services'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100), nullable=False)
url: Mapped[str] = mapped_column(String(500), nullable=False)
is_enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
)
+2
View File
@@ -12,6 +12,7 @@ from . import (
department_service,
faq_service,
guide_service,
linked_service_service,
permission_service,
report_service,
user_service,
@@ -26,6 +27,7 @@ __all__ = [
'department_service',
'faq_service',
'guide_service',
'linked_service_service',
'permission_service',
'report_service',
'user_service',
@@ -0,0 +1,130 @@
"""
backend/app/services/admin/linked_service_service.py
用途:关联服务 CRUD 与侧栏只读列表。
依赖:models.LinkedService、app.core.errors。
逻辑:api/admin/linked_services.py 管理 CRUD;api/linked_services.py 返回已启用项。
"""
from __future__ import annotations
from typing import Any
from urllib.parse import urlparse
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import LinkedService
def _normalize_name(value: Any) -> str:
"""校验并规范化显示名称。"""
name = str(value or '').strip()
if not name:
raise ValidationError('Name is required')
if len(name) > 100:
raise ValidationError('Name is too long')
return name
def _normalize_url(value: Any) -> str:
"""
校验并规范化访问地址。
核心逻辑:仅允许 http/https,且必须含主机;内网 IP 可用 http。
"""
url = str(value or '').strip()
if not url:
raise ValidationError('URL is required')
if len(url) > 500:
raise ValidationError('URL is too long')
parsed = urlparse(url)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise ValidationError('URL must be an absolute http(s) address')
return url
def serialize_linked_service(row: LinkedService, *, include_admin_fields: bool = False) -> dict:
"""LinkedService ORM → API dict。"""
payload = {
'id': row.id,
'name': row.name,
'url': row.url,
}
if include_admin_fields:
payload.update({
'is_enabled': bool(row.is_enabled),
'sort_order': int(row.sort_order or 0),
'created_at': row.created_at.isoformat() if row.created_at else None,
'updated_at': row.updated_at.isoformat() if row.updated_at else None,
})
return payload
def list_enabled_linked_services() -> list[dict]:
"""返回已启用关联服务,供 Chat/工作台侧栏入口使用。"""
rows = (
db.session.query(LinkedService)
.filter(LinkedService.is_enabled.is_(True))
.order_by(LinkedService.sort_order.asc(), LinkedService.id.asc())
.all()
)
return [serialize_linked_service(row) for row in rows]
def list_linked_services() -> list[dict]:
"""管理端列表:含停用项与排序字段。"""
rows = (
db.session.query(LinkedService)
.order_by(LinkedService.sort_order.asc(), LinkedService.id.asc())
.all()
)
return [serialize_linked_service(row, include_admin_fields=True) for row in rows]
def create_linked_service(data: dict[str, Any]) -> dict:
"""
创建关联服务。
Args:
data: 含 name、url;可选 is_enabled、sort_order。
Returns:
{ id, message }
"""
row = LinkedService(
name=_normalize_name(data.get('name')),
url=_normalize_url(data.get('url')),
is_enabled=bool(data.get('is_enabled', True)),
sort_order=int(data.get('sort_order') or 0),
)
db.session.add(row)
db.session.commit()
return {'message': 'Created', 'id': row.id}
def update_linked_service(service_id: int, data: dict[str, Any]) -> dict:
"""
更新关联服务。
Raises:
NotFoundError: 记录不存在。
"""
row = db.session.get(LinkedService, service_id)
if not row:
raise NotFoundError('Not found')
row.name = _normalize_name(data.get('name'))
row.url = _normalize_url(data.get('url'))
if 'is_enabled' in data:
row.is_enabled = bool(data.get('is_enabled'))
if 'sort_order' in data:
row.sort_order = int(data.get('sort_order') or 0)
db.session.commit()
return {'message': 'Updated'}
def delete_linked_service(service_id: int) -> dict:
"""删除关联服务(不存在时静默成功)。"""
row = db.session.get(LinkedService, service_id)
if row:
db.session.delete(row)
db.session.commit()
return {'message': 'Deleted'}
@@ -214,6 +214,7 @@ def create_user(data: dict[str, Any]) -> dict:
casdoor_service.sync_create_user(
username=user.username,
password=data['password'],
employee_id=user.employee_id,
email=email,
real_name=user.real_name,
phone_number=user.phone_number,
+12 -1
View File
@@ -24,6 +24,17 @@ def _claim_text(claims: Mapping[str, Any], *keys: str) -> str | None:
return None
def _claim_or_property_text(claims: Mapping[str, Any], *keys: str) -> str | None:
"""优先读取顶层 claim,再兼容 Casdoor properties 中同名的用户自定义属性。"""
value = _claim_text(claims, *keys)
if value:
return value
properties = claims.get('properties')
if isinstance(properties, Mapping):
return _claim_text(properties, *keys)
return None
def identity_from_claims(
claims: Mapping[str, Any],
*,
@@ -53,7 +64,7 @@ def identity_from_claims(
display_name=_claim_text(claims, 'display_name', 'displayName', 'real_name', 'realName', 'name'),
email=_claim_text(claims, 'email'),
phone_number=_claim_text(claims, 'phone_number', 'phone'),
employee_id=_claim_text(claims, 'employee_id', 'employeeId'),
employee_id=_claim_or_property_text(claims, 'employee_id', 'employeeId'),
department=_claim_text(claims, 'department', 'affiliation'),
)
return require_stable_identity(identity)
+9 -1
View File
@@ -2,11 +2,14 @@
backend/app/services/auth/hxops/__init__.py
用途:导出依赖 HXOPS User、数据库和会话契约的认证编排能力。
依赖:user_resolver、session_token、login_service、casdoor_user_sync。
依赖:user_resolver、session_token、login_service、casdoor_route_adapter、casdoor_authorize、casdoor_state、casdoor_user_sync。
逻辑:API 路由调用本包;平级服务不复制本目录。
"""
from .login_service import HxopsLoginService, LoginResult
from .casdoor_authorize import CasdoorAuthorizeOptions, build_casdoor_authorize_payload
from . import casdoor_route_adapter
from .casdoor_state import consume_casdoor_state, issue_casdoor_state
from . import casdoor_user_sync
from .session_token import issue_hxops_access_token
from .user_resolver import resolve_hxops_user
@@ -15,6 +18,11 @@ __all__ = [
'HxopsLoginService',
'LoginResult',
'casdoor_user_sync',
'CasdoorAuthorizeOptions',
'build_casdoor_authorize_payload',
'casdoor_route_adapter',
'consume_casdoor_state',
'issue_hxops_access_token',
'issue_casdoor_state',
'resolve_hxops_user',
]
@@ -0,0 +1,105 @@
"""
backend/app/services/auth/hxops/casdoor_authorize.py
用途:组装 HXOPS 跳转 Casdoor 的 OAuth 授权地址及其 state 响应。
依赖:Flask 配置、Casdoor OIDC discovery、Casdoor state 服务。
逻辑:路由传入可选参数,本模块选择默认值、处理企微 provider 规则并返回原有响应字段。
"""
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from typing import Any
from urllib.parse import quote
from flask import current_app
from app.core.errors import AppError
from .casdoor_state import issue_casdoor_state
MetadataOperation = Callable[[], Mapping[str, Any]]
StateOperation = Callable[[str], str]
@dataclass(frozen=True)
class CasdoorAuthorizeOptions:
"""授权地址构造所需的浏览器可选参数,不包含任何 client_secret。"""
redirect_uri: str | None = None
provider_hint: str | None = None
default_provider: str | None = None
silent_signin: str | None = None
def _clean_text(value: object) -> str | None:
"""将 query/config 值归一为去空白字符串,空值统一为 None。"""
text = str(value or '').strip()
return text or None
def _is_truthy(value: object) -> bool:
"""识别现有接口支持的 1/true/yes 静默登录显式开关。"""
return (_clean_text(value) or '').lower() in {'1', 'true', 'yes'}
def build_casdoor_authorize_payload(
options: CasdoorAuthorizeOptions,
*,
oidc_metadata: MetadataOperation | None = None,
issue_state: StateOperation = issue_casdoor_state,
) -> dict[str, str]:
"""
依据 Casdoor discovery 与 HXOPS 配置构造授权地址,保持现有 response 字段和参数规则。
Args:
options: redirect_uri、provider_hint、default_provider 与 silent_signin 的可选浏览器输入。
oidc_metadata: 可选 discovery 读取函数,路由和测试可注入既有兼容代理。
issue_state: 可选 state 签发函数,供路由兼容 monkeypatch 与单元测试注入。
Returns:
包含 ``url``、``state`` 与 ``redirect_uri`` 的原有扁平响应 payload。
Raises:
AppError: Casdoor 授权端点或 client/redirect 配置缺失时保持既有 500 错误契约。
"""
metadata = (oidc_metadata or _flask_oidc_metadata)()
authorize_endpoint = _clean_text(metadata.get('authorization_endpoint'))
if not authorize_endpoint:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Casdoor authorization endpoint missing', http_status=500)
client_id = _clean_text(current_app.config.get('CASDOOR_CLIENT_ID'))
redirect_uri = _clean_text(options.redirect_uri) or _clean_text(current_app.config.get('CASDOOR_REDIRECT_URI'))
scope = _clean_text(current_app.config.get('CASDOOR_SCOPE')) or 'openid profile email'
if not client_id or not redirect_uri:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Casdoor client config is incomplete', http_status=500)
default_provider = (_clean_text(options.default_provider) or '').lower()
provider_hint = _clean_text(options.provider_hint)
if not provider_hint and default_provider == 'wecom':
provider_hint = _clean_text(current_app.config.get('CASDOOR_WECOM_PROVIDER_HINT'))
silent_signin = _is_truthy(options.silent_signin)
if not silent_signin and default_provider == 'wecom':
silent_signin = bool(current_app.config.get('CASDOOR_WECOM_SILENT_SIGNIN'))
state = issue_state(redirect_uri)
url = (
f'{authorize_endpoint}?client_id={quote(client_id, safe="")}'
f'&response_type=code&redirect_uri={quote(redirect_uri, safe="")}'
f'&scope={quote(scope, safe="")}&state={quote(state, safe="")}'
)
if provider_hint:
url += f'&provider_hint={quote(provider_hint, safe="")}'
if silent_signin:
url += '&silentSignin=1'
return {'url': url, 'state': state, 'redirect_uri': redirect_uri}
def _flask_oidc_metadata() -> Mapping[str, Any]:
"""读取当前 Flask 配置对应的 Casdoor discovery 文档,供默认服务调用。"""
from app.services.auth.casdoor import get_casdoor_client
return get_casdoor_client().oidc_metadata()
@@ -0,0 +1,92 @@
"""
backend/app/services/auth/hxops/casdoor_route_adapter.py
用途:集中 HXOPS Casdoor 路由所需的默认操作与登录服务装配。
依赖:CasdoorClient、授权地址/state 服务、HxopsLoginService。
逻辑:api/user 保留历史私有替换点,本模块提供其默认实现及可注入的登录编排工厂。
"""
from __future__ import annotations
from collections.abc import Callable, Mapping
from typing import Any
from app.services.auth.casdoor import get_casdoor_client
from .casdoor_authorize import CasdoorAuthorizeOptions, build_casdoor_authorize_payload
from .casdoor_state import consume_casdoor_state, issue_casdoor_state
from .login_service import HxopsLoginService, TokenOperation, UserinfoOperation
AuditOperation = Callable[..., None]
MetadataOperation = Callable[[], Mapping[str, Any]]
StateOperation = Callable[[str], str]
def get_oidc_metadata() -> dict[str, Any]:
"""读取当前 HXOPS Casdoor Application 对应的 OIDC discovery 文档。"""
return get_casdoor_client().oidc_metadata()
def password_login(username: str, password: str) -> dict[str, Any]:
"""以 HXOPS 自己的 Casdoor Application 执行 password grant。"""
return get_casdoor_client().password_login(username, password).as_dict()
def authorization_code_login(code: str, redirect_uri: str) -> dict[str, Any]:
"""以 HXOPS 自己的 Casdoor Application 兑换 authorization code。"""
return get_casdoor_client().authorization_code_login(code, redirect_uri).as_dict()
def refresh_token(refresh_token_value: str) -> dict[str, Any]:
"""使用 Casdoor refresh token 获取新的 Casdoor token 集合。"""
return get_casdoor_client().refresh(refresh_token_value).as_dict()
def userinfo(access_token: str) -> dict[str, Any]:
"""读取 Casdoor userinfo,供登录编排在缺少可信 ID token 时回退。"""
return get_casdoor_client().userinfo(access_token)
def build_authorize_payload(
options: CasdoorAuthorizeOptions,
*,
oidc_metadata: MetadataOperation | None = None,
issue_state: StateOperation | None = None,
) -> dict[str, str]:
"""构造原有 Casdoor authorize-url 响应,并允许路由兼容层注入测试替身。"""
return build_casdoor_authorize_payload(
options,
oidc_metadata=oidc_metadata or get_oidc_metadata,
issue_state=issue_state or issue_casdoor_state,
)
def create_login_service(
*,
write_login_audit: AuditOperation | None,
password_operation: TokenOperation | None = None,
code_operation: TokenOperation | None = None,
refresh_operation: TokenOperation | None = None,
userinfo_operation: UserinfoOperation | None = None,
) -> HxopsLoginService:
"""
组装 HXOPS 登录服务;路由可注入旧私有替换点以维持测试和渐进迁移兼容。
Args:
write_login_audit: HXOPS 登录审计写入函数。
password_operation: 可选 password grant 实现,默认使用本模块操作。
code_operation: 可选 authorization code grant 实现,默认使用本模块操作。
refresh_operation: 可选 refresh grant 实现,默认使用本模块操作。
userinfo_operation: 可选 userinfo 实现,默认使用本模块操作。
Returns:
已配置 Casdoor 操作和审计回调的 HxopsLoginService。
"""
return HxopsLoginService(
password_login=password_operation or password_login,
authorization_code_login=code_operation or authorization_code_login,
refresh_token=refresh_operation or refresh_token,
userinfo=userinfo_operation or userinfo,
write_login_audit=write_login_audit,
)
@@ -0,0 +1,103 @@
"""
backend/app/services/auth/hxops/casdoor_state.py
用途:签发和校验 Casdoor 授权码登录的无状态 HMAC state。
依赖:标准库、Flask 配置;不依赖数据库和 HXOPS User。
逻辑:授权地址签发固定格式 state,回调校验签名和有效期后恢复已绑定的 redirect_uri。
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import time
import uuid
from typing import Callable
from flask import current_app
_STATE_PREFIX = 'hxops_casdoor_v1'
_STATE_TTL_SECONDS = 600
def issue_casdoor_state(
redirect_uri: str,
*,
secret: str | None = None,
now_timestamp: int | None = None,
nonce_factory: Callable[[], str] | None = None,
) -> str:
"""
签发绑定 callback redirect_uri 的短时 HMAC state,保持现有 state 格式不变。
Args:
redirect_uri: 已由调用方选择的 Casdoor 回调地址,原样写入签名 payload。
secret: 可选 HMAC 密钥,仅供测试或非 Flask 调用注入;默认使用 SECRET_KEY。
now_timestamp: 可选当前 Unix 秒数,用于确定性测试;默认读取系统时钟。
nonce_factory: 可选随机 nonce 生成器;默认生成 UUID4 hex。
Returns:
格式为 ``hxops_casdoor_v1.<payload>.<signature>`` 的 URL-safe state。
"""
now = int(time.time()) if now_timestamp is None else int(now_timestamp)
payload = {
'v': 1,
'exp': now + _STATE_TTL_SECONDS,
'nonce': (nonce_factory or (lambda: uuid.uuid4().hex))(),
'redirect_uri': redirect_uri,
}
payload_json = json.dumps(payload, separators=(',', ':'))
payload_b64 = base64.urlsafe_b64encode(payload_json.encode('utf-8')).decode('ascii').rstrip('=')
signing_secret = str(secret if secret is not None else current_app.config.get('SECRET_KEY') or '')
signature = hmac.new(signing_secret.encode('utf-8'), payload_b64.encode('ascii'), hashlib.sha256).digest()
signature_b64 = base64.urlsafe_b64encode(signature).decode('ascii').rstrip('=')
return f'{_STATE_PREFIX}.{payload_b64}.{signature_b64}'
def consume_casdoor_state(
state: str | None,
*,
secret: str | None = None,
now_timestamp: int | None = None,
) -> str | None:
"""
校验 Casdoor state 的版本、HMAC 签名和有效期,成功时返回其绑定的 redirect_uri。
Args:
state: Casdoor 回调带回的 state。
secret: 可选 HMAC 密钥,仅供测试或非 Flask 调用注入;默认使用 SECRET_KEY。
now_timestamp: 可选当前 Unix 秒数,用于确定性测试;默认读取系统时钟。
Returns:
已签名且未过期的 redirect_uri;任一校验失败时返回 None,调用方映射为既有验证错误。
"""
if not state:
return None
try:
prefix, payload_b64, signature_b64 = state.split('.')
if prefix != _STATE_PREFIX:
return None
signing_secret = str(secret if secret is not None else current_app.config.get('SECRET_KEY') or '')
expected_signature = hmac.new(
signing_secret.encode('utf-8'),
payload_b64.encode('ascii'),
hashlib.sha256,
).digest()
expected_b64 = base64.urlsafe_b64encode(expected_signature).decode('ascii').rstrip('=')
if not hmac.compare_digest(expected_b64, signature_b64):
return None
padded_payload = payload_b64 + '=' * (-len(payload_b64) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded_payload.encode('ascii')).decode('utf-8'))
if not isinstance(payload, dict) or payload.get('v') != 1:
return None
expires_at = int(payload.get('exp') or 0)
except (TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError):
return None
now = int(time.time()) if now_timestamp is None else int(now_timestamp)
if expires_at <= now:
return None
redirect_uri = payload.get('redirect_uri')
return str(redirect_uri).strip() or None
@@ -134,12 +134,13 @@ def build_user_profile_payload(
*,
username: str,
email: str,
employee_id: str | None = None,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor 用户资料字段,不包含任何密码。"""
"""组装 Casdoor 用户资料字段,并将 HXOPS 工号写入 Casdoor 自定义属性。"""
payload: dict[str, Any] = {
'owner': casdoor_user_owner(),
'name': username,
@@ -152,6 +153,10 @@ def build_user_profile_payload(
department_value = clean_str(department)
if department_value:
payload['affiliation'] = department_value
employee_id_value = clean_str(employee_id)
if employee_id_value:
# Casdoor 将扩展资料放入 properties;应用需将 employee_id 配置为 userinfo/ID token 可见。
payload['properties'] = {'employee_id': employee_id_value}
return payload
@@ -160,6 +165,7 @@ def build_user_payload(
username: str,
password: str,
email: str,
employee_id: str | None = None,
real_name=None,
phone_number=None,
status='active',
@@ -168,6 +174,7 @@ def build_user_payload(
"""组装 Casdoor add-user 请求体,并只在创建场景附加明文密码。"""
payload = build_user_profile_payload(
username=username,
employee_id=employee_id,
email=email,
real_name=real_name,
phone_number=phone_number,
@@ -250,6 +257,7 @@ def sync_create_user(
username: str,
password: str,
email: str,
employee_id: str | None = None,
real_name=None,
phone_number=None,
status='active',
@@ -262,6 +270,7 @@ def sync_create_user(
payload = build_user_payload(
username=username,
password=password,
employee_id=employee_id,
email=email,
real_name=real_name,
phone_number=phone_number,
@@ -306,6 +315,7 @@ def sync_update_user(
sync_create_user(
username=user.username,
password=new_password,
employee_id=user.employee_id,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
@@ -1,9 +1,9 @@
"""
backend/app/services/auth/hxops/user_resolver.py
用途:将统一 AuthIdentity 映射为 HXOPS 本地 User。
用途:将统一 AuthIdentity 按工号映射为 HXOPS 本地 User。
依赖:Flask 日志、SQLAlchemy session、User、AuthIdentity。
逻辑:当前阶段保持原用户名优先、邮箱回退规则,并统一检查本地用户状态。
逻辑:Casdoor 工号优先;用户名作为当前“用户名即工号”的过渡兼容,不使用邮箱或手机号。
"""
from __future__ import annotations
@@ -26,26 +26,53 @@ class HxopsIdentityMappingError(Exception):
def resolve_hxops_user(identity: AuthIdentity) -> User:
"""
按现有规则将认证身份映射到 HXOPS 用户。
按工号优先规则将认证身份映射到 HXOPS 用户。
核心逻辑:优先使用 Casdoor employee_id;若其缺失,则将当前用户名作为工号
查找本地 employee_id,最后才按 username 兼容历史数据。邮箱和手机号不参与认证
匹配。若工号与用户名分别命中不同用户,拒绝登录以防错误账号关联。
Args:
identity: 已验证 Casdoor issuer/subject 的统一身份。
identity: 已验证 Casdoor issuer/subject 的统一身份;employee_id 是首选匹配键。
Returns:
状态为 active 的 HXOPS User。
Raises:
HxopsIdentityMappingError: 用户未同步到 HXOPS 或账号已禁用。
HxopsIdentityMappingError: 用户未同步、身份字段冲突或账号已禁用。
"""
current_app.logger.info(
'[casdoor_login] identity username=%s email=%s subject=%s',
'[casdoor_login] identity employee_id=%s username=%s subject=%s',
identity.employee_id,
identity.username,
identity.email,
identity.subject,
)
user = db.session.query(User).filter_by(username=identity.username).first()
if user is None and identity.email:
user = db.session.query(User).filter_by(email=identity.email).first()
# [STEP 1] 工号是当前产品用户的主映射键;Casdoor 未提供时用户名即工号。
employee_id = str(identity.employee_id or identity.username or '').strip()
employee_user = None
if employee_id:
employee_user = db.session.query(User).filter_by(employee_id=employee_id).first()
# [STEP 2] username 仅保留给尚未补齐 employee_id 的历史本地账号。
username_user = db.session.query(User).filter_by(username=identity.username).first()
if employee_user is not None and username_user is not None and employee_user.id != username_user.id:
current_app.logger.warning(
'[casdoor_login] identity_mapping_conflict employee_id=%s employee_user_id=%s '
'username=%s username_user_id=%s subject=%s',
employee_id,
employee_user.id,
identity.username,
username_user.id,
identity.subject,
)
raise HxopsIdentityMappingError(
'Casdoor employee ID and username map to different local accounts. Please contact admin.',
code='CASDOOR_IDENTITY_CONFLICT',
status=403,
)
user = employee_user or username_user
if user is None:
raise HxopsIdentityMappingError(
'No local user matched Casdoor identity. Please contact admin to provision account.',
@@ -0,0 +1,40 @@
"""Add linked_services table for admin-configured peer service entries.
Revision ID: e5f7a9b1c3d4
Revises: d4e6f8a0b2c3
Create Date: 2026-07-29 11:50:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'e5f7a9b1c3d4'
down_revision = 'd4e6f8a0b2c3'
branch_labels = None
depends_on = None
def upgrade():
"""创建关联服务表,供管理台配置名称与 URL。"""
op.create_table(
'linked_services',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('url', sa.String(length=500), nullable=False),
sa.Column('is_enabled', sa.Boolean(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_linked_services_is_enabled', 'linked_services', ['is_enabled'])
op.create_index('ix_linked_services_sort_order', 'linked_services', ['sort_order'])
def downgrade():
"""删除关联服务表。"""
op.drop_index('ix_linked_services_sort_order', table_name='linked_services')
op.drop_index('ix_linked_services_is_enabled', table_name='linked_services')
op.drop_table('linked_services')
@@ -67,6 +67,7 @@ def test_admin_create_user_syncs_casdoor(client, admin_headers, monkeypatch):
assert casdoor_calls['payload']['email'] == 'casdoor_new@example.com'
assert casdoor_calls['payload']['displayName'] == 'Casdoor User'
assert casdoor_calls['payload']['phone'] == '13800000099'
assert casdoor_calls['payload']['properties'] == {'employee_id': 'EMP-CAS-001'}
assert casdoor_calls['payload']['isForbidden'] is False
user = db.session.query(User).filter_by(username='casdoor_new').first()
@@ -256,13 +257,14 @@ def test_admin_update_user_provisions_missing_casdoor_user_with_password(client,
client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret'
client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX'
casdoor_calls = {'update_user': 0, 'add_user': 0, 'set_password': 0}
casdoor_calls = {'update_user': 0, 'add_user': 0, 'set_password': 0, 'add_payload': None}
def fake_update_user(_payload):
casdoor_calls['update_user'] += 1
def fake_add_user(_payload):
def fake_add_user(payload):
casdoor_calls['add_user'] += 1
casdoor_calls['add_payload'] = payload
def fake_set_password(_owner, _name, _old, _new):
casdoor_calls['set_password'] += 1
@@ -278,7 +280,10 @@ def test_admin_update_user_provisions_missing_casdoor_user_with_password(client,
headers=admin_headers,
)
assert res.status_code == 200
assert casdoor_calls == {'update_user': 0, 'add_user': 1, 'set_password': 1}
assert casdoor_calls['update_user'] == 0
assert casdoor_calls['add_user'] == 1
assert casdoor_calls['set_password'] == 1
assert casdoor_calls['add_payload']['properties'] == {'employee_id': user.employee_id}
db.session.refresh(user)
assert user.real_name == 'Legacy Updated'
+12
View File
@@ -82,12 +82,14 @@ def test_identity_from_claims_validates_issuer_and_normalizes_fields():
'iss': 'https://casdoor.test/',
'sub': 'subject-1',
'preferred_username': 'alice',
'employeeId': 'E1001',
'displayName': 'Alice Zhang',
'email': 'alice@example.com',
'affiliation': 'IT',
}, expected_issuer='https://casdoor.test')
assert identity.username == 'alice'
assert identity.display_name == 'Alice Zhang'
assert identity.employee_id == 'E1001'
assert identity.department == 'IT'
with pytest.raises(IdentityValidationError):
identity_from_claims({
@@ -107,6 +109,16 @@ def test_identity_from_claims_uses_configured_issuer_when_userinfo_omits_iss():
assert identity.subject == 'subject-1'
def test_identity_from_claims_reads_employee_id_from_casdoor_properties():
"""Casdoor 将自定义工号放在 properties 时,公共解析器仍输出 employee_id。"""
identity = identity_from_claims({
'sub': 'subject-1',
'preferred_username': '26040006',
'properties': {'employee_id': '26040006'},
}, expected_issuer='https://casdoor.test')
assert identity.employee_id == '26040006'
def test_casdoor_config_repr_does_not_expose_secret(app):
"""配置对象可诊断但不得在 repr 中泄漏 Casdoor client_secret。"""
app.config.update(
+10 -1
View File
@@ -20,7 +20,13 @@ from app.models import User
@pytest.fixture
def casdoor_user(app):
"""创建能被 Casdoor userinfo 映射的 active HXOPS 用户。"""
user = User(username='casdoor-session', email='casdoor-session@example.com', role='user', status='active')
user = User(
username='casdoor-session',
employee_id='casdoor-session',
email='casdoor-session@example.com',
role='user',
status='active',
)
db.session.add(user)
db.session.commit()
return user
@@ -44,6 +50,7 @@ def test_password_login_returns_hxops_api_session(client, app, casdoor_user, mon
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
'iss': 'https://casdoor.example.com',
'sub': 'casdoor-subject-session',
'employee_id': casdoor_user.employee_id,
'preferred_username': casdoor_user.username,
'email': casdoor_user.email,
})
@@ -89,6 +96,7 @@ def test_authorization_code_login_returns_hxops_api_session(client, app, casdoor
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
'iss': 'https://casdoor.example.com',
'sub': 'casdoor-subject-code-session',
'employee_id': casdoor_user.employee_id,
'preferred_username': casdoor_user.username,
'email': casdoor_user.email,
})
@@ -134,6 +142,7 @@ def test_refresh_returns_new_hxops_api_session(client, app, casdoor_user, monkey
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
'iss': 'https://casdoor.example.com',
'sub': 'casdoor-subject-session',
'employee_id': casdoor_user.employee_id,
'preferred_username': casdoor_user.username,
'email': casdoor_user.email,
})
+115 -1
View File
@@ -1,6 +1,17 @@
"""Casdoor authorize URL: provider_hint and WeCom defaults."""
"""
backend/tests/test_casdoor_authorize_url.py
用途:验证 Casdoor 授权地址的 provider、静默登录、编码和配置失败契约。
依赖:user API 兼容代理、HXOPS Casdoor 授权地址服务。
逻辑:路由测试保留历史 monkeypatch 入口,服务测试锁定可复制的授权地址组装规则。
"""
import pytest
from app.api import user as user_api
from app.core.errors import AppError
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions, build_casdoor_authorize_payload
from app.services.auth.hxops.casdoor_route_adapter import build_authorize_payload, create_login_service
def test_casdoor_authorize_url_wecom_defaults(client, app, monkeypatch):
@@ -61,3 +72,106 @@ def test_casdoor_authorize_url_explicit_provider_hint(client, app, monkeypatch):
url = res.get_json()['url']
assert 'provider_hint=from_query' in url
assert 'silentSignin' not in url
def test_authorize_service_encodes_values_and_honors_explicit_silent_signin(app):
"""授权地址必须编码 redirect/scope/provider/state,且 query 显式静默开关优先于默认 provider。"""
app.config.update(
CASDOOR_CLIENT_ID='client id',
CASDOOR_REDIRECT_URI='https://fallback.example.com/callback',
CASDOOR_SCOPE='openid profile email',
CASDOOR_WECOM_SILENT_SIGNIN=False,
)
payload = build_casdoor_authorize_payload(
CasdoorAuthorizeOptions(
redirect_uri='https://hxops.example.com/callback?source=admin panel',
provider_hint='wecom provider',
silent_signin='yes',
),
oidc_metadata=lambda: {'authorization_endpoint': 'https://casdoor.example.com/authorize'},
issue_state=lambda redirect_uri: f'state for {redirect_uri}',
)
assert payload['redirect_uri'] == 'https://hxops.example.com/callback?source=admin panel'
assert 'client_id=client%20id' in payload['url']
assert 'redirect_uri=https%3A%2F%2Fhxops.example.com%2Fcallback%3Fsource%3Dadmin%20panel' in payload['url']
assert 'provider_hint=wecom%20provider' in payload['url']
assert 'state=state%20for%20https%3A%2F%2Fhxops.example.com%2Fcallback%3Fsource%3Dadmin%20panel' in payload['url']
assert payload['url'].endswith('&silentSignin=1')
@pytest.mark.parametrize(
('metadata', 'client_id', 'redirect_uri', 'message'),
[
({}, 'client', 'https://hxops.example.com/callback', 'Casdoor authorization endpoint missing'),
({'authorization_endpoint': 'https://casdoor.example.com/authorize'}, '', 'https://hxops.example.com/callback', 'Casdoor client config is incomplete'),
({'authorization_endpoint': 'https://casdoor.example.com/authorize'}, 'client', '', 'Casdoor client config is incomplete'),
],
)
def test_authorize_service_rejects_missing_required_config(app, metadata, client_id, redirect_uri, message):
"""缺少 discovery endpoint、client_id 或 callback 时维持既有稳定 AppError。"""
app.config.update(CASDOOR_CLIENT_ID=client_id, CASDOOR_REDIRECT_URI=redirect_uri)
with pytest.raises(AppError) as captured:
build_casdoor_authorize_payload(
CasdoorAuthorizeOptions(),
oidc_metadata=lambda: metadata,
issue_state=lambda _: 'state',
)
assert captured.value.code == 'SYSTEM.INTERNAL_ERROR'
assert captured.value.message == message
def test_route_adapter_passes_compatibility_operations_to_authorize_service(app):
"""路由适配器必须透传路由层的 discovery/state 替身,避免改变历史 monkeypatch 契约。"""
app.config.update(
CASDOOR_CLIENT_ID='client',
CASDOOR_REDIRECT_URI='https://hxops.example.com/callback',
)
seen = {}
def metadata():
"""提供可断言的 discovery 数据,验证适配器没有绕过注入操作。"""
seen['metadata'] = True
return {'authorization_endpoint': 'https://casdoor.example.com/authorize'}
def issue_state(redirect_uri):
"""记录 state 绑定的回调地址,并返回固定 state。"""
seen['redirect_uri'] = redirect_uri
return 'compatibility-state'
payload = build_authorize_payload(
CasdoorAuthorizeOptions(),
oidc_metadata=metadata,
issue_state=issue_state,
)
assert seen == {
'metadata': True,
'redirect_uri': 'https://hxops.example.com/callback',
}
assert 'state=compatibility-state' in payload['url']
def test_route_adapter_injects_legacy_login_operations():
"""登录服务工厂必须采用传入操作,确保路由迁移期间旧替身点仍然有效。"""
password_operation = lambda username, password: {}
code_operation = lambda code, redirect_uri: {}
refresh_operation = lambda refresh_token: {}
userinfo_operation = lambda access_token: {}
audit_operation = lambda *args, **kwargs: None
service = create_login_service(
write_login_audit=audit_operation,
password_operation=password_operation,
code_operation=code_operation,
refresh_operation=refresh_operation,
userinfo_operation=userinfo_operation,
)
assert service._password_login is password_operation
assert service._authorization_code_login is code_operation
assert service._refresh_token is refresh_operation
assert service._userinfo is userinfo_operation
assert service._write_login_audit is audit_operation
+53
View File
@@ -0,0 +1,53 @@
"""
backend/tests/test_casdoor_state.py
用途:验证 Casdoor 授权码回调 state 的格式兼容、签名完整性和有效期边界。
依赖:HXOPS Casdoor state 服务;不访问 Flask 路由、数据库或 Casdoor。
逻辑:固定密钥和时钟验证 state 可跨实例校验,篡改或过期必须安全失败。
"""
from __future__ import annotations
from app.services.auth.hxops.casdoor_state import consume_casdoor_state, issue_casdoor_state
def test_casdoor_state_preserves_existing_wire_format_and_redirect_uri():
"""新服务签发的 state 保持 v1 前缀,且在同一密钥下可恢复原 redirect_uri。"""
state = issue_casdoor_state(
'https://hxops.example.com/auth/callback',
secret='state-test-secret',
now_timestamp=1_700_000_000,
nonce_factory=lambda: 'fixed-nonce',
)
assert state.startswith('hxops_casdoor_v1.')
assert consume_casdoor_state(
state,
secret='state-test-secret',
now_timestamp=1_700_000_001,
) == 'https://hxops.example.com/auth/callback'
def test_casdoor_state_rejects_tampered_signature():
"""攻击者篡改 payload 或签名后,服务必须拒绝恢复 callback 地址。"""
state = issue_casdoor_state(
'https://hxops.example.com/auth/callback',
secret='state-test-secret',
now_timestamp=1_700_000_000,
)
prefix, payload, signature = state.split('.')
tampered = f'{prefix}.{payload}.{signature[:-1]}x'
assert consume_casdoor_state(tampered, secret='state-test-secret', now_timestamp=1_700_000_001) is None
def test_casdoor_state_rejects_expired_or_wrong_secret():
"""过期 state 或不同实例密钥均不得通过,保持 callback 的 CSRF 防护。"""
state = issue_casdoor_state(
'https://hxops.example.com/auth/callback',
secret='state-test-secret',
now_timestamp=1_700_000_000,
)
assert consume_casdoor_state(state, secret='wrong-secret', now_timestamp=1_700_000_001) is None
assert consume_casdoor_state(state, secret='state-test-secret', now_timestamp=1_700_000_600) is None
+109
View File
@@ -0,0 +1,109 @@
"""
backend/tests/test_hxops_user_resolver.py
用途:验证 Casdoor 身份到 HXOPS 用户的工号优先映射规则。
依赖:Flask 测试应用、User、AuthIdentity、HXOPS 用户解析器。
逻辑:覆盖工号优先、用户名兼容、邮箱手机号不匹配和双键冲突拒绝。
"""
from __future__ import annotations
import pytest
from app import db
from app.models import User
from app.services.auth.common import AuthIdentity
from app.services.auth.hxops.user_resolver import HxopsIdentityMappingError, resolve_hxops_user
def _identity(*, employee_id: str | None, username: str, email: str | None = None, phone_number: str | None = None) -> AuthIdentity:
"""构造最小 Casdoor 统一身份,供映射规则测试复用。"""
return AuthIdentity(
issuer='https://casdoor.example.com',
subject='casdoor-subject',
employee_id=employee_id,
username=username,
email=email,
phone_number=phone_number,
)
def _user(*, username: str, employee_id: str | None, email: str, phone_number: str | None = None) -> User:
"""创建 active HXOPS 用户,确保每个测试自行声明本地身份资料。"""
user = User(
username=username,
employee_id=employee_id,
email=email,
phone_number=phone_number,
role='user',
status='active',
)
db.session.add(user)
db.session.commit()
return user
def test_resolver_prefers_casdoor_employee_id_over_username(app):
"""Casdoor 同时提供工号和用户名时,优先以 employee_id 命中 HXOPS 用户。"""
with app.app_context():
expected = _user(username='26040006', employee_id='26040006', email='employee@example.com')
user = resolve_hxops_user(_identity(employee_id='26040006', username='casdoor-display-name'))
assert user.id == expected.id
def test_resolver_uses_username_as_employee_id_compatibility(app):
"""Casdoor 未返回 employee_id 时,当前用户名即工号可匹配本地 employee_id。"""
with app.app_context():
expected = _user(username='legacy-local-name', employee_id='26040008', email='compat@example.com')
user = resolve_hxops_user(_identity(employee_id=None, username='26040008'))
assert user.id == expected.id
def test_resolver_does_not_match_email_or_phone(app):
"""邮箱和手机号仅是资料字段,不能作为 Casdoor 登录身份回退键。"""
with app.app_context():
_user(
username='other-employee',
employee_id='26040009',
email='shared@example.com',
phone_number='13800000009',
)
with pytest.raises(HxopsIdentityMappingError) as captured:
resolve_hxops_user(_identity(
employee_id='missing-employee',
username='missing-username',
email='shared@example.com',
phone_number='13800000009',
))
assert captured.value.code == 'CASDOOR_USER_NOT_FOUND'
def test_resolver_rejects_conflicting_employee_id_and_username(app):
"""工号与用户名指向不同本地用户时必须拒绝,避免把 Casdoor 身份关联到错误账号。"""
with app.app_context():
_user(username='26040010', employee_id='26040010', email='employee-conflict@example.com')
_user(username='legacy-conflict', employee_id='26040011', email='username-conflict@example.com')
with pytest.raises(HxopsIdentityMappingError) as captured:
resolve_hxops_user(_identity(employee_id='26040010', username='legacy-conflict'))
assert captured.value.code == 'CASDOOR_IDENTITY_CONFLICT'
def test_resolver_rejects_disabled_employee(app):
"""工号命中 rejected/disabled 用户时保持既有 active 状态校验。"""
with app.app_context():
user = _user(username='26040012', employee_id='26040012', email='disabled@example.com')
user.status = 'rejected'
db.session.commit()
with pytest.raises(HxopsIdentityMappingError) as captured:
resolve_hxops_user(_identity(employee_id='26040012', username='26040012'))
assert captured.value.code == 'ACCOUNT_DISABLED'
+1
View File
@@ -467,5 +467,6 @@
- 本期只建设认证、跳转和共享身份契约,不处理企业微信登录、拒绝用户清理、跨服务业务权限同步和全局单点退出。
- HXOPS 已按无状态短时 JWT 方案移除 Redis 一次性票据接口;平级服务侧按 [features/auth/hxops-peer-service-sso.md](features/auth/hxops-peer-service-sso.md) 实现独立登录、JWT 验签和本地 Session。
- 认证代码先完成结构重构并提取可复制公共部分,不制作依赖包;重构不得改变现有认证协议、接口路径、响应格式、JWT 声明/有效期或数据库结构。
- Casdoor 登录到 HXOPS 本地用户以 `employee_id`(工号)为主映射键;当前用户名等于工号,仅保留用户名到本地工号/用户名的兼容回退。邮箱和手机号不参与认证映射;工号与用户名命中不同本地用户时拒绝登录。
---
@@ -548,6 +548,8 @@ backend/app/services/auth/
casdoor_service.py # 历史调用兼容门面,不承载新的核心实现
```
`hxops/casdoor_route_adapter.py` 是 HXOPS 路由与认证服务之间的最后一层装配适配器:集中默认的 OIDC discovery、password/code/refresh/userinfo 操作、授权地址构造和 `HxopsLoginService` 工厂。`api/user.py` 只保留同名的兼容代理及 HTTP 参数/响应处理,因此既有路由调用与测试替身点仍有效;平级服务不需要复制该适配器,应直接使用 `common/`、`casdoor/` 并按自身框架装配登录服务。
平级服务实现自己的登录页时,可以复制 `common/` 与 `casdoor/`,然后按自身框架替换配置适配器、用户映射和 Session 创建。不得复制 HXOPS 的 `User` 模型、角色权限或本地 API JWT 签发逻辑。
本阶段结构重构保持以下外部契约不变:
@@ -560,6 +562,41 @@ backend/app/services/auth/
Casdoor discovery 文档由配置对应的进程内客户端缓存 10 分钟;配置变化时自动创建新客户端。用户创建、管理员改密和 IdP 缺失用户补建集中在 `hxops/casdoor_user_sync.py`,旧入口继续通过兼容门面委托,以便分阶段迁移调用方。
### 18.4 HXOPS 用户映射规则(工号主键)
HXOPS 当前用户名等于工号,但认证映射必须以独立的 `employee_id` 为主,避免将展示用户名固化为跨系统身份协议:
1. Casdoor claims 提供 `employee_id` 或 `employeeId` 时,按其匹配 `users.employee_id`。
2. Casdoor 未提供工号时,以 `preferred_username` 先匹配 `users.employee_id`,兼容当前“用户名即工号”的数据。
3. 若仍未命中,才按 `users.username` 兼容尚未补齐 `employee_id` 的历史数据。
4. 邮箱和手机号仅用于用户资料,不参与 Casdoor、HXOPS 或平级服务登录映射。
5. 工号命中用户与用户名命中用户不一致时,拒绝登录并返回 `CASDOOR_IDENTITY_CONFLICT`,不得自动选择任一账号。
平级服务应沿用同一规则完成首次本地账号映射;完成映射后仍以 Casdoor `(issuer, subject)` 作为跨服务稳定身份键。
HXOPS 在管理端创建用户或为缺失 IdP 账号补建用户时,会把本地 `employee_id` 写入 Casdoor 用户 `properties.employee_id`。Casdoor 管理员必须将该自定义属性配置为 HXOPS 及平级服务对应 Application 的 userinfo/ID Token 可返回 claim;本项目同时兼容 Casdoor 把它展平为顶层 `employee_id` 或 `employeeId`。未完成 Casdoor 控制台配置时,登录会走用户名兼容回退,无法保证工号 claim 可用。
### 18.5 Casdoor 授权码 state 结构
HXOPS 的 Casdoor 授权码登录 state 已从路由层抽至 `services/auth/hxops/casdoor_state.py`。它是独立于平级服务 SSO state 的 HXOPS 登录 callback 防护,保持原有无状态格式和 10 分钟有效期:
```text
hxops_casdoor_v1.<base64url-json-payload>.<hmac-sha256-signature>
```
payload 只包含版本、过期时间、随机 nonce 和已签名的 `redirect_uri`。回调必须校验版本、HMAC 与过期时间,失败仍返回既有的 `Invalid or expired Casdoor state`。该 state 不依赖 Redis,不是 SSO assertion,也不携带用户身份或 Casdoor token。
### 18.6 Casdoor 授权地址构造
`services/auth/hxops/casdoor_authorize.py` 统一构造 `/api/user/casdoor/authorize-url` 的返回值,路由只读取 query 参数并返回原有 `{ url, state, redirect_uri }`。该服务负责:
- 从 Casdoor OIDC discovery 读取 `authorization_endpoint`。
- 校验当前服务的 `client_id` 与 callback `redirect_uri`。
- URL 编码 OAuth 参数和 state。
- 保留已有 `default_provider=wecom`、`provider_hint`、`silent_signin` / `silentSignin=1` 兼容行为。
这里的 `wecom` 是 Casdoor 已配置 provider 的授权地址参数,不增加 HXOPS 企业微信登录链路;本期认证范围仍不改造企业微信登录。
`AUTH_JWT_ISSUER` 必须填写 `CASDOOR_BASE_URL/.well-known/openid-configuration` 返回的 `issuer`,不能填写 HXOPS 前端/后端地址,也不能简单使用 Casdoor 内网访问地址。HXOPS 会对 ID token/userinfo 中的 `iss` 做严格匹配;配置不一致时返回 `AUTH.CASDOOR_IDENTITY_INVALID`。
## 19. 测试方案
+6
View File
@@ -570,7 +570,13 @@
| HXOPS Casdoor 表单登录 | 已实现 | 用户只在 HXOPS 登录页输入用户名/密码,后端调用 Casdoor password-login,不跳转 Casdoor 页面。 |
| HXOPS API 会话 JWT | 已实现 | Casdoor 校验成功后由 HXOPS 签发本站 API JWT,并保留 Casdoor 稳定身份声明。 |
| 认证公共结构第一阶段重构 | 已实现 | 已拆分 `common/casdoor/hxops` 三层;平级服务可直接复制无业务模型依赖的 `common` 与 `casdoor`,旧入口由兼容门面保持不变。 |
| HXOPS 工号主认证映射 | 已实现 | Casdoor `employee_id/employeeId` 优先匹配本地工号;用户名仅兼容回退,不使用邮箱或手机号;双键冲突拒绝登录。 |
| Casdoor 工号属性同步 | 已实现 | HXOPS 创建或补建用户时写入 `properties.employee_id`;需在 Casdoor Application 配置该属性进入 userinfo/ID Token。 |
| Casdoor 授权码 state 服务化 | 已实现 | `hxops_casdoor_v1` HMAC state 的签发和校验已移至认证服务层;格式、10 分钟有效期和接口保持不变。 |
| Casdoor 授权地址服务化 | 已实现 | OIDC discovery、OAuth URL 编码和既有 provider/silentSignin 规则已从路由抽至认证服务层;接口响应保持不变。 |
| Casdoor 路由装配适配器 | 已实现 | `casdoor_route_adapter.py` 集中路由所需的默认 Casdoor 操作和登录服务工厂;`api/user.py` 只保留兼容代理、参数校验与响应,历史替身点和接口契约不变。 |
| 平级服务注册表与入口 | 已实现 | 服务端应用目录使用 `audience/callback_url`,工作台、Chat、Admin 和移动端复用统一入口组件。 |
| 关联服务管理台配置 | 已实现 | 管理台「关联服务」可配置名称与 URL;启用后自动出现在 Chat/工作台侧栏底部;若 URL/名称命中 SSO 注册表则走无感登录 launch。 |
| HXOPS 登录续跳 | 已实现 | 未登录授权请求保存到 sessionStorage,登录成功后自动恢复 assertion 签发流程。 |
| RS256 专用短时 JWT 签发 | 已实现 | `/api/sso/apps/{app_key}/assertions` 按目标服务绑定 `aud`,配置有效期限制为 10-60 秒。 |
| HXOPS JWKS 发布与轮换 | 已实现 | `/.well-known/jwks.json` 发布当前 RSA 公钥,并可在换钥窗口继续发布旧验证公钥。 |
+5
View File
@@ -1150,5 +1150,10 @@ Dify
- HXOPS 前端保留登录续跳和统一平级服务入口;平级服务可提供“使用 HXOPS 登录”及返回 HXOPS 的普通 HTTPS 链接。
- HXOPS 已移除 `/tickets`、`/api/sso/exchange` 和 Redis 票据存储,统一使用 assertion/JWKS 协议。平级服务独立登录、验签和本地 Session 仍在对应代码库实现。完整接口、密钥轮换、安全约束、测试与验收见 [features/auth/hxops-peer-service-sso.md](features/auth/hxops-peer-service-sso.md)。
- 认证代码第一阶段结构重构已落地:`services/auth/common` 定义无框架稳定身份,`services/auth/casdoor` 封装可复制的配置、OAuth/OIDC 客户端、claims 与错误映射,`services/auth/hxops` 承载用户映射、本地 JWT、登录编排及用户同步;`casdoor_service.py` 仅保留旧调用兼容门面。本阶段不改变协议、接口路径、响应格式、JWT 语义或数据库结构。
- HXOPS 本地用户映射以 Casdoor `employee_id/employeeId` 对应 `users.employee_id` 为第一优先级;当 Casdoor 尚未返回工号时,`preferred_username` 依次兼容 `users.employee_id` 与 `users.username`。邮箱和手机号不参与认证匹配;工号与用户名分别命中不同用户时返回 `CASDOOR_IDENTITY_CONFLICT`,避免静默错绑身份。
- HXOPS 创建或补建 Casdoor 用户时将工号写入 `properties.employee_id`;Casdoor Application 必须将该自定义属性暴露给 userinfo/ID Token。身份解析器同时兼容顶层 `employee_id`、`employeeId` 和 `properties.employee_id`,以支持不同 Casdoor claim 映射配置。
- Casdoor 授权码登录的 callback state 由 `services/auth/hxops/casdoor_state.py` 统一签发与校验,保持 `hxops_casdoor_v1` 的 HMAC 无状态格式和 10 分钟 TTL;路由仅保留兼容代理。该 state 不依赖 Redis,且与平级服务 assertion/state 协议隔离。
- Casdoor 授权地址构造已抽至 `services/auth/hxops/casdoor_authorize.py`,统一处理 OIDC discovery、callback/client 配置、OAuth URL 编码和既有 Casdoor WeCom provider 参数;`/api/user/casdoor/authorize-url` 的路径、请求参数及 `{ url, state, redirect_uri }` 响应保持不变。
- Casdoor 路由默认操作已收口到 `services/auth/hxops/casdoor_route_adapter.py`:统一装配 discovery、password/code/refresh/userinfo、授权地址和登录编排;`api/user.py` 仅保留兼容代理、请求校验和响应处理。适配器支持注入历史替身点,保证重构期间既有测试和外部契约不变。
---
+9 -2
View File
@@ -2,6 +2,8 @@
/**
* App.vue
* 根组件:主题初始化、全局消息弹窗、401 登出监听、html lang 与 i18n locale 同步。
* 依赖:useTheme、useGlobalMessageDialog、auth、linked-nav.store。
* 逻辑:已登录时预取关联服务侧栏入口,避免页面切换后入口后闪现。
*/
import { useI18n } from 'vue-i18n';
import { watch, onMounted, onBeforeUnmount } from 'vue';
@@ -11,6 +13,7 @@ import { useGlobalMessageDialog } from '@/shared/composables/useGlobalMessageDia
import { useRouter } from 'vue-router';
import { getAuthHeaders, logoutAuth } from '@/shared/utils/auth';
import { isPublicPath } from '@/shared/constants/routes';
import { useLinkedNavStore } from '@/features/sso/stores/linked-nav.store';
const router = useRouter();
const { locale, t } = useI18n();
@@ -64,18 +67,20 @@ watch(themePreference, (newTheme) => {
/**
* 处理接口返回未登录状态,提示用户重新登录并清理失效的本地登录信息。
* 核心逻辑:忽略可选的 SSO 应用目录请求;其余未授权请求统一展示易懂提示,再执行登出。
* 核心逻辑:忽略可选的关联服务/SSO 目录请求;其余未授权请求统一展示易懂提示,再执行登出。
* @param event - 包含请求地址和状态码的全局未授权事件。
*/
const onUnauthorized = (event: Event) => {
const url = String((event as CustomEvent<{ url?: string }>).detail?.url || '');
// 外部应用目录是可选导航能力,加载失败只能隐藏入口,不能清除有效 HXOPS 登录态。
// 侧栏入口目录是可选导航能力,加载失败只能隐藏入口,不能清除有效 HXOPS 登录态。
if (/\/api\/sso\/apps(?:\?|$)/.test(url)) return;
if (/\/api\/linked-services(?:\?|$)/.test(url)) return;
showMessageDialog('error', t('login.sessionExpiredHint'), t('login.sessionExpired'));
logoutAuth();
};
const onLogout = (event: Event) => {
useLinkedNavStore().reset();
const detail = (event as CustomEvent<{ remote?: boolean }>).detail;
if (detail?.remote) {
showMessageDialog('info', '您已在其他标签页退出登录');
@@ -94,6 +99,8 @@ onMounted(async () => {
const headers = getAuthHeaders();
if (Object.keys(headers).length > 0) {
// 尽早预取侧栏关联服务,避免进入 Chat/工作台后入口后加载闪现。
void useLinkedNavStore().ensureLoaded();
try {
const res = await fetch('/api/user/home', { headers });
if (res.ok) {
@@ -45,6 +45,9 @@ const WecomSettingsPage = () => import("@/features/admin/modules/wecom/pages/Wec
const WecomBindingsPage = () => import("@/features/admin/modules/wecom/pages/WecomBindingsPage.vue");
const WecomAuditsPage = () => import("@/features/admin/modules/wecom/pages/WecomAuditsPage.vue");
const LinkedServicesPage = () =>
import("@/features/admin/modules/linked-services/LinkedServicesPage.vue");
const ReportsPage = () =>
import("@/features/admin/modules/reports/ReportsPage.vue");
@@ -169,6 +172,16 @@ export const adminRoutes: RouteRecordRaw[] = [
title: "常用问题",
},
},
{
path: "linked-services",
name: "AdminLinkedServices",
component: LinkedServicesPage,
meta: {
requiresAdmin: true,
adminModule: "linked_services",
title: "关联服务",
},
},
{
path: "requests",
name: "AdminRequests",
+1
View File
@@ -58,6 +58,7 @@ export const config = {
announcements: true, // 公告管理
questions: true, // 常用问题
wecom: true, // 企业微信
linked_services: true, // 关联服务(侧栏跳转入口)
permissions: true, // 应用权限
platform_apps: true, // 平台应用说明
requests: true, // 审批权限
+12 -1
View File
@@ -1,12 +1,13 @@
/**
* features/admin/api/admin.api.ts
* 管理后台 HTTP API:用户、部门、Agent、权限、报表、企业微信、公告等。
* 管理后台 HTTP API:用户、部门、Agent、权限、报表、企业微信、公告、关联服务等。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import { requestJson } from '@/shared/api/client';
import type { AdminUserRow } from '../types/admin.types';
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
import type { PaginatedResult } from '@/shared/types/pagination.types';
import type { AdminLinkedServiceRow } from '../types/linked-service.types';
import type {
ApplicationReport,
ApplicationSortKey,
@@ -394,6 +395,16 @@ export const updateAnnouncement = (id: number, payload: Record<string, unknown>)
export const deleteAnnouncement = (id: number) =>
requestJson(`/api/admin/announcements/${id}`, { method: 'DELETE', ...auth() });
// Linked services(关联服务:侧栏跳转入口)
export const listLinkedServices = () =>
requestJson<AdminLinkedServiceRow[]>('/api/admin/linked-services', auth());
export const createLinkedService = (payload: Record<string, unknown>) =>
requestJson('/api/admin/linked-services', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
export const updateLinkedService = (id: number, payload: Record<string, unknown>) =>
requestJson(`/api/admin/linked-services/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
export const deleteLinkedService = (id: number) =>
requestJson(`/api/admin/linked-services/${id}`, { method: 'DELETE', ...auth() });
// Quick questions
export const listAdminQuickQuestions = () => requestJson<any[]>('/api/admin/quick-questions', auth());
export const saveAdminQuickQuestion = (url: string, method: string, payload: Record<string, unknown>) =>
@@ -11,7 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
import {
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow,
ScrollText,
ScrollText, ExternalLink,
} from 'lucide-vue-next';
import type { Component } from 'vue';
import { config } from '@/config';
@@ -35,6 +35,7 @@ const iconMap: Record<AdminModuleId, Component> = {
announcements: Megaphone,
questions: MessageCircleQuestion,
wecom: Link2,
linked_services: ExternalLink,
permissions: Users,
platform_apps: AppWindow,
procurement_contract: ScrollText,
@@ -15,7 +15,7 @@ export interface AdminModuleMeta {
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'platform_apps', 'procurement_contract', 'reports',
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'procurement_contract', 'reports',
]);
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
@@ -29,6 +29,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
{ id: 'announcements', routeName: 'AdminAnnouncements', path: 'announcements', labelKey: 'admin.nav.announcements', configKey: 'announcements' },
{ id: 'questions', routeName: 'AdminQuestions', path: 'questions', labelKey: 'admin.nav.questions', configKey: 'questions' },
{ id: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' },
{ id: 'linked_services', routeName: 'AdminLinkedServices', path: 'linked-services', labelKey: 'admin.nav.linkedServices', configKey: 'linked_services' },
{ id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' },
{ id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' },
{ id: 'procurement_contract', routeName: 'AdminProcurementContract', path: 'procurement-contract', labelKey: 'admin.nav.procurementContract', configKey: 'procurement_contract' },
@@ -0,0 +1,135 @@
/**
* features/admin/modules/linked-services/LinkedServicesPage.vue
* 关联服务管理独立页面:表格列表 + 新增/编辑弹窗。
* 依赖:useLinkedServicesAdmin、LinkedServiceFormModal、DeleteConfirmDialog。
* 逻辑:路由 /admin/linked-services;启用项自动出现在 Chat/工作台侧栏底部。
*/
<script setup lang="ts">
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Plus, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import LinkedServiceFormModal from './components/LinkedServiceFormModal.vue';
import { useLinkedServicesAdmin } from './composables/useLinkedServicesAdmin';
const { t } = useI18n();
const {
services,
form,
isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
openCreateModal,
openEditModal,
closeFormModal,
saveService,
toggleEnabled,
deleteServiceItem,
closeDeleteConfirm,
confirmDelete,
} = useLinkedServicesAdmin();
onMounted(() => {
void loadAll();
});
</script>
<template>
<section class="admin-table-section animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.linkedServices.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.linkedServices.subtitle') }}</p>
</div>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.linkedServices.add') }}</span>
</button>
</div>
<div class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.linkedServices.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.linkedServices.headers.url') }}</th>
<th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.linkedServices.headers.status') }}</th>
<th class="px-6 py-4 text-left text-xs w-24">{{ t('admin.linkedServices.headers.sortOrder') }}</th>
<th class="px-6 py-4 text-right text-xs w-40">{{ t('admin.linkedServices.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="services.length === 0">
<td colspan="5" class="px-6 admin-table-empty">{{ t('admin.linkedServices.empty') }}</td>
</tr>
<tr v-for="row in services" :key="row.id">
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary font-mono break-all">{{ row.url }}</td>
<td class="px-6 py-4">
<button
type="button"
class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium transition-colors"
:class="row.is_enabled
? 'bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
: 'bg-surface-soft text-muted hover:bg-surface'"
@click="toggleEnabled(row)"
>
{{ row.is_enabled ? t('admin.linkedServices.status.enabled') : t('admin.linkedServices.status.disabled') }}
</button>
</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.sort_order }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<button
type="button"
class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary"
:title="t('admin.edit')"
@click="openEditModal(row)"
>
<Edit class="w-4 h-4" />
</button>
<button
type="button"
class="p-2 rounded-lg text-muted hover:bg-red-50 hover:text-red-600"
:title="t('admin.delete')"
@click="deleteServiceItem(row.id)"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<LinkedServiceFormModal
:visible="showFormModal"
:form="form"
:is-saving="isSaving"
@close="closeFormModal"
@save="saveService"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@cancel="closeDeleteConfirm"
@confirm="confirmDelete"
/>
</section>
</template>
@@ -0,0 +1,70 @@
/**
* features/admin/modules/linked-services/components/LinkedServiceFormModal.vue
* 关联服务创建/编辑居中弹窗。
* 依赖:LinkedServiceFormState、admin 通用 modal 样式。
* 逻辑:LinkedServicesPage 打开本组件;提交时 emit save。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { LinkedServiceFormState } from '@/features/admin/types/linked-service.types';
defineProps<{
visible: boolean;
form: LinkedServiceFormState;
isSaving: boolean;
}>();
const emit = defineEmits<{
close: [];
save: [];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">
{{ form.id ? t('admin.linkedServices.edit') : t('admin.linkedServices.add') }}
</h3>
<p class="section-desc mt-1">{{ t('admin.linkedServices.formHint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.linkedServices.fields.name') }}</label>
<input
v-model="form.name"
type="text"
class="input-field text-sm"
:placeholder="t('admin.linkedServices.placeholders.name')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.linkedServices.fields.url') }}</label>
<input
v-model="form.url"
type="url"
class="input-field text-sm font-mono"
:placeholder="t('admin.linkedServices.placeholders.url')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.linkedServices.fields.sortOrder') }}</label>
<input v-model.number="form.sort_order" type="number" class="input-field text-sm" min="0" />
</div>
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="form.is_enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.linkedServices.fields.enabled') }}
</label>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : form.id ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,198 @@
/**
* features/admin/modules/linked-services/composables/useLinkedServicesAdmin.ts
* 关联服务管理:列表、新增/编辑弹窗、启用开关、删除。
* 依赖:admin.api、linked-service.types、linked-nav.store、useMessage。
* 逻辑:LinkedServicesPage 调用本 composable;保存/删除后刷新侧栏入口缓存。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
createLinkedService,
deleteLinkedService,
listLinkedServices,
updateLinkedService,
} from '@/features/admin/api/admin.api';
import { useLinkedNavStore } from '@/features/sso/stores/linked-nav.store';
import { useMessage } from '@/shared/composables/useMessage';
import {
createEmptyLinkedServiceForm,
linkedServiceRowToForm,
type AdminLinkedServiceRow,
type LinkedServiceFormState,
} from '@/features/admin/types/linked-service.types';
export function useLinkedServicesAdmin() {
const { t } = useI18n();
const msg = useMessage();
const linkedNav = useLinkedNavStore();
const services = ref<AdminLinkedServiceRow[]>([]);
const form = ref<LinkedServiceFormState>(createEmptyLinkedServiceForm());
const isLoading = ref(true);
const isSaving = ref(false);
const showFormModal = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null;
/**
* 拉取关联服务列表。
* @returns Promise<void>
*/
const loadServices = async (): Promise<void> => {
try {
services.value = await listLinkedServices();
} catch (e) {
console.error('Failed to load linked services', e);
services.value = [];
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
/**
* 页面初始化:加载列表并结束 loading。
* @returns Promise<void>
*/
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await loadServices();
isLoading.value = false;
};
/** 打开删除确认对话框。 */
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message;
deleteConfirmAction = action;
showDeleteConfirmDialog.value = true;
};
/** 关闭删除确认对话框。 */
const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false;
deleteConfirmAction = null;
};
/** 执行删除确认动作。 */
const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return;
try {
await deleteConfirmAction();
} finally {
closeDeleteConfirm();
}
};
/** 打开「新增关联服务」弹窗。 */
const openCreateModal = (): void => {
form.value = createEmptyLinkedServiceForm();
form.value.sort_order = services.value.length;
showFormModal.value = true;
};
/**
* 打开「编辑关联服务」弹窗。
* @param row - 待编辑行
*/
const openEditModal = (row: AdminLinkedServiceRow): void => {
form.value = linkedServiceRowToForm(row);
showFormModal.value = true;
};
/** 关闭表单弹窗。 */
const closeFormModal = (): void => {
showFormModal.value = false;
form.value = createEmptyLinkedServiceForm();
};
/**
* 保存关联服务:有 id 则更新,否则新建。
* 核心逻辑:校验名称与 URL → 调 API → 刷新列表。
*/
const saveService = async (): Promise<void> => {
if (!form.value.name.trim() || !form.value.url.trim()) {
msg.warning(t('admin.linkedServices.msg.fillAll'));
return;
}
isSaving.value = true;
try {
const payload = {
name: form.value.name.trim(),
url: form.value.url.trim(),
is_enabled: form.value.is_enabled,
sort_order: Number(form.value.sort_order || 0),
};
if (form.value.id) {
await updateLinkedService(form.value.id, payload);
} else {
await createLinkedService(payload);
}
closeFormModal();
await loadServices();
void linkedNav.refresh();
msg.success(t('admin.linkedServices.msg.saved'));
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
/**
* 切换启用状态并立即保存。
* @param row - 目标行
*/
const toggleEnabled = async (row: AdminLinkedServiceRow): Promise<void> => {
try {
await updateLinkedService(row.id, {
name: row.name,
url: row.url,
is_enabled: !row.is_enabled,
sort_order: row.sort_order,
});
await loadServices();
void linkedNav.refresh();
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
/**
* 删除指定关联服务。
* @param id - 主键
*/
const deleteServiceItem = (id: number): void => {
openDeleteConfirm(t('admin.linkedServices.confirmDelete'), async () => {
try {
await deleteLinkedService(id);
await loadServices();
void linkedNav.refresh();
msg.success(t('admin.linkedServices.msg.deleted'));
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
});
};
return {
services,
form,
isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
loadAll,
openCreateModal,
openEditModal,
closeFormModal,
saveService,
toggleEnabled,
deleteServiceItem,
closeDeleteConfirm,
confirmDelete,
};
}
@@ -14,6 +14,7 @@ export type AdminModuleId =
| 'announcements'
| 'questions'
| 'wecom'
| 'linked_services'
| 'permissions'
| 'requests'
| 'platform_apps'
@@ -0,0 +1,44 @@
/**
* features/admin/types/linked-service.types.ts
* 关联服务管理表单与行数据类型。
*/
export interface AdminLinkedServiceRow {
id: number;
name: string;
url: string;
is_enabled: boolean;
sort_order: number;
created_at?: string | null;
updated_at?: string | null;
}
export interface LinkedServiceFormState {
id: number | null;
name: string;
url: string;
is_enabled: boolean;
sort_order: number;
}
/** 创建空的关联服务表单。 */
export function createEmptyLinkedServiceForm(): LinkedServiceFormState {
return {
id: null,
name: '',
url: '',
is_enabled: true,
sort_order: 0,
};
}
/** 将列表行回填为编辑表单。 */
export function linkedServiceRowToForm(row: AdminLinkedServiceRow): LinkedServiceFormState {
return {
id: row.id,
name: row.name,
url: row.url,
is_enabled: Boolean(row.is_enabled),
sort_order: Number(row.sort_order || 0),
};
}
@@ -1,6 +1,8 @@
/**
* features/auth/composables/useLogin.ts
* 登录页编排层:组合认证、公告展示与 OAuth 回调,provide 给 LoginView 子组件。
* 依赖:auth.store、linked-nav.store、useLoginAuth、useLoginLanding。
* 逻辑:登录成功后预取关联服务侧栏入口,减少进入 Chat/工作台后的入口闪现。
*/
import { onMounted, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
@@ -13,6 +15,7 @@ import loginBg from '@/assets/login-bg.png';
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
import { useWorkspaceLocale } from '@/features/workspace/composables/useWorkspaceLocale';
import { continuationLocation, readSsoContinuation } from '@/features/sso';
import { useLinkedNavStore } from '@/features/sso/stores/linked-nav.store';
import { useLoginAuth } from './useLoginAuth';
import { useLoginLanding } from './useLoginLanding';
@@ -22,6 +25,7 @@ export function useLogin() {
const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const linkedNav = useLinkedNavStore();
const { setThemePreference, appliedTheme } = useTheme();
const deps = { t, locale, msg, router, route, setThemePreference, appliedTheme };
@@ -29,6 +33,7 @@ export function useLogin() {
const completePasswordLogin = async () => {
authStore.syncFromStorage();
void linkedNav.ensureLoaded({ force: true });
const continuation = readSsoContinuation();
if (continuation) {
await router.replace(continuationLocation(continuation));
@@ -39,6 +44,7 @@ export function useLogin() {
const completeOAuthLogin = async () => {
authStore.syncFromStorage();
void linkedNav.ensureLoaded({ force: true });
const continuation = readSsoContinuation();
if (continuation) {
await router.replace(continuationLocation(continuation));
@@ -1,6 +1,8 @@
/**
* features/chat/components/ChatMobileHeader.vue
* 移动端顶栏:Agent 名称、学习之窗与 Agent 切换弹层。
* 移动端顶栏:Agent 名称、学习之窗、关联服务入口与 Agent 切换弹层。
* 依赖:AgentCategoryList、ExternalSystemLinks。
* 逻辑:关联服务 compact 按钮与右侧 Agent/历史按钮同为 h-9 圆形图标。
*/
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
@@ -77,7 +79,12 @@ onBeforeUnmount(() => {
</button>
</div>
<div class="flex items-center gap-1">
<ExternalSystemLinks compact :show-label="false" />
<ExternalSystemLinks
compact
:show-label="false"
button-class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft"
icon-class="h-4 w-4 shrink-0"
/>
<button
type="button"
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft"
@@ -4,6 +4,7 @@
* 依赖:lucide-vue-next、LocaleToggleButton、ExternalSystemLinks、AgentCategoryList、chat.types。
* 逻辑:由聊天页面传入当前 Agent、历史记录与用户可用 Agent;通过事件把新会话、切换 Agent、反馈、进入管理控制台等操作回传给页面。
* 管理员通过底部右侧工具图标进入管理控制台;用户下拉菜单仅保留退出登录。
* 关联服务入口与主题/语言等底栏图标统一为同尺寸 inline icon 按钮,避免错位。
*/
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
@@ -129,7 +130,12 @@ const userInitial = (fallback: string) => {
</button>
<div class="mt-auto flex flex-col items-center gap-6 pb-2 text-muted">
<ExternalSystemLinks compact :show-label="false" />
<ExternalSystemLinks
compact
:show-label="false"
button-class="inline-flex items-center justify-center transition-colors hover:text-secondary"
icon-class="h-5 w-5 shrink-0"
/>
<button type="button" class="transition-colors hover:text-secondary"><Sparkles class="h-5 w-5" /></button>
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-brand-600 text-sm font-bold text-white shadow-sm shadow-brand-500/20">
{{ userInitial('I') }}
@@ -302,11 +308,16 @@ const userInitial = (fallback: string) => {
</button>
</div>
<div class="flex gap-3">
<ExternalSystemLinks compact :show-label="false" />
<div class="flex items-center gap-3">
<ExternalSystemLinks
compact
:show-label="false"
button-class="inline-flex items-center justify-center transition-colors hover:text-secondary"
icon-class="h-4 w-4 shrink-0"
/>
<button
type="button"
class="transition-colors hover:text-secondary"
class="inline-flex items-center justify-center transition-colors hover:text-secondary"
:title="appliedTheme === 'dark' ? ($t('theme.switchToLight') || 'Switch to light mode') : ($t('theme.switchToDark') || 'Switch to dark mode')"
@click="emit('toggle-theme')"
>
@@ -314,16 +325,16 @@ const userInitial = (fallback: string) => {
<Moon v-else class="h-4 w-4" />
</button>
<LocaleToggleButton variant="sidebar" />
<button type="button" class="transition-colors hover:text-secondary" :title="$t('chat.generalFeedback')" @click="emit('open-feedback')">
<button type="button" class="inline-flex items-center justify-center transition-colors hover:text-secondary" :title="$t('chat.generalFeedback')" @click="emit('open-feedback')">
<MessageSquareText class="h-4 w-4" />
</button>
<button type="button" class="transition-colors hover:text-secondary" :title="$t('workspace.title')" @click="emit('go-workspace')">
<button type="button" class="inline-flex items-center justify-center transition-colors hover:text-secondary" :title="$t('workspace.title')" @click="emit('go-workspace')">
<Briefcase class="h-4 w-4" />
</button>
<button
v-if="currentUser?.role === 'admin'"
type="button"
class="transition-colors hover:text-secondary"
class="inline-flex items-center justify-center transition-colors hover:text-secondary"
:title="$t('admin.title')"
@click="onGoAdmin"
>
@@ -0,0 +1,20 @@
/**
* features/sso/api/linked-services.api.ts
* 用途:读取管理台配置的关联服务(已启用),供侧栏入口展示。
* 依赖:shared/api/client。
* 逻辑:ExternalSystemLinks 合并本目录与 SSO 应用目录后渲染。
*/
import { requestJson } from '@/shared/api/client';
export interface LinkedServiceItem {
id: number;
name: string;
url: string;
}
/** 获取当前用户可见的已启用关联服务。 */
export async function listLinkedServices(): Promise<LinkedServiceItem[]> {
const data = await requestJson<{ items?: LinkedServiceItem[] } | LinkedServiceItem[]>('/api/linked-services');
if (Array.isArray(data)) return data;
return Array.isArray(data?.items) ? data.items : [];
}
@@ -1,54 +1,63 @@
<!--
features/sso/components/ExternalSystemLinks.vue
用途:在 HXOPS 已登录页面展示已配置产品内平级服务入口。
依赖:SSO 应用目录 API、lucide-vue-next。
逻辑:点击后先打开 HXOPS 同源 launch 页以继承当前登录态,再由 launch 页跳平级服务生成签名 state。
用途:在 HXOPS 已登录页面展示关联服务与产品内 SSO 平级服务入口。
依赖:linked-nav.store、lucide-vue-next。
逻辑:读 Pinia 缓存即时渲染;未缓存时触发一次预取。工作台可通过 buttonClass/iconClass 对齐 ws-nav-btn。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { computed, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { ExternalLink } from 'lucide-vue-next';
import { listSsoApplications, type SsoApplication } from '../api/sso.api';
import { useLinkedNavStore } from '../stores/linked-nav.store';
withDefaults(defineProps<{
const props = withDefaults(defineProps<{
compact?: boolean;
showLabel?: boolean;
/** 覆盖按钮样式(如工作台 ws-nav-btn),未传时用紧凑/默认样式 */
buttonClass?: string;
/** 覆盖图标尺寸类,未传时随 compact 变化 */
iconClass?: string;
}>(), {
compact: false,
showLabel: true,
buttonClass: '',
iconClass: '',
});
const applications = ref<SsoApplication[]>([]);
const linkedNav = useLinkedNavStore();
const { items } = storeToRefs(linkedNav);
/** 加载已启用应用;目录不可用时隐藏入口,不阻断 HXOPS 主业务。 */
async function loadApplications(): Promise<void> {
try {
applications.value = await listSsoApplications();
} catch (error) {
console.warn('[sso] failed to load peer services', error);
/**
* 解析按钮 class。
* 核心逻辑:外部传入优先;compact 默认与 Chat 底栏图标按钮一致(无额外 36px 盒子,避免错位)。
*/
const resolvedButtonClass = computed(() => {
if (props.buttonClass) return props.buttonClass;
if (props.compact) {
return 'inline-flex items-center justify-center transition-colors hover:text-secondary';
}
}
return 'inline-flex items-center justify-center gap-2 rounded-xl px-3 py-2 text-sm text-muted transition-colors hover:bg-surface-soft hover:text-secondary min-h-9';
});
/** 在新标签先打开同源中转页,确保非 remember 登录态也可继承到新标签。 */
function openApplication(application: SsoApplication): void {
window.open(`/sso/launch?app=${encodeURIComponent(application.key)}`, '_blank');
}
/** 解析图标 class:默认 16px,与 Chat 底栏 Moon/Briefcase 一致。 */
const resolvedIconClass = computed(() => props.iconClass || 'h-4 w-4 shrink-0');
onMounted(() => {
void loadApplications();
// 已缓存则立即展示;未缓存时补一次预取(登录后 App 通常已预取)。
void linkedNav.ensureLoaded();
});
</script>
<template>
<template v-for="application in applications" :key="application.key">
<template v-for="entry in items" :key="entry.key">
<button
type="button"
class="inline-flex items-center justify-center gap-2 rounded-xl text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
:class="compact ? 'h-9 w-9' : 'min-h-9 px-3 py-2 text-sm'"
:title="application.display_name"
@click="openApplication(application)"
:class="resolvedButtonClass"
:title="entry.display_name"
@click="linkedNav.openItem(entry)"
>
<ExternalLink class="h-4 w-4 shrink-0" />
<span v-if="showLabel && !compact" class="truncate">{{ application.display_name }}</span>
<ExternalLink :class="resolvedIconClass" />
<span v-if="showLabel && !compact" class="truncate">{{ entry.display_name }}</span>
</button>
</template>
</template>
+1
View File
@@ -5,6 +5,7 @@
* 逻辑:页面通过本入口复用平级服务导航,登录模块复用 continuation。
*/
export { default as ExternalSystemLinks } from './components/ExternalSystemLinks.vue';
export { useLinkedNavStore } from './stores/linked-nav.store';
export {
continuationLocation,
readSsoContinuation,
@@ -0,0 +1,154 @@
/**
* features/sso/stores/linked-nav.store.ts
* 用途:缓存关联服务 / SSO 侧栏入口,避免页面切换时重复请求导致入口闪现。
* 依赖:linked-services.api、sso.api、pinia。
* 逻辑:登录后预取一次;ExternalSystemLinks 直接读 store;登出或管理台变更时刷新/清空。
*/
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { listLinkedServices, type LinkedServiceItem } from '../api/linked-services.api';
import { listSsoApplications, type SsoApplication } from '../api/sso.api';
/** 侧栏可渲染的入口元数据(可序列化,不含函数)。 */
export interface LinkedNavItem {
key: string;
display_name: string;
/** sso:走 /sso/launch;url:直接打开 target */
mode: 'sso' | 'url';
target: string;
}
/** 规范化 URL 便于与 SSO login_url 比对。 */
function normalizeUrl(value: string): string {
return String(value || '').trim().replace(/\/+$/, '').toLowerCase();
}
/**
* 合并关联服务与 SSO 目录为侧栏入口列表。
* 核心逻辑:关联服务优先;命中 SSO 注册表则 mode=sso。
*/
function buildNavItems(linked: LinkedServiceItem[], ssoApps: SsoApplication[]): LinkedNavItem[] {
const usedSsoKeys = new Set<string>();
const next: LinkedNavItem[] = [];
for (const item of linked) {
const matched = ssoApps.find(
(app) =>
normalizeUrl(app.login_url) === normalizeUrl(item.url)
|| String(app.display_name || '').trim() === String(item.name || '').trim(),
);
if (matched) {
usedSsoKeys.add(matched.key);
next.push({
key: `linked-${item.id}`,
display_name: item.name,
mode: 'sso',
target: matched.key,
});
} else {
next.push({
key: `linked-${item.id}`,
display_name: item.name,
mode: 'url',
target: item.url,
});
}
}
for (const app of ssoApps) {
if (usedSsoKeys.has(app.key)) continue;
next.push({
key: `sso-${app.key}`,
display_name: app.display_name,
mode: 'sso',
target: app.key,
});
}
return next;
}
export const useLinkedNavStore = defineStore('linkedNav', () => {
const items = ref<LinkedNavItem[]>([]);
const loaded = ref(false);
const loading = ref(false);
let inflight: Promise<void> | null = null;
const hasItems = computed(() => items.value.length > 0);
/**
* 预取侧栏入口;已加载且非 force 时直接复用缓存。
* @param options.force - 为 true 时忽略缓存强制刷新(管理台保存后)
*/
async function ensureLoaded(options?: { force?: boolean }): Promise<void> {
if (options?.force) {
loaded.value = false;
}
if (loaded.value) return;
if (inflight) {
await inflight;
return;
}
loading.value = true;
inflight = (async () => {
let linked: LinkedServiceItem[] = [];
let ssoApps: SsoApplication[] = [];
try {
linked = await listLinkedServices();
} catch (error) {
console.warn('[linked-nav] failed to load linked services', error);
}
try {
ssoApps = await listSsoApplications();
} catch (error) {
console.warn('[linked-nav] failed to load sso apps', error);
}
items.value = buildNavItems(linked, ssoApps);
loaded.value = true;
})();
try {
await inflight;
} finally {
loading.value = false;
inflight = null;
}
}
/** 强制刷新入口缓存(管理台增删改后调用)。 */
async function refresh(): Promise<void> {
await ensureLoaded({ force: true });
}
/** 登出时清空,避免下一账号看到旧入口。 */
function reset(): void {
items.value = [];
loaded.value = false;
loading.value = false;
inflight = null;
}
/**
* 打开入口:SSO 走同源 launch,其它直接新开 URL。
* @param item - 侧栏入口元数据
*/
function openItem(item: LinkedNavItem): void {
if (item.mode === 'sso') {
window.open(`/sso/launch?app=${encodeURIComponent(item.target)}`, '_blank');
return;
}
window.open(item.target, '_blank');
}
return {
items,
loaded,
loading,
hasItems,
ensureLoaded,
refresh,
reset,
openItem,
};
});
@@ -1,7 +1,9 @@
<script setup lang="ts">
/**
* features/workspace/components/WorkspaceSidebar.vue
* 工作台左侧导航:子路由链接、第三方系统、返回聊天与退出登录。
* 工作台左侧导航:子路由链接、关联服务入口、返回聊天与退出登录。
* 依赖:WORKSPACE_PATHS、workspace.context、ExternalSystemLinks。
* 逻辑:底部关联服务复用 ws-nav-btn,与返回聊天/退出登录对齐。
*/
import { inject } from 'vue';
import { useRoute } from 'vue-router';
@@ -107,7 +109,12 @@ function isActive(match: readonly string[]) {
<div class="border-t border-subtle pt-4">
<div class="space-y-2">
<ExternalSystemLinks :compact="Boolean(collapsed)" :show-label="!collapsed" />
<ExternalSystemLinks
:compact="Boolean(collapsed)"
:show-label="!collapsed"
:button-class="collapsed ? 'ws-nav-btn justify-center px-0' : 'ws-nav-btn'"
icon-class="h-[18px] w-[18px] shrink-0"
/>
<button
type="button"
@click="ws.navigateToGeneralChat"
+36
View File
@@ -23,6 +23,7 @@
"announcements": "Announcements",
"questions": "Common Questions",
"wecom": "WeCom",
"linkedServices": "Linked Services",
"permissions": "App Permissions",
"requests": "Permission Requests",
"reports": "Data Reports",
@@ -30,6 +31,41 @@
"platformApps": "Platform Apps",
"procurementContract": "Procurement Contract Review"
},
"linkedServices": {
"title": "Linked Services",
"subtitle": "Configured name and URL entries appear at the bottom of the Chat and Workspace sidebars for one-click jumps.",
"add": "Add Service",
"edit": "Edit Linked Service",
"formHint": "When enabled, the entry is shown in the Chat / Workspace sidebar footer.",
"empty": "No linked services yet. Click Add Service to create one.",
"confirmDelete": "Delete this linked service? It will disappear from the sidebar immediately.",
"fields": {
"name": "Display Name",
"url": "URL",
"sortOrder": "Sort Order",
"enabled": "Enable entry"
},
"placeholders": {
"name": "e.g. Drawings",
"url": "http://192.168.100.192:8910/"
},
"headers": {
"name": "Name",
"url": "URL",
"status": "Status",
"sortOrder": "Order",
"actions": "Actions"
},
"status": {
"enabled": "Enabled",
"disabled": "Disabled"
},
"msg": {
"fillAll": "Please fill in name and URL",
"saved": "Linked service saved",
"deleted": "Linked service deleted"
}
},
"platformApps": {
"guideUsage": "Guide Usage",
"generalGuide": "General Guide",
+36
View File
@@ -23,6 +23,7 @@
"announcements": "การจัดการประกาศ",
"questions": "คำถามทั่วไป",
"wecom": "WeCom",
"linkedServices": "บริการที่เชื่อมโยง",
"permissions": "สิทธิ์แอปพลิเคชัน",
"requests": "คำขอสิทธิ์",
"reports": "รายงานข้อมูล",
@@ -30,6 +31,41 @@
"platformApps": "แอปแพลตฟอร์ม",
"procurementContract": "ตรวจสอบสัญญาจัดซื้อ"
},
"linkedServices": {
"title": "บริการที่เชื่อมโยง",
"subtitle": "ตั้งชื่อและ URL แล้วรายการจะปรากฏที่ด้านล่างของแถบข้าง Chat และ Workspace สำหรับการข้ามด้วยคลิกเดียว",
"add": "เพิ่มบริการ",
"edit": "แก้ไขบริการที่เชื่อมโยง",
"formHint": "เมื่อเปิดใช้งาน รายการจะแสดงที่ท้ายแถบข้าง Chat / Workspace",
"empty": "ยังไม่มีบริการที่เชื่อมโยง คลิกเพิ่มบริการเพื่อสร้าง",
"confirmDelete": "ลบบริการนี้หรือไม่? รายการจะหายจากแถบข้างทันที",
"fields": {
"name": "ชื่อที่แสดง",
"url": "URL",
"sortOrder": "ลำดับ",
"enabled": "เปิดใช้งานทางเข้า"
},
"placeholders": {
"name": "เช่น แบบ도면",
"url": "http://192.168.100.192:8910/"
},
"headers": {
"name": "ชื่อ",
"url": "URL",
"status": "สถานะ",
"sortOrder": "ลำดับ",
"actions": "การดำเนินการ"
},
"status": {
"enabled": "เปิด",
"disabled": "ปิด"
},
"msg": {
"fillAll": "กรุณากรอกชื่อและ URL",
"saved": "บันทึกบริการแล้ว",
"deleted": "ลบบริการแล้ว"
}
},
"platformApps": {
"guideUsage": "ประเภทการใช้งานเอกสาร",
"generalGuide": "คู่มือทั่วไป",
+36
View File
@@ -23,6 +23,7 @@
"announcements": "公告管理",
"questions": "常用问题",
"wecom": "企业微信",
"linkedServices": "关联服务",
"permissions": "应用权限",
"platformApps": "平台应用说明",
"requests": "权限审批",
@@ -30,6 +31,41 @@
"schedules": "排程管理",
"procurementContract": "采购合同审查"
},
"linkedServices": {
"title": "关联服务",
"subtitle": "配置名称与访问地址后,将自动出现在 Chat 与工作台侧栏底部,供用户一键跳转。",
"add": "新增服务",
"edit": "编辑关联服务",
"formHint": "启用后会同步展示在 Chat / 工作台侧栏底部入口。",
"empty": "暂无关联服务,点击右上角新增。",
"confirmDelete": "确定删除该关联服务?删除后侧栏入口将立即消失。",
"fields": {
"name": "显示名称",
"url": "访问地址",
"sortOrder": "排序",
"enabled": "启用入口"
},
"placeholders": {
"name": "例如:图纸",
"url": "http://192.168.100.192:8910/"
},
"headers": {
"name": "名称",
"url": "URL",
"status": "状态",
"sortOrder": "排序",
"actions": "操作"
},
"status": {
"enabled": "启用",
"disabled": "停用"
},
"msg": {
"fillAll": "请填写名称和访问地址",
"saved": "关联服务已保存",
"deleted": "关联服务已删除"
}
},
"platformApps": {
"guideUsage": "资料用途",
"generalGuide": "通用指南",
+36
View File
@@ -23,6 +23,7 @@
"announcements": "公告管理",
"questions": "常用問題",
"wecom": "企業微信",
"linkedServices": "關聯服務",
"permissions": "應用權限",
"requests": "權限審批",
"reports": "數據報表",
@@ -30,6 +31,41 @@
"platformApps": "平台應用說明",
"procurementContract": "採購合同審查"
},
"linkedServices": {
"title": "關聯服務",
"subtitle": "設定名稱與訪問地址後,將自動出現在 Chat 與工作台側欄底部,供使用者一鍵跳轉。",
"add": "新增服務",
"edit": "編輯關聯服務",
"formHint": "啟用後會同步展示在 Chat / 工作台側欄底部入口。",
"empty": "暫無關聯服務,點擊右上角新增。",
"confirmDelete": "確定刪除該關聯服務?刪除後側欄入口將立即消失。",
"fields": {
"name": "顯示名稱",
"url": "訪問地址",
"sortOrder": "排序",
"enabled": "啟用入口"
},
"placeholders": {
"name": "例如:圖紙",
"url": "http://192.168.100.192:8910/"
},
"headers": {
"name": "名稱",
"url": "URL",
"status": "狀態",
"sortOrder": "排序",
"actions": "操作"
},
"status": {
"enabled": "啟用",
"disabled": "停用"
},
"msg": {
"fillAll": "請填寫名稱和訪問地址",
"saved": "關聯服務已儲存",
"deleted": "關聯服務已刪除"
}
},
"platformApps": {
"guideUsage": "資料用途",
"generalGuide": "通用指南",