swiftapi-kernel 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of swiftapi-kernel might be problematic. Click here for more details.
- swiftapi/__init__.py +22 -0
- swiftapi/app/__init__.py +0 -0
- swiftapi/app/factory.py +200 -0
- swiftapi/app/lifespan.py +167 -0
- swiftapi/app/routers.py +58 -0
- swiftapi/cli/__init__.py +0 -0
- swiftapi/cli/admin.py +198 -0
- swiftapi/cli/appref.py +51 -0
- swiftapi/cli/audit.py +45 -0
- swiftapi/cli/db.py +185 -0
- swiftapi/cli/endpoint.py +169 -0
- swiftapi/cli/logs.py +100 -0
- swiftapi/cli/main.py +238 -0
- swiftapi/cli/new.py +113 -0
- swiftapi/cli/openapi.py +69 -0
- swiftapi/cli/resource.py +657 -0
- swiftapi/cli/scaffold.py +168 -0
- swiftapi/config/__init__.py +0 -0
- swiftapi/config/constants.py +51 -0
- swiftapi/config/environments.py +38 -0
- swiftapi/config/settings.py +764 -0
- swiftapi/core/__init__.py +0 -0
- swiftapi/core/admin/__init__.py +0 -0
- swiftapi/core/admin/accounts.py +385 -0
- swiftapi/core/admin/audit.py +203 -0
- swiftapi/core/admin/maintenance.py +53 -0
- swiftapi/core/admin/registry.py +53 -0
- swiftapi/core/admin/security.py +94 -0
- swiftapi/core/admin/session.py +154 -0
- swiftapi/core/admin/views.py +2428 -0
- swiftapi/core/cache/__init__.py +0 -0
- swiftapi/core/cache/base.py +29 -0
- swiftapi/core/cache/decorators.py +51 -0
- swiftapi/core/cache/factory.py +30 -0
- swiftapi/core/cache/keys.py +24 -0
- swiftapi/core/cache/memory.py +60 -0
- swiftapi/core/cache/null.py +28 -0
- swiftapi/core/cache/redis.py +50 -0
- swiftapi/core/container.py +209 -0
- swiftapi/core/db/__init__.py +0 -0
- swiftapi/core/db/base_model.py +122 -0
- swiftapi/core/db/crud.py +242 -0
- swiftapi/core/db/dialects/__init__.py +8 -0
- swiftapi/core/db/dialects/base.py +106 -0
- swiftapi/core/db/dialects/mysql.py +47 -0
- swiftapi/core/db/dialects/pg.py +51 -0
- swiftapi/core/db/dialects/registry.py +30 -0
- swiftapi/core/db/dialects/sqlite.py +47 -0
- swiftapi/core/db/engine.py +209 -0
- swiftapi/core/db/health.py +84 -0
- swiftapi/core/db/migrate/__init__.py +1 -0
- swiftapi/core/db/migrate/ddl.py +162 -0
- swiftapi/core/db/migrate/render.py +84 -0
- swiftapi/core/db/migrate/runner.py +159 -0
- swiftapi/core/db/migrate/schema.py +248 -0
- swiftapi/core/db/mixins.py +53 -0
- swiftapi/core/db/session.py +54 -0
- swiftapi/core/db/snapshot.py +33 -0
- swiftapi/core/db/tenant_model.py +43 -0
- swiftapi/core/db/tenant_router.py +114 -0
- swiftapi/core/db/types.py +109 -0
- swiftapi/core/db/unit_of_work.py +65 -0
- swiftapi/core/docs/__init__.py +0 -0
- swiftapi/core/docs/router.py +26 -0
- swiftapi/core/docs/tsgen.py +93 -0
- swiftapi/core/docs/ui.py +132 -0
- swiftapi/core/errors/__init__.py +0 -0
- swiftapi/core/errors/base.py +168 -0
- swiftapi/core/errors/codes.py +117 -0
- swiftapi/core/errors/handlers.py +155 -0
- swiftapi/core/errors/problem.py +58 -0
- swiftapi/core/errors/validation.py +11 -0
- swiftapi/core/framework_models.py +22 -0
- swiftapi/core/http/__init__.py +47 -0
- swiftapi/core/http/app.py +247 -0
- swiftapi/core/http/cors.py +100 -0
- swiftapi/core/http/idempotency.py +148 -0
- swiftapi/core/http/middleware/__init__.py +82 -0
- swiftapi/core/http/middleware/access_log.py +57 -0
- swiftapi/core/http/middleware/auth.py +105 -0
- swiftapi/core/http/middleware/body_limit.py +76 -0
- swiftapi/core/http/middleware/rate_limit.py +103 -0
- swiftapi/core/http/middleware/request_body.py +122 -0
- swiftapi/core/http/middleware/request_id.py +46 -0
- swiftapi/core/http/middleware/security_headers.py +46 -0
- swiftapi/core/http/middleware/tenant.py +93 -0
- swiftapi/core/http/middleware/timing.py +57 -0
- swiftapi/core/http/multipart.py +116 -0
- swiftapi/core/http/multipart_stream.py +216 -0
- swiftapi/core/http/openapi.py +148 -0
- swiftapi/core/http/pagination.py +55 -0
- swiftapi/core/http/params.py +302 -0
- swiftapi/core/http/request.py +145 -0
- swiftapi/core/http/responses.py +127 -0
- swiftapi/core/http/routing.py +200 -0
- swiftapi/core/http/types.py +86 -0
- swiftapi/core/http/uploads.py +222 -0
- swiftapi/core/messaging/__init__.py +0 -0
- swiftapi/core/messaging/base.py +33 -0
- swiftapi/core/messaging/consumer.py +57 -0
- swiftapi/core/messaging/factory.py +30 -0
- swiftapi/core/messaging/idempotency.py +61 -0
- swiftapi/core/messaging/inprocess.py +30 -0
- swiftapi/core/messaging/outbox.py +106 -0
- swiftapi/core/messaging/rabbitmq.py +186 -0
- swiftapi/core/messaging/relay.py +151 -0
- swiftapi/core/messaging/streams.py +141 -0
- swiftapi/core/observability/__init__.py +0 -0
- swiftapi/core/observability/archive.py +136 -0
- swiftapi/core/observability/context.py +102 -0
- swiftapi/core/observability/logging.py +192 -0
- swiftapi/core/observability/masking.py +74 -0
- swiftapi/core/observability/metrics.py +101 -0
- swiftapi/core/observability/volume.py +67 -0
- swiftapi/core/resilience/__init__.py +0 -0
- swiftapi/core/resilience/bulkhead.py +50 -0
- swiftapi/core/resilience/circuit_breaker.py +97 -0
- swiftapi/core/resilience/client.py +179 -0
- swiftapi/core/resilience/retry.py +59 -0
- swiftapi/core/security/__init__.py +0 -0
- swiftapi/core/security/jwt.py +78 -0
- swiftapi/core/security/principal.py +78 -0
- swiftapi/core/tenant/__init__.py +1 -0
- swiftapi/core/tenant/catalog.py +89 -0
- swiftapi/core/tenant/context.py +75 -0
- swiftapi/core/tenant/isolation.py +48 -0
- swiftapi/core/tenant/resolver.py +48 -0
- swiftapi/core/validation/__init__.py +0 -0
- swiftapi/core/validation/base.py +32 -0
- swiftapi/db.py +50 -0
- swiftapi/modules/__init__.py +0 -0
- swiftapi/modules/users/__init__.py +11 -0
- swiftapi/modules/users/api/__init__.py +0 -0
- swiftapi/modules/users/api/users.py +110 -0
- swiftapi/modules/users/crud/__init__.py +0 -0
- swiftapi/modules/users/crud/user.py +23 -0
- swiftapi/modules/users/errors.py +24 -0
- swiftapi/modules/users/mappers.py +19 -0
- swiftapi/modules/users/model/__init__.py +0 -0
- swiftapi/modules/users/model/user.py +37 -0
- swiftapi/modules/users/policies.py +19 -0
- swiftapi/modules/users/schema/__init__.py +0 -0
- swiftapi/modules/users/schema/user.py +40 -0
- swiftapi/modules/users/service/__init__.py +0 -0
- swiftapi/modules/users/service/user.py +107 -0
- swiftapi/py.typed +0 -0
- swiftapi/templates/__init__.py +0 -0
- swiftapi/templates/app_skeleton/README.md +17 -0
- swiftapi/templates/app_skeleton/__init__.py +1 -0
- swiftapi/templates/app_skeleton/api/__init__.py +23 -0
- swiftapi/templates/app_skeleton/api/health.py +12 -0
- swiftapi/templates/app_skeleton/crud/__init__.py +1 -0
- swiftapi/templates/app_skeleton/model/__init__.py +1 -0
- swiftapi/templates/app_skeleton/router.py +16 -0
- swiftapi/templates/app_skeleton/schema/__init__.py +1 -0
- swiftapi/templates/app_skeleton/service/__init__.py +1 -0
- swiftapi/templates/project/__init__.py +0 -0
- swiftapi/templates/project/api.py +135 -0
- swiftapi/templates/project/app.py +57 -0
- swiftapi/templates/project/endpoints/__init__.py +25 -0
- swiftapi/templates/project/events.py +43 -0
- swiftapi/templates/project/models.py +79 -0
- swiftapi/templates/project/resources/__init__.py +35 -0
- swiftapi/templates/project/schemas.py +45 -0
- swiftapi/templates/project/service.py +125 -0
- swiftapi/templates/project/settings.py +17 -0
- swiftapi/templates/project_skeleton/.env.example +5 -0
- swiftapi/templates/project_skeleton/.gitignore +6 -0
- swiftapi/templates/project_skeleton/README.md +25 -0
- swiftapi/templates/project_skeleton/__init__.py +1 -0
- swiftapi/templates/project_skeleton/app.py +26 -0
- swiftapi/templates/project_skeleton/apps/__init__.py +1 -0
- swiftapi/templates/project_skeleton/common/__init__.py +4 -0
- swiftapi/templates/project_skeleton/conf/__init__.py +1 -0
- swiftapi/templates/project_skeleton/conf/settings.py +73 -0
- swiftapi/templates/project_skeleton/logs/.gitkeep +0 -0
- swiftapi/templates/project_skeleton/models.py +12 -0
- swiftapi/templates/project_skeleton/nginx/nginx.conf +20 -0
- swiftapi/templates/project_skeleton/router.py +46 -0
- swiftapi/templates/project_skeleton/script/start.sh +13 -0
- swiftapi/templates/project_skeleton/start.py +35 -0
- swiftapi/version.py +8 -0
- swiftapi_kernel-0.1.0.dist-info/METADATA +962 -0
- swiftapi_kernel-0.1.0.dist-info/RECORD +187 -0
- swiftapi_kernel-0.1.0.dist-info/WHEEL +4 -0
- swiftapi_kernel-0.1.0.dist-info/entry_points.txt +3 -0
- swiftapi_kernel-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""已认证主体与权限判定(架构文档 §10.9)。
|
|
2
|
+
|
|
3
|
+
认证方式(JWT/OIDC)在 P4 接入;这里定义"认证之后长什么样"以及"怎么判权"。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from uuid import UUID
|
|
11
|
+
|
|
12
|
+
from swiftapi.core.errors.base import PermissionDenied, Unauthenticated
|
|
13
|
+
from swiftapi.core.http.request import Request
|
|
14
|
+
|
|
15
|
+
ROLE_PERMISSIONS: dict[str, frozenset[str]] = {
|
|
16
|
+
"admin": frozenset(
|
|
17
|
+
{
|
|
18
|
+
"users:read",
|
|
19
|
+
"users:write",
|
|
20
|
+
"admin:view",
|
|
21
|
+
"admin:create",
|
|
22
|
+
"admin:edit",
|
|
23
|
+
"admin:export",
|
|
24
|
+
"admin:manage",
|
|
25
|
+
"admin:dangerous",
|
|
26
|
+
}
|
|
27
|
+
),
|
|
28
|
+
"member": frozenset({"users:read"}),
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def register_role(role: str, permissions: frozenset[str]) -> None:
|
|
33
|
+
"""应用可以扩展自己的角色(内核只内置 admin/member 两种)。"""
|
|
34
|
+
ROLE_PERMISSIONS[role] = permissions
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, slots=True)
|
|
38
|
+
class Principal:
|
|
39
|
+
subject: UUID
|
|
40
|
+
roles: frozenset[str] = field(default_factory=frozenset)
|
|
41
|
+
tenant_id: UUID | None = None
|
|
42
|
+
tenants: frozenset[str] = field(default_factory=frozenset)
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def permissions(self) -> frozenset[str]:
|
|
46
|
+
granted: set[str] = set()
|
|
47
|
+
for role in self.roles:
|
|
48
|
+
granted |= ROLE_PERMISSIONS.get(role, frozenset())
|
|
49
|
+
return frozenset(granted)
|
|
50
|
+
|
|
51
|
+
def can(self, permission: str) -> bool:
|
|
52
|
+
return permission in self.permissions
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def current_principal(request: Request) -> Principal:
|
|
56
|
+
principal = request.state.get("principal")
|
|
57
|
+
if not isinstance(principal, Principal):
|
|
58
|
+
raise Unauthenticated("缺少认证信息")
|
|
59
|
+
return principal
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def require_permission(permission: str) -> Callable[[Request], Principal]:
|
|
63
|
+
def dependency(request: Request) -> Principal:
|
|
64
|
+
principal = current_principal(request)
|
|
65
|
+
if not principal.can(permission):
|
|
66
|
+
raise PermissionDenied(f"缺少权限: {permission}")
|
|
67
|
+
return principal
|
|
68
|
+
|
|
69
|
+
return dependency
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
__all__ = [
|
|
73
|
+
"ROLE_PERMISSIONS",
|
|
74
|
+
"Principal",
|
|
75
|
+
"current_principal",
|
|
76
|
+
"register_role",
|
|
77
|
+
"require_permission",
|
|
78
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""多租户包。"""
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""租户目录:slug → TenantContext。
|
|
2
|
+
|
|
3
|
+
P2 用确定性映射(uuid5)保证可测试;P3 接入 `platform.tenant` 表后替换实现,
|
|
4
|
+
接口不变(`TenantCatalog` 协议)。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from typing import Protocol
|
|
11
|
+
from uuid import NAMESPACE_URL, UUID, uuid5
|
|
12
|
+
|
|
13
|
+
from swiftapi.config.settings import TenantStrategy
|
|
14
|
+
from swiftapi.core.tenant.context import TenantContext
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TenantCatalog(Protocol):
|
|
18
|
+
def get(self, slug: str) -> TenantContext | None: ...
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_SCHEMA_SAFE = re.compile(r"[^a-z0-9_]+")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _schema_name(slug: str, prefix: str) -> str:
|
|
25
|
+
safe = _SCHEMA_SAFE.sub("_", slug.lower()).strip("_") or "tenant"
|
|
26
|
+
return f"{prefix}{safe}"[:63]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class StaticTenantCatalog:
|
|
30
|
+
"""演示/测试用:未知租户视为不存在(404),不做"自动创建"。
|
|
31
|
+
|
|
32
|
+
`schema` / `database` 策略下,租户的物理位置在注册时确定:
|
|
33
|
+
- schema:`schema_prefix + slug`(PostgreSQL schema);
|
|
34
|
+
- database:`database_url_template` 里的 `{tenant}` 替换(每个租户一个库)。
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
strategy: TenantStrategy = TenantStrategy.ROW,
|
|
40
|
+
*,
|
|
41
|
+
schema_prefix: str = "tenant_",
|
|
42
|
+
database_url_template: str | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
self._strategy = strategy
|
|
45
|
+
self._schema_prefix = schema_prefix
|
|
46
|
+
self._database_url_template = database_url_template
|
|
47
|
+
self._known: dict[str, TenantContext] = {}
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def strategy(self) -> TenantStrategy:
|
|
51
|
+
return self._strategy
|
|
52
|
+
|
|
53
|
+
def register(
|
|
54
|
+
self,
|
|
55
|
+
slug: str,
|
|
56
|
+
*,
|
|
57
|
+
schema: str | None = None,
|
|
58
|
+
database_url: str | None = None,
|
|
59
|
+
) -> TenantContext:
|
|
60
|
+
physical_schema = None
|
|
61
|
+
if self._strategy is TenantStrategy.SCHEMA:
|
|
62
|
+
physical_schema = schema or _schema_name(slug, self._schema_prefix)
|
|
63
|
+
resolved_url = database_url
|
|
64
|
+
if self._strategy is TenantStrategy.DATABASE and resolved_url is None:
|
|
65
|
+
if self._database_url_template is None:
|
|
66
|
+
raise ValueError(
|
|
67
|
+
"database 级租户隔离需要 tenant.database_url_template,"
|
|
68
|
+
f"或显式给租户 {slug} 指定 database_url"
|
|
69
|
+
)
|
|
70
|
+
resolved_url = self._database_url_template.replace("{tenant}", slug)
|
|
71
|
+
context = TenantContext(
|
|
72
|
+
id=uuid5(NAMESPACE_URL, f"swiftapi:tenant:{slug}"),
|
|
73
|
+
slug=slug,
|
|
74
|
+
strategy=self._strategy,
|
|
75
|
+
schema=physical_schema,
|
|
76
|
+
database_url=resolved_url,
|
|
77
|
+
)
|
|
78
|
+
self._known[slug] = context
|
|
79
|
+
return context
|
|
80
|
+
|
|
81
|
+
def all(self) -> list[TenantContext]:
|
|
82
|
+
return list(self._known.values())
|
|
83
|
+
|
|
84
|
+
def get(self, slug: str) -> TenantContext | None:
|
|
85
|
+
return self._known.get(slug)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def tenant_id_for(slug: str) -> UUID:
|
|
89
|
+
return uuid5(NAMESPACE_URL, f"swiftapi:tenant:{slug}")
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""租户上下文:请求级不可变对象(架构文档 §17.4)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextvars import ContextVar, Token
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
from swiftapi.config.settings import TenantStrategy
|
|
10
|
+
from swiftapi.core.errors.base import TenantRequired
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True, slots=True)
|
|
14
|
+
class TenantContext:
|
|
15
|
+
id: UUID
|
|
16
|
+
slug: str
|
|
17
|
+
strategy: TenantStrategy = TenantStrategy.ROW
|
|
18
|
+
# schema 级:PostgreSQL schema 名(未加引号)
|
|
19
|
+
schema: str | None = None
|
|
20
|
+
# database 级:该租户独立库的连接串(含密码,禁止 repr/日志)
|
|
21
|
+
database_url: str | None = field(default=None, repr=False)
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def is_row(self) -> bool:
|
|
25
|
+
return self.strategy is TenantStrategy.ROW
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def is_schema(self) -> bool:
|
|
29
|
+
return self.strategy is TenantStrategy.SCHEMA
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def is_database(self) -> bool:
|
|
33
|
+
return self.strategy is TenantStrategy.DATABASE
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_ctx: ContextVar[TenantContext | None] = ContextVar("swiftapi_tenant", default=None)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def bind_tenant(context: TenantContext) -> Token[TenantContext | None]:
|
|
40
|
+
return _ctx.set(context)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def reset_tenant(token: Token[TenantContext | None]) -> None:
|
|
44
|
+
_ctx.reset(token)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def current_tenant() -> TenantContext | None:
|
|
48
|
+
return _ctx.get()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def current_tenant_id() -> UUID:
|
|
52
|
+
"""请求上下文里的租户;未开启多租户时回落到默认租户(不再让业务写 fallback)。"""
|
|
53
|
+
context = _ctx.get()
|
|
54
|
+
if context is not None:
|
|
55
|
+
return context.id
|
|
56
|
+
from swiftapi.config.constants import DEFAULT_TENANT_ID
|
|
57
|
+
|
|
58
|
+
return DEFAULT_TENANT_ID
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def require_tenant() -> TenantContext:
|
|
62
|
+
context = _ctx.get()
|
|
63
|
+
if context is None:
|
|
64
|
+
raise TenantRequired("当前请求没有绑定租户")
|
|
65
|
+
return context
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
__all__ = [
|
|
69
|
+
"TenantContext",
|
|
70
|
+
"bind_tenant",
|
|
71
|
+
"current_tenant",
|
|
72
|
+
"current_tenant_id",
|
|
73
|
+
"require_tenant",
|
|
74
|
+
"reset_tenant",
|
|
75
|
+
]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""查询级隔离:给所有 SELECT 自动注入 tenant_id 条件(架构文档 §17.5)。
|
|
2
|
+
|
|
3
|
+
这是"结构性保证"而非"记得写 where":
|
|
4
|
+
- 默认注入;
|
|
5
|
+
- 只有显式 `execution_options(skip_tenant_filter=True)` 才绕过(平台级/迁移代码)。
|
|
6
|
+
|
|
7
|
+
注意:显式传 `tenant_id` 的 CRUD 仍是主路径(fail closed),本层是纵深防御。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from sqlalchemy import event
|
|
15
|
+
from sqlalchemy.orm import ORMExecuteState, Session, with_loader_criteria
|
|
16
|
+
|
|
17
|
+
from swiftapi.core.db.tenant_model import TenantScopedModel
|
|
18
|
+
from swiftapi.core.tenant.context import current_tenant
|
|
19
|
+
|
|
20
|
+
_installed = False
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def install_tenant_isolation() -> None:
|
|
24
|
+
global _installed
|
|
25
|
+
if _installed:
|
|
26
|
+
return
|
|
27
|
+
_installed = True
|
|
28
|
+
|
|
29
|
+
@event.listens_for(Session, "do_orm_execute")
|
|
30
|
+
def _add_tenant_filter(execute_state: ORMExecuteState) -> None: # pragma: no cover - 事件回调
|
|
31
|
+
if not execute_state.is_select:
|
|
32
|
+
return
|
|
33
|
+
if execute_state.execution_options.get("skip_tenant_filter"):
|
|
34
|
+
return
|
|
35
|
+
context = current_tenant()
|
|
36
|
+
if context is None:
|
|
37
|
+
return
|
|
38
|
+
tenant_id: Any = context.id
|
|
39
|
+
execute_state.statement = execute_state.statement.options(
|
|
40
|
+
with_loader_criteria(
|
|
41
|
+
TenantScopedModel,
|
|
42
|
+
lambda cls: cls.tenant_id == tenant_id,
|
|
43
|
+
include_aliases=True,
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
__all__ = ["install_tenant_isolation"]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""租户解析:JWT > path > subdomain > header(架构文档 §17.3)。
|
|
2
|
+
|
|
3
|
+
当前实现覆盖 path / subdomain / header;JWT claim 由 P4 的认证中间件写入
|
|
4
|
+
`request.state["tenant_claim"]` 后再优先使用(此处已预留读取)。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from swiftapi.config.settings import Settings, TenantResolver
|
|
10
|
+
from swiftapi.core.http.request import Request
|
|
11
|
+
from swiftapi.core.tenant.catalog import TenantCatalog
|
|
12
|
+
from swiftapi.core.tenant.context import TenantContext
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TenantResolverService:
|
|
16
|
+
def __init__(self, settings: Settings, catalog: TenantCatalog) -> None:
|
|
17
|
+
self.settings = settings
|
|
18
|
+
self.catalog = catalog
|
|
19
|
+
|
|
20
|
+
def resolve(self, request: Request) -> TenantContext | None:
|
|
21
|
+
sources = self.settings.tenant.resolver
|
|
22
|
+
|
|
23
|
+
claim = request.state.get("tenant_claim")
|
|
24
|
+
if claim and TenantResolver.JWT in sources:
|
|
25
|
+
return self.catalog.get(str(claim))
|
|
26
|
+
|
|
27
|
+
if TenantResolver.PATH in sources:
|
|
28
|
+
# path_prefix 形如 "/t/{tenant}":取占位符之前的字面量段
|
|
29
|
+
literal = self.settings.tenant.path_prefix.strip("/").split("{")[0].strip("/")
|
|
30
|
+
parts = request.path.strip("/").split("/")
|
|
31
|
+
if literal and parts[0] == literal and len(parts) > 1:
|
|
32
|
+
return self.catalog.get(parts[1])
|
|
33
|
+
|
|
34
|
+
if TenantResolver.SUBDOMAIN in sources:
|
|
35
|
+
host = (request.headers.get("host") or "").split(":")[0]
|
|
36
|
+
root = self.settings.tenant.root_domain or ""
|
|
37
|
+
if root and host.endswith(f".{root}"):
|
|
38
|
+
return self.catalog.get(host[: -(len(root) + 1)])
|
|
39
|
+
|
|
40
|
+
if TenantResolver.HEADER in sources and self.settings.tenant.trust_header:
|
|
41
|
+
slug = request.headers.get(self.settings.tenant.header_name)
|
|
42
|
+
if slug:
|
|
43
|
+
return self.catalog.get(slug)
|
|
44
|
+
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
__all__ = ["TenantResolverService"]
|
|
File without changes
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""契约基类:所有请求/响应/事件模型都继承它(架构文档 §14.2)。
|
|
2
|
+
|
|
3
|
+
`extra="forbid"` 是最重要的一条:多传字段直接 422,而不是静默丢弃——
|
|
4
|
+
静默丢弃会让前端拼错的字段永远发现不了。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, ConfigDict
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class StrictModel(BaseModel):
|
|
13
|
+
model_config = ConfigDict(
|
|
14
|
+
extra="forbid",
|
|
15
|
+
str_strip_whitespace=True,
|
|
16
|
+
validate_assignment=True,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class OutModel(StrictModel):
|
|
21
|
+
"""响应模型基类:允许直接从 ORM 对象构造(`OutModel.model_validate(obj)`)。"""
|
|
22
|
+
|
|
23
|
+
model_config = ConfigDict(extra="forbid", from_attributes=True)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class EventModel(StrictModel):
|
|
27
|
+
"""领域事件:不可变,避免消费端误改。"""
|
|
28
|
+
|
|
29
|
+
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
__all__ = ["EventModel", "OutModel", "StrictModel"]
|
swiftapi/db.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""公共模型 API:业务代码只从这里导入基类与 Mixin。
|
|
2
|
+
|
|
3
|
+
from swiftapi.db import BaseModel, TenantScopedModel, SoftDeleteMixin
|
|
4
|
+
|
|
5
|
+
为什么需要这层门面:`core/db` 是内核实现,业务模块不应依赖其内部路径;
|
|
6
|
+
同时把"两个 BaseModel"的分工固定在唯一入口上(架构文档 §17.5.7)。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from swiftapi.core.db.base_model import NAMING_CONVENTION, BaseModel
|
|
12
|
+
from swiftapi.core.db.crud import CRUDBase
|
|
13
|
+
from swiftapi.core.db.mixins import AuditMixin, SoftDeleteMixin, TimestampMixin, VersionMixin
|
|
14
|
+
from swiftapi.core.db.snapshot import ColumnSnapshot, TableSnapshot
|
|
15
|
+
from swiftapi.core.db.tenant_model import TenantScopedModel
|
|
16
|
+
from swiftapi.core.db.types import (
|
|
17
|
+
JSONType,
|
|
18
|
+
LongText,
|
|
19
|
+
Money,
|
|
20
|
+
ShortText,
|
|
21
|
+
TZDateTime,
|
|
22
|
+
UUIDType,
|
|
23
|
+
)
|
|
24
|
+
from swiftapi.core.db.unit_of_work import UnitOfWork
|
|
25
|
+
|
|
26
|
+
# 短别名:偏好简洁写法的团队可用 `Model` / `TenantModel`
|
|
27
|
+
Model = BaseModel
|
|
28
|
+
TenantModel = TenantScopedModel
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"NAMING_CONVENTION",
|
|
32
|
+
"AuditMixin",
|
|
33
|
+
"BaseModel",
|
|
34
|
+
"CRUDBase",
|
|
35
|
+
"ColumnSnapshot",
|
|
36
|
+
"JSONType",
|
|
37
|
+
"LongText",
|
|
38
|
+
"Model",
|
|
39
|
+
"Money",
|
|
40
|
+
"ShortText",
|
|
41
|
+
"SoftDeleteMixin",
|
|
42
|
+
"TZDateTime",
|
|
43
|
+
"TableSnapshot",
|
|
44
|
+
"TenantModel",
|
|
45
|
+
"TenantScopedModel",
|
|
46
|
+
"TimestampMixin",
|
|
47
|
+
"UUIDType",
|
|
48
|
+
"UnitOfWork",
|
|
49
|
+
"VersionMixin",
|
|
50
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""users 模块:五层结构(api / schema / model / crud / service)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from swiftapi.core.http import Router
|
|
6
|
+
from swiftapi.modules.users.api.users import router as _users
|
|
7
|
+
|
|
8
|
+
router = Router(prefix="/users")
|
|
9
|
+
router.include_router(_users)
|
|
10
|
+
|
|
11
|
+
__all__ = ["router"]
|
|
File without changes
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""用户接口:只做 HTTP 适配,零业务逻辑。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Annotated
|
|
6
|
+
from uuid import UUID
|
|
7
|
+
|
|
8
|
+
from swiftapi.core.http import Depends, Query, Request, Response, Router
|
|
9
|
+
from swiftapi.core.security.principal import Principal, require_permission
|
|
10
|
+
from swiftapi.db import UnitOfWork
|
|
11
|
+
from swiftapi.modules.users.mappers import to_user_out
|
|
12
|
+
from swiftapi.modules.users.schema.user import UserCreate, UserOut, UserUpdate
|
|
13
|
+
from swiftapi.modules.users.service.user import UserService
|
|
14
|
+
|
|
15
|
+
router = Router(tags=("users",))
|
|
16
|
+
|
|
17
|
+
TenantId = Annotated[UUID, "当前租户"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _tenant_id(request: Request) -> UUID:
|
|
21
|
+
from uuid import UUID as _UUID
|
|
22
|
+
|
|
23
|
+
from swiftapi.config.constants import DEFAULT_TENANT_ID
|
|
24
|
+
from swiftapi.core.tenant.context import current_tenant
|
|
25
|
+
|
|
26
|
+
context = current_tenant()
|
|
27
|
+
if context is not None:
|
|
28
|
+
return context.id
|
|
29
|
+
fallback = request.state.get("tenant_id")
|
|
30
|
+
return _UUID(str(fallback)) if fallback else DEFAULT_TENANT_ID
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@router.get("", summary="用户列表", response_model=None)
|
|
34
|
+
async def list_users(
|
|
35
|
+
request: Request,
|
|
36
|
+
uow: Annotated[UnitOfWork, Depends("uow")],
|
|
37
|
+
principal: Annotated[Principal, Depends(require_permission("users:read"))],
|
|
38
|
+
limit: Annotated[int, Query(20)] = 20,
|
|
39
|
+
offset: Annotated[int, Query(0)] = 0,
|
|
40
|
+
status: Annotated[str | None, Query(None)] = None,
|
|
41
|
+
) -> dict[str, object]:
|
|
42
|
+
rows, total = await UserService(uow).list(
|
|
43
|
+
tenant_id=_tenant_id(request),
|
|
44
|
+
principal=principal,
|
|
45
|
+
limit=limit,
|
|
46
|
+
offset=offset,
|
|
47
|
+
status=status,
|
|
48
|
+
)
|
|
49
|
+
return {
|
|
50
|
+
"items": [to_user_out(row).model_dump(mode="json") for row in rows],
|
|
51
|
+
"total": total,
|
|
52
|
+
"limit": limit,
|
|
53
|
+
"offset": offset,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@router.post("", summary="创建用户", status_code=201, response_model=UserOut)
|
|
58
|
+
async def create_user(
|
|
59
|
+
request: Request,
|
|
60
|
+
payload: UserCreate,
|
|
61
|
+
uow: Annotated[UnitOfWork, Depends("uow")],
|
|
62
|
+
principal: Annotated[Principal, Depends(require_permission("users:write"))],
|
|
63
|
+
) -> UserOut:
|
|
64
|
+
user = await UserService(uow).create(
|
|
65
|
+
payload, tenant_id=_tenant_id(request), principal=principal
|
|
66
|
+
)
|
|
67
|
+
return to_user_out(user)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@router.get("/{user_id}", summary="用户详情", response_model=UserOut)
|
|
71
|
+
async def get_user(
|
|
72
|
+
request: Request,
|
|
73
|
+
user_id: UUID,
|
|
74
|
+
uow: Annotated[UnitOfWork, Depends("uow")],
|
|
75
|
+
principal: Annotated[Principal, Depends(require_permission("users:read"))],
|
|
76
|
+
) -> UserOut:
|
|
77
|
+
user = await UserService(uow).get(
|
|
78
|
+
user_id, tenant_id=_tenant_id(request), principal=principal
|
|
79
|
+
)
|
|
80
|
+
return to_user_out(user)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@router.patch("/{user_id}", summary="更新用户", response_model=UserOut)
|
|
84
|
+
async def update_user(
|
|
85
|
+
request: Request,
|
|
86
|
+
user_id: UUID,
|
|
87
|
+
payload: UserUpdate,
|
|
88
|
+
uow: Annotated[UnitOfWork, Depends("uow")],
|
|
89
|
+
principal: Annotated[Principal, Depends(require_permission("users:write"))],
|
|
90
|
+
) -> UserOut:
|
|
91
|
+
user = await UserService(uow).update(
|
|
92
|
+
user_id, payload, tenant_id=_tenant_id(request), principal=principal
|
|
93
|
+
)
|
|
94
|
+
return to_user_out(user)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@router.delete("/{user_id}", summary="删除用户", status_code=204)
|
|
98
|
+
async def delete_user(
|
|
99
|
+
request: Request,
|
|
100
|
+
user_id: UUID,
|
|
101
|
+
uow: Annotated[UnitOfWork, Depends("uow")],
|
|
102
|
+
principal: Annotated[Principal, Depends(require_permission("users:write"))],
|
|
103
|
+
) -> Response:
|
|
104
|
+
await UserService(uow).delete(
|
|
105
|
+
user_id, tenant_id=_tenant_id(request), principal=principal
|
|
106
|
+
)
|
|
107
|
+
return Response(b"", status_code=204)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
__all__ = ["router"]
|
|
File without changes
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""用户数据访问:只拼查询,不含业务规则。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from uuid import UUID
|
|
6
|
+
|
|
7
|
+
from sqlalchemy import select
|
|
8
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
9
|
+
|
|
10
|
+
from swiftapi.db import CRUDBase
|
|
11
|
+
from swiftapi.modules.users.model.user import User
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CRUDUser(CRUDBase[User]):
|
|
15
|
+
async def get_by_email(
|
|
16
|
+
self, session: AsyncSession, email: str, *, tenant_id: UUID
|
|
17
|
+
) -> User | None:
|
|
18
|
+
stmt = select(User).where(User.email == email, User.deleted_at.is_(None))
|
|
19
|
+
stmt = self._scoped(stmt, tenant_id)
|
|
20
|
+
return (await session.execute(stmt)).scalar_one_or_none()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
__all__ = ["CRUDUser"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""用户域错误:引用全局错误码,不重复定义。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from swiftapi.core.errors.base import DomainError
|
|
6
|
+
from swiftapi.core.errors.codes import ErrorCode
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class UserEmailTaken(DomainError):
|
|
10
|
+
def __init__(self, email: str) -> None:
|
|
11
|
+
super().__init__(ErrorCode.USER_EMAIL_TAKEN, f"{email} 已注册")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class UserNotFound(DomainError):
|
|
15
|
+
def __init__(self, user_id: object) -> None:
|
|
16
|
+
super().__init__(ErrorCode.USER_NOT_FOUND, f"用户 {user_id} 不存在")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class WeakPassword(DomainError):
|
|
20
|
+
def __init__(self) -> None:
|
|
21
|
+
super().__init__(ErrorCode.USER_WEAK_PASSWORD, "密码强度不足")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
__all__ = ["UserEmailTaken", "UserNotFound", "WeakPassword"]
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""ORM → DTO 显式映射:白名单字段,避免内部列(password_hash)泄漏。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from swiftapi.modules.users.model.user import User
|
|
6
|
+
from swiftapi.modules.users.schema.user import UserOut
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def to_user_out(user: User) -> UserOut:
|
|
10
|
+
return UserOut(
|
|
11
|
+
id=user.id,
|
|
12
|
+
email=user.email,
|
|
13
|
+
display_name=user.display_name,
|
|
14
|
+
status=user.status,
|
|
15
|
+
created_at=user.created_at,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
__all__ = ["to_user_out"]
|
|
File without changes
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""用户表模型(租户表 → TenantScopedModel)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from enum import StrEnum
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
from sqlalchemy.orm import Mapped, mapped_column
|
|
10
|
+
|
|
11
|
+
from swiftapi.db import (
|
|
12
|
+
ShortText,
|
|
13
|
+
SoftDeleteMixin,
|
|
14
|
+
TenantScopedModel,
|
|
15
|
+
TimestampMixin,
|
|
16
|
+
UUIDType,
|
|
17
|
+
VersionMixin,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class UserStatus(StrEnum):
|
|
22
|
+
ACTIVE = "active"
|
|
23
|
+
DISABLED = "disabled"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class User(TenantScopedModel, TimestampMixin, SoftDeleteMixin, VersionMixin):
|
|
27
|
+
__tablename__ = "user"
|
|
28
|
+
__module_schema__ = "users"
|
|
29
|
+
|
|
30
|
+
id: Mapped[UUID] = mapped_column(UUIDType, primary_key=True, default=uuid.uuid4)
|
|
31
|
+
email: Mapped[str] = mapped_column(ShortText(254), index=True)
|
|
32
|
+
display_name: Mapped[str] = mapped_column(ShortText(64))
|
|
33
|
+
status: Mapped[str] = mapped_column(ShortText(16), default=UserStatus.ACTIVE.value)
|
|
34
|
+
password_hash: Mapped[str] = mapped_column(ShortText(255))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
__all__ = ["User", "UserStatus"]
|