85 lines
3.2 KiB
Python
85 lines
3.2 KiB
Python
"""
|
|
backend/app/services/auth/hxops/user_resolver.py
|
|
|
|
用途:将统一 AuthIdentity 按工号映射为 HXOPS 本地 User。
|
|
依赖:Flask 日志、SQLAlchemy session、User、AuthIdentity。
|
|
逻辑:Casdoor 工号优先;用户名作为当前“用户名即工号”的过渡兼容,不使用邮箱或手机号。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from flask import current_app
|
|
|
|
from app.extensions import db
|
|
from app.models import User
|
|
from app.services.auth.common import AuthIdentity
|
|
|
|
|
|
class HxopsIdentityMappingError(Exception):
|
|
"""HXOPS 本地用户无法映射或状态不允许登录。"""
|
|
|
|
def __init__(self, message: str, *, code: str, status: int):
|
|
super().__init__(message)
|
|
self.code = code
|
|
self.status = status
|
|
|
|
|
|
def resolve_hxops_user(identity: AuthIdentity) -> User:
|
|
"""
|
|
按工号优先规则将认证身份映射到 HXOPS 用户。
|
|
|
|
核心逻辑:优先使用 Casdoor employee_id;若其缺失,则将当前用户名作为工号
|
|
查找本地 employee_id,最后才按 username 兼容历史数据。邮箱和手机号不参与认证
|
|
匹配。若工号与用户名分别命中不同用户,拒绝登录以防错误账号关联。
|
|
|
|
Args:
|
|
identity: 已验证 Casdoor issuer/subject 的统一身份;employee_id 是首选匹配键。
|
|
|
|
Returns:
|
|
状态为 active 的 HXOPS User。
|
|
|
|
Raises:
|
|
HxopsIdentityMappingError: 用户未同步、身份字段冲突或账号已禁用。
|
|
"""
|
|
current_app.logger.info(
|
|
'[casdoor_login] identity employee_id=%s username=%s subject=%s',
|
|
identity.employee_id,
|
|
identity.username,
|
|
identity.subject,
|
|
)
|
|
|
|
# [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.',
|
|
code='CASDOOR_USER_NOT_FOUND',
|
|
status=403,
|
|
)
|
|
if user.status != 'active':
|
|
raise HxopsIdentityMappingError('Account is disabled', code='ACCOUNT_DISABLED', status=403)
|
|
return user
|