fix(auth): 重构登录认证,并支持跳转到关联服务如图纸标注
This commit is contained in:
1 parent
ce1fd59f61
commit
affe139bf9
51 files changed
+1939
-132
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
@@ -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.',
|
||||
|
||||
Reference in new issue
Block a user