70 lines
2.3 KiB
Python
70 lines
2.3 KiB
Python
"""
|
|
backend/app/services/auth/common/identity.py
|
|
|
|
用途:定义跨认证来源通用、可复制的稳定身份对象。
|
|
依赖:Python dataclasses;不依赖 Flask、SQLAlchemy 或 HXOPS User。
|
|
逻辑:Casdoor claims 先转换为 AuthIdentity,业务系统再按 issuer + subject 映射自己的用户。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
|
class IdentityValidationError(ValueError):
|
|
"""身份缺少跨服务稳定键时抛出,调用方负责映射为自身错误契约。"""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class AuthIdentity:
|
|
"""认证系统返回的稳定身份和可变展示资料,不包含任何业务权限。"""
|
|
|
|
issuer: str
|
|
subject: str
|
|
username: str
|
|
display_name: str | None = None
|
|
email: str | None = None
|
|
phone_number: str | None = None
|
|
employee_id: str | None = None
|
|
department: str | None = None
|
|
|
|
|
|
def require_stable_identity(identity: AuthIdentity) -> AuthIdentity:
|
|
"""
|
|
校验跨服务身份必须具备 issuer、subject 和 username。
|
|
|
|
Args:
|
|
identity: 待校验的认证身份。
|
|
|
|
Returns:
|
|
去除稳定键首尾空白后的不可变身份对象。
|
|
|
|
Raises:
|
|
IdentityValidationError: 缺少稳定身份键或用户名。
|
|
"""
|
|
issuer = str(identity.issuer or '').strip()
|
|
subject = str(identity.subject or '').strip()
|
|
username = str(identity.username or '').strip()
|
|
if not issuer or not subject:
|
|
raise IdentityValidationError('Identity issuer and subject are required')
|
|
if not username:
|
|
raise IdentityValidationError('Identity username is required')
|
|
if issuer == identity.issuer and subject == identity.subject and username == identity.username:
|
|
return identity
|
|
return AuthIdentity(
|
|
issuer=issuer,
|
|
subject=subject,
|
|
username=username,
|
|
display_name=identity.display_name,
|
|
email=identity.email,
|
|
phone_number=identity.phone_number,
|
|
employee_id=identity.employee_id,
|
|
department=identity.department,
|
|
)
|
|
|
|
|
|
def identity_key(identity: AuthIdentity) -> tuple[str, str]:
|
|
"""返回业务系统建立外部身份映射时使用的唯一键 ``(issuer, subject)``。"""
|
|
stable = require_stable_identity(identity)
|
|
return stable.issuer, stable.subject
|