fix(auth): bind admins to enterprise tenant context
This commit is contained in:
@@ -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