fix(auth): bind admins to enterprise tenant context

This commit is contained in:
caoxiaozhu
2026-07-20 10:29:30 +08:00
parent 372e35d62a
commit c59990dc35
9 changed files with 336 additions and 18 deletions

View File

@@ -8,6 +8,7 @@ from sqlalchemy.orm import Session
from app.db.session import get_session_factory
from app.services.auth import AuthService
from app.services.auth_sessions import AuthSessionService
from app.services.tenant_registry import PLATFORM_TENANT_ID
def get_db() -> Generator[Session, None, None]:
@@ -129,6 +130,19 @@ def require_admin_user(
)
def require_enterprise_admin_user(
current_user: Annotated[CurrentUserContext, Depends(require_admin_user)],
) -> CurrentUserContext:
"""限制企业目录类管理接口,避免在平台工作域误生成业务数据。"""
if current_user.tenant_id == PLATFORM_TENANT_ID:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="员工目录只能在企业工作域内使用。",
)
return current_user
def require_platform_admin_user(
current_user: Annotated[CurrentUserContext, Depends(get_current_user)],
) -> CurrentUserContext:

View File

@@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile,
from fastapi.responses import Response
from sqlalchemy.orm import Session
from app.api.deps import CurrentUserContext, get_db, require_admin_user
from app.api.deps import CurrentUserContext, get_db, require_enterprise_admin_user
from app.api.pagination import PageNumber, PageSize, page_payload, wants_page
from app.schemas.common import ErrorResponse, PaginatedResponse
from app.schemas.employee import (
@@ -19,9 +19,9 @@ from app.schemas.employee import (
from app.services.employee import EmployeeService
from app.services.employee_pagination import EmployeePaginationService
router = APIRouter(dependencies=[Depends(require_admin_user)])
router = APIRouter(dependencies=[Depends(require_enterprise_admin_user)])
DbSession = Annotated[Session, Depends(get_db)]
AdminUser = Annotated[CurrentUserContext, Depends(require_admin_user)]
AdminUser = Annotated[CurrentUserContext, Depends(require_enterprise_admin_user)]
def _employee_service(db: Session, current_user: CurrentUserContext) -> EmployeeService:

View File

@@ -72,7 +72,11 @@ class AuthService:
identifier = payload.username.strip()
password = payload.password
admin_user = self._authenticate_admin(identifier, password)
admin_user = self._authenticate_admin(
identifier,
password,
requested_tenant=payload.tenant_id,
)
if admin_user is not None:
logger.info("Admin login succeeded identifier=%s", identifier)
return self._build_login_response(admin_user)
@@ -127,7 +131,14 @@ class AuthService:
}
if auth_session.username.strip().casefold() not in allowed_identifiers:
return None
return self._restore_session_scope(self._build_admin_user(record), auth_session)
try:
tenant_id = self._resolve_admin_tenant_id(auth_session.tenant_id)
except ValueError:
return None
return self._restore_session_scope(
self._build_admin_user(record, tenant_id=tenant_id),
auth_session,
)
if auth_session.principal_type != "employee":
return None
@@ -189,15 +200,28 @@ class AuthService:
return self._serialize_user(self._build_employee_user(employee))
def _authenticate_admin(self, identifier: str, password: str) -> AuthenticatedUser | None:
def _authenticate_admin(
self,
identifier: str,
password: str,
*,
requested_tenant: str | None,
) -> AuthenticatedUser | None:
record = SettingsService(self.db).verify_admin_login(identifier, password)
if record is None:
return None
return self._build_admin_user(record)
return self._build_admin_user(
record,
tenant_id=self._resolve_admin_tenant_id(requested_tenant),
)
@staticmethod
def _build_admin_user(record: Any) -> AuthenticatedUser:
def _build_admin_user(
record: Any,
*,
tenant_id: str = PLATFORM_TENANT_ID,
) -> AuthenticatedUser:
admin_username = record.account.strip()
admin_email = record.email.strip()
display_name = admin_username or admin_email or "系统管理员"
@@ -218,10 +242,30 @@ class AuthService:
role_codes=["manager"],
email=admin_email or f"{admin_username}@local",
avatar=display_name[:1].upper(),
tenant_id=PLATFORM_TENANT_ID,
tenant_id=required_tenant_id(tenant_id),
is_admin=True,
)
def _resolve_admin_tenant_id(self, requested_tenant: str | None) -> str:
"""把管理员当前工作域绑定到登录时选择的有效企业。"""
normalized_tenant = str(requested_tenant or "").strip()
if not normalized_tenant or normalized_tenant == PLATFORM_TENANT_ID:
return PLATFORM_TENANT_ID
tenant = self.db.scalar(
select(Tenant).where(
or_(
Tenant.tenant_id == normalized_tenant,
Tenant.tenant_code == normalized_tenant,
),
Tenant.status == "active",
)
)
if tenant is None:
raise ValueError("企业代码不存在或当前不可用。")
return required_tenant_id(tenant.tenant_id)
def _authenticate_employee(
self,
identifier: str,