fix(auth): bind admins to enterprise tenant context
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -7,6 +7,7 @@ from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.db.base import Base
|
||||
from app.models.auth_session import AuthSession
|
||||
from app.models.tenant import Tenant
|
||||
from app.models.user_session_metric import UserSessionMetric
|
||||
from app.schemas.auth import LoginRequest
|
||||
from app.schemas.settings import SettingsWrite
|
||||
@@ -16,7 +17,7 @@ from app.services.employee import EmployeeService
|
||||
from app.services.settings import SettingsService
|
||||
|
||||
|
||||
def build_session() -> Session:
|
||||
def build_session() -> Session:
|
||||
engine = create_engine(
|
||||
"sqlite+pysqlite:///:memory:",
|
||||
connect_args={"check_same_thread": False},
|
||||
@@ -24,7 +25,16 @@ def build_session() -> Session:
|
||||
)
|
||||
Base.metadata.create_all(bind=engine)
|
||||
session_factory = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
return session_factory()
|
||||
return session_factory()
|
||||
|
||||
|
||||
def configure_admin(db: Session, *, account: str = "admin", password: str = "admin") -> None:
|
||||
settings_service = SettingsService(db)
|
||||
payload = settings_service.get_settings_snapshot().model_dump()
|
||||
payload["adminForm"]["adminAccount"] = account
|
||||
payload["adminForm"]["newPassword"] = password
|
||||
payload["adminForm"]["confirmPassword"] = password
|
||||
settings_service.save_settings_snapshot(SettingsWrite(**payload))
|
||||
|
||||
|
||||
def test_employee_can_login_with_seed_default_password() -> None:
|
||||
@@ -65,13 +75,8 @@ def test_current_user_snapshot_refreshes_employee_position() -> None:
|
||||
|
||||
|
||||
def test_admin_can_login_with_database_password() -> None:
|
||||
with build_session() as db:
|
||||
settings_service = SettingsService(db)
|
||||
payload = settings_service.get_settings_snapshot().model_dump()
|
||||
payload["adminForm"]["adminAccount"] = "superadmin"
|
||||
payload["adminForm"]["newPassword"] = "admin123"
|
||||
payload["adminForm"]["confirmPassword"] = "admin123"
|
||||
settings_service.save_settings_snapshot(SettingsWrite(**payload))
|
||||
with build_session() as db:
|
||||
configure_admin(db, account="superadmin", password="admin123")
|
||||
|
||||
result = AuthService(db).login(
|
||||
LoginRequest(username="superadmin", password="admin123")
|
||||
@@ -82,6 +87,67 @@ def test_admin_can_login_with_database_password() -> None:
|
||||
assert result.user.isAdmin is True
|
||||
assert result.user.position == "系统管理员"
|
||||
assert result.user.roleCodes == ["manager"]
|
||||
assert result.user.tenantId == "platform"
|
||||
|
||||
|
||||
def test_admin_login_uses_requested_active_tenant_and_restores_session_scope() -> None:
|
||||
with build_session() as db:
|
||||
configure_admin(db)
|
||||
db.add(
|
||||
Tenant(
|
||||
tenant_id="default",
|
||||
tenant_code="default",
|
||||
name="默认企业",
|
||||
status="active",
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
result = AuthService(db).login(
|
||||
LoginRequest(username="admin", password="admin", tenantId="default")
|
||||
)
|
||||
auth_session = db.query(AuthSession).one()
|
||||
restored = AuthService(db).get_session_user(auth_session)
|
||||
|
||||
assert result.user.isAdmin is True
|
||||
assert result.user.tenantId == "default"
|
||||
assert auth_session.principal_type == "admin"
|
||||
assert auth_session.tenant_id == "default"
|
||||
assert restored is not None
|
||||
assert restored.is_admin is True
|
||||
assert restored.tenant_id == "default"
|
||||
|
||||
|
||||
def test_admin_login_rejects_unknown_or_inactive_requested_tenant() -> None:
|
||||
with build_session() as db:
|
||||
configure_admin(db)
|
||||
db.add(
|
||||
Tenant(
|
||||
tenant_id="tenant-disabled",
|
||||
tenant_code="company-disabled",
|
||||
name="停用企业",
|
||||
status="disabled",
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
with pytest.raises(ValueError, match="企业代码不存在或当前不可用"):
|
||||
AuthService(db).login(
|
||||
LoginRequest(
|
||||
username="admin",
|
||||
password="admin",
|
||||
tenantId="company-disabled",
|
||||
)
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="企业代码不存在或当前不可用"):
|
||||
AuthService(db).login(
|
||||
LoginRequest(
|
||||
username="admin",
|
||||
password="admin",
|
||||
tenantId="missing-tenant",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_disabled_employee_cannot_login() -> None:
|
||||
|
||||
131
server/tests/test_employee_admin_tenant_endpoints.py
Normal file
131
server/tests/test_employee_admin_tenant_endpoints.py
Normal file
@@ -0,0 +1,131 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Generator
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine, func, select
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.api.deps import get_db
|
||||
from app.db.base import Base
|
||||
from app.main import create_app
|
||||
from app.models.employee import Employee
|
||||
from app.models.organization import OrganizationUnit
|
||||
from app.schemas.settings import SettingsWrite
|
||||
from app.services.settings import SettingsService
|
||||
from app.services.tenant_registry import TenantRegistryService
|
||||
|
||||
|
||||
def build_client() -> tuple[TestClient, sessionmaker[Session]]:
|
||||
engine = create_engine(
|
||||
"sqlite+pysqlite:///:memory:",
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
Base.metadata.create_all(bind=engine)
|
||||
session_factory = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
with session_factory() as db:
|
||||
TenantRegistryService(db).ensure_builtin()
|
||||
settings_service = SettingsService(db)
|
||||
payload = settings_service.get_settings_snapshot().model_dump()
|
||||
payload["adminForm"]["adminAccount"] = "admin"
|
||||
payload["adminForm"]["newPassword"] = "admin"
|
||||
payload["adminForm"]["confirmPassword"] = "admin"
|
||||
settings_service.save_settings_snapshot(SettingsWrite(**payload))
|
||||
|
||||
app = create_app()
|
||||
|
||||
def override_db() -> Generator[Session, None, None]:
|
||||
with session_factory() as db:
|
||||
yield db
|
||||
|
||||
app.dependency_overrides[get_db] = override_db
|
||||
return TestClient(app), session_factory
|
||||
|
||||
|
||||
def test_admin_selected_default_tenant_reads_default_employee_directory() -> None:
|
||||
client, session_factory = build_client()
|
||||
|
||||
login_response = client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"username": "admin", "password": "admin", "tenantId": "default"},
|
||||
)
|
||||
|
||||
assert login_response.status_code == 200
|
||||
login_payload = login_response.json()
|
||||
assert login_payload["user"]["tenantId"] == "default"
|
||||
headers = {"Authorization": f"Bearer {login_payload['accessToken']}"}
|
||||
|
||||
meta_response = client.get("/api/v1/employees/meta", headers=headers)
|
||||
list_response = client.get("/api/v1/employees", headers=headers)
|
||||
|
||||
assert meta_response.status_code == 200
|
||||
assert list_response.status_code == 200
|
||||
assert meta_response.json()["totalEmployees"] == 30
|
||||
assert len(list_response.json()) == 30
|
||||
|
||||
with session_factory() as db:
|
||||
default_employee_count = db.scalar(
|
||||
select(func.count())
|
||||
.select_from(Employee)
|
||||
.where(Employee.tenant_id == "default")
|
||||
)
|
||||
platform_employee_count = db.scalar(
|
||||
select(func.count())
|
||||
.select_from(Employee)
|
||||
.where(Employee.tenant_id == "platform")
|
||||
)
|
||||
default_unit_count = db.scalar(
|
||||
select(func.count())
|
||||
.select_from(OrganizationUnit)
|
||||
.where(OrganizationUnit.tenant_id == "default")
|
||||
)
|
||||
platform_unit_count = db.scalar(
|
||||
select(func.count())
|
||||
.select_from(OrganizationUnit)
|
||||
.where(OrganizationUnit.tenant_id == "platform")
|
||||
)
|
||||
|
||||
assert default_employee_count == 30
|
||||
assert platform_employee_count == 0
|
||||
assert default_unit_count == 7
|
||||
assert platform_unit_count == 0
|
||||
|
||||
|
||||
def test_platform_admin_cannot_seed_platform_employee_directory() -> None:
|
||||
client, session_factory = build_client()
|
||||
|
||||
login_response = client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"username": "admin", "password": "admin"},
|
||||
)
|
||||
|
||||
assert login_response.status_code == 200
|
||||
login_payload = login_response.json()
|
||||
assert login_payload["user"]["tenantId"] == "platform"
|
||||
headers = {"Authorization": f"Bearer {login_payload['accessToken']}"}
|
||||
|
||||
meta_response = client.get("/api/v1/employees/meta", headers=headers)
|
||||
list_response = client.get("/api/v1/employees", headers=headers)
|
||||
|
||||
assert meta_response.status_code == 403
|
||||
assert list_response.status_code == 403
|
||||
assert meta_response.json()["detail"] == "员工目录只能在企业工作域内使用。"
|
||||
assert list_response.json()["detail"] == "员工目录只能在企业工作域内使用。"
|
||||
|
||||
with session_factory() as db:
|
||||
platform_employee_count = db.scalar(
|
||||
select(func.count())
|
||||
.select_from(Employee)
|
||||
.where(Employee.tenant_id == "platform")
|
||||
)
|
||||
platform_unit_count = db.scalar(
|
||||
select(func.count())
|
||||
.select_from(OrganizationUnit)
|
||||
.where(OrganizationUnit.tenant_id == "platform")
|
||||
)
|
||||
|
||||
assert platform_employee_count == 0
|
||||
assert platform_unit_count == 0
|
||||
Reference in New Issue
Block a user