khitish-backend-core 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.
- khitish_backend/__init__.py +15 -0
- khitish_backend/adapters/__init__.py +5 -0
- khitish_backend/adapters/database/__init__.py +8 -0
- khitish_backend/adapters/database/django_repo.py +96 -0
- khitish_backend/adapters/database/sqlalchemy_repo.py +106 -0
- khitish_backend/adapters/django/__init__.py +7 -0
- khitish_backend/adapters/django/admin.py +118 -0
- khitish_backend/adapters/django/apps.py +23 -0
- khitish_backend/adapters/django/exceptions.py +57 -0
- khitish_backend/adapters/django/middleware.py +77 -0
- khitish_backend/adapters/django/migrations/0001_initial.py +365 -0
- khitish_backend/adapters/django/migrations/__init__.py +3 -0
- khitish_backend/adapters/django/models.py +314 -0
- khitish_backend/adapters/django/pagination.py +46 -0
- khitish_backend/adapters/django/permissions.py +71 -0
- khitish_backend/adapters/django/serializers.py +256 -0
- khitish_backend/adapters/django/settings.py +85 -0
- khitish_backend/adapters/django/signals.py +29 -0
- khitish_backend/adapters/django/urls.py +28 -0
- khitish_backend/adapters/django/views.py +324 -0
- khitish_backend/adapters/fastapi/__init__.py +19 -0
- khitish_backend/adapters/fastapi/app.py +118 -0
- khitish_backend/adapters/fastapi/dependencies.py +212 -0
- khitish_backend/adapters/fastapi/exceptions.py +94 -0
- khitish_backend/adapters/fastapi/middleware.py +76 -0
- khitish_backend/adapters/fastapi/routers/__init__.py +17 -0
- khitish_backend/adapters/fastapi/routers/auth.py +238 -0
- khitish_backend/adapters/fastapi/routers/health.py +39 -0
- khitish_backend/adapters/fastapi/routers/organizations.py +76 -0
- khitish_backend/adapters/fastapi/routers/users.py +92 -0
- khitish_backend/adapters/fastapi/schemas.py +195 -0
- khitish_backend/application/__init__.py +13 -0
- khitish_backend/application/events/__init__.py +830 -0
- khitish_backend/application/interfaces/__init__.py +610 -0
- khitish_backend/application/services/__init__.py +9 -0
- khitish_backend/application/use_cases/__init__.py +396 -0
- khitish_backend/cli/__init__.py +7 -0
- khitish_backend/cli/commands/__init__.py +7 -0
- khitish_backend/cli/commands/create.py +491 -0
- khitish_backend/cli/main.py +30 -0
- khitish_backend/core/__init__.py +9 -0
- khitish_backend/core/config/__init__.py +244 -0
- khitish_backend/core/contracts/__init__.py +761 -0
- khitish_backend/core/exceptions/__init__.py +1117 -0
- khitish_backend/core/logging/__init__.py +380 -0
- khitish_backend/core/observability/__init__.py +456 -0
- khitish_backend/core/security/__init__.py +638 -0
- khitish_backend/core/types/__init__.py +391 -0
- khitish_backend/core/utils/__init__.py +531 -0
- khitish_backend/infrastructure/__init__.py +5 -0
- khitish_backend/infrastructure/email/__init__.py +7 -0
- khitish_backend/infrastructure/email/smtp.py +109 -0
- khitish_backend/infrastructure/payments/__init__.py +7 -0
- khitish_backend/infrastructure/payments/stripe_adapter.py +93 -0
- khitish_backend/infrastructure/postgres/__init__.py +19 -0
- khitish_backend/infrastructure/postgres/engine.py +174 -0
- khitish_backend/infrastructure/queue/__init__.py +7 -0
- khitish_backend/infrastructure/queue/celery_app.py +57 -0
- khitish_backend/infrastructure/redis/__init__.py +11 -0
- khitish_backend/infrastructure/redis/client.py +219 -0
- khitish_backend/infrastructure/storage/__init__.py +16 -0
- khitish_backend/infrastructure/storage/local.py +92 -0
- khitish_backend/infrastructure/storage/s3.py +97 -0
- khitish_backend/infrastructure/telemetry/__init__.py +11 -0
- khitish_backend/infrastructure/telemetry/otel.py +94 -0
- khitish_backend/modules/__init__.py +5 -0
- khitish_backend/modules/audit/__init__.py +13 -0
- khitish_backend/modules/audit/models.py +103 -0
- khitish_backend/modules/audit/service.py +219 -0
- khitish_backend/modules/authentication/__init__.py +37 -0
- khitish_backend/modules/authentication/models.py +205 -0
- khitish_backend/modules/authentication/service.py +229 -0
- khitish_backend/modules/authorization/__init__.py +23 -0
- khitish_backend/modules/authorization/models.py +126 -0
- khitish_backend/modules/authorization/service.py +333 -0
- khitish_backend/modules/background_jobs/__init__.py +23 -0
- khitish_backend/modules/background_jobs/config.py +60 -0
- khitish_backend/modules/background_jobs/tasks.py +115 -0
- khitish_backend/modules/email/__init__.py +21 -0
- khitish_backend/modules/email/models.py +77 -0
- khitish_backend/modules/email/service.py +208 -0
- khitish_backend/modules/file_storage/__init__.py +17 -0
- khitish_backend/modules/file_storage/models.py +93 -0
- khitish_backend/modules/file_storage/service.py +190 -0
- khitish_backend/modules/notifications/__init__.py +19 -0
- khitish_backend/modules/notifications/models.py +72 -0
- khitish_backend/modules/notifications/service.py +218 -0
- khitish_backend/modules/organizations/__init__.py +21 -0
- khitish_backend/modules/organizations/models.py +289 -0
- khitish_backend/modules/payments/__init__.py +31 -0
- khitish_backend/modules/payments/models.py +195 -0
- khitish_backend/modules/payments/providers/__init__.py +7 -0
- khitish_backend/modules/payments/providers/mock.py +73 -0
- khitish_backend/modules/payments/service.py +283 -0
- khitish_backend/modules/users/__init__.py +23 -0
- khitish_backend/modules/users/models.py +329 -0
- khitish_backend/modules/users/service.py +212 -0
- khitish_backend/version.py +4 -0
- khitish_backend_core-0.1.0.dist-info/METADATA +204 -0
- khitish_backend_core-0.1.0.dist-info/RECORD +103 -0
- khitish_backend_core-0.1.0.dist-info/WHEEL +4 -0
- khitish_backend_core-0.1.0.dist-info/entry_points.txt +2 -0
- khitish_backend_core-0.1.0.dist-info/licenses/LICENSE +6 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Khitish Backend Core — enterprise-grade Python backend platform.
|
|
2
|
+
|
|
3
|
+
Provides authentication, authorization, configuration, storage,
|
|
4
|
+
email, payment, audit, and notification abstractions for Django
|
|
5
|
+
and FastAPI applications.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from khitish_backend.version import __version__, __version_info__
|
|
11
|
+
|
|
12
|
+
__all__: list[str] = [
|
|
13
|
+
"__version__",
|
|
14
|
+
"__version_info__",
|
|
15
|
+
]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Database repository adapters for SQLAlchemy 2.x and Django ORM."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from khitish_backend.adapters.database.django_repo import DjangoRepository
|
|
6
|
+
from khitish_backend.adapters.database.sqlalchemy_repo import SQLAlchemyRepository
|
|
7
|
+
|
|
8
|
+
__all__ = ["DjangoRepository", "SQLAlchemyRepository"]
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Generic Django ORM repository implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Generic, TypeVar
|
|
6
|
+
|
|
7
|
+
import structlog
|
|
8
|
+
|
|
9
|
+
from khitish_backend.core.exceptions import NotFoundError
|
|
10
|
+
from khitish_backend.core.types import Paginated, PaginationParams
|
|
11
|
+
|
|
12
|
+
__all__ = ["DjangoRepository"]
|
|
13
|
+
|
|
14
|
+
T = TypeVar("T")
|
|
15
|
+
ID = TypeVar("ID")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DjangoRepository(Generic[T, ID]):
|
|
19
|
+
"""Generic synchronous Django ORM repository."""
|
|
20
|
+
|
|
21
|
+
model_class: type[Any]
|
|
22
|
+
|
|
23
|
+
def __init__(self) -> None:
|
|
24
|
+
self._logger = structlog.get_logger(__name__)
|
|
25
|
+
|
|
26
|
+
def _get_queryset(self) -> Any:
|
|
27
|
+
return self.model_class.objects.all()
|
|
28
|
+
|
|
29
|
+
def get(self, id: ID) -> T | None:
|
|
30
|
+
"""Fetch model instance by primary key."""
|
|
31
|
+
try:
|
|
32
|
+
return self._get_queryset().get(pk=id) # type: ignore[no-any-return]
|
|
33
|
+
except self.model_class.DoesNotExist:
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
def get_or_raise(self, id: ID) -> T:
|
|
37
|
+
"""Fetch model instance or raise :class:`NotFoundError`."""
|
|
38
|
+
obj = self.get(id)
|
|
39
|
+
if obj is None:
|
|
40
|
+
raise NotFoundError(
|
|
41
|
+
resource_type=self.model_class.__name__,
|
|
42
|
+
resource_id=str(id),
|
|
43
|
+
)
|
|
44
|
+
return obj
|
|
45
|
+
|
|
46
|
+
def list(
|
|
47
|
+
self,
|
|
48
|
+
filters: dict[str, Any] | None = None,
|
|
49
|
+
pagination: PaginationParams | None = None,
|
|
50
|
+
order_by: str | None = None,
|
|
51
|
+
) -> Paginated[T]:
|
|
52
|
+
"""List model instances with optional filters, ordering, and pagination."""
|
|
53
|
+
params = (pagination or PaginationParams()).validate()
|
|
54
|
+
qs = self._get_queryset()
|
|
55
|
+
if filters:
|
|
56
|
+
qs = qs.filter(**{k: v for k, v in filters.items() if v is not None})
|
|
57
|
+
if order_by:
|
|
58
|
+
qs = qs.order_by(order_by)
|
|
59
|
+
|
|
60
|
+
total = int(qs.count())
|
|
61
|
+
items = list(qs[params.offset : params.offset + params.limit])
|
|
62
|
+
return params.build_paginated(items, total)
|
|
63
|
+
|
|
64
|
+
def create(self, **kwargs: Any) -> T:
|
|
65
|
+
"""Create, validate, and save a new model instance."""
|
|
66
|
+
obj = self.model_class(**kwargs)
|
|
67
|
+
obj.full_clean()
|
|
68
|
+
obj.save()
|
|
69
|
+
return obj # type: ignore[no-any-return]
|
|
70
|
+
|
|
71
|
+
def update(self, obj: Any, **kwargs: Any) -> T:
|
|
72
|
+
"""Update fields on *obj*, validate, and save."""
|
|
73
|
+
for key, value in kwargs.items():
|
|
74
|
+
setattr(obj, key, value)
|
|
75
|
+
obj.full_clean()
|
|
76
|
+
obj.save()
|
|
77
|
+
return obj # type: ignore[no-any-return]
|
|
78
|
+
|
|
79
|
+
def delete(self, id: ID) -> bool:
|
|
80
|
+
"""Delete instance by primary key."""
|
|
81
|
+
obj = self.get(id)
|
|
82
|
+
if obj is None:
|
|
83
|
+
return False
|
|
84
|
+
obj.delete() # type: ignore[attr-defined]
|
|
85
|
+
return True
|
|
86
|
+
|
|
87
|
+
def exists(self, id: ID) -> bool:
|
|
88
|
+
"""Return True if instance exists."""
|
|
89
|
+
return bool(self._get_queryset().filter(pk=id).exists())
|
|
90
|
+
|
|
91
|
+
def count(self, filters: dict[str, Any] | None = None) -> int:
|
|
92
|
+
"""Count instances matching *filters*."""
|
|
93
|
+
qs = self._get_queryset()
|
|
94
|
+
if filters:
|
|
95
|
+
qs = qs.filter(**{k: v for k, v in filters.items() if v is not None})
|
|
96
|
+
return int(qs.count())
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Generic SQLAlchemy 2.x async repository implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Generic, TypeVar
|
|
6
|
+
|
|
7
|
+
import structlog
|
|
8
|
+
from sqlalchemy import func, select
|
|
9
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
10
|
+
|
|
11
|
+
from khitish_backend.core.exceptions import NotFoundError
|
|
12
|
+
from khitish_backend.core.types import Paginated, PaginationParams
|
|
13
|
+
|
|
14
|
+
__all__ = ["SQLAlchemyRepository"]
|
|
15
|
+
|
|
16
|
+
T = TypeVar("T")
|
|
17
|
+
ID = TypeVar("ID")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SQLAlchemyRepository(Generic[T, ID]):
|
|
21
|
+
"""Generic SQLAlchemy 2.x async repository."""
|
|
22
|
+
|
|
23
|
+
model_class: type[T]
|
|
24
|
+
|
|
25
|
+
def __init__(self, session: AsyncSession) -> None:
|
|
26
|
+
self._session = session
|
|
27
|
+
self._logger = structlog.get_logger(__name__)
|
|
28
|
+
|
|
29
|
+
async def get(self, id: ID) -> T | None:
|
|
30
|
+
"""Fetch entity by primary key."""
|
|
31
|
+
return await self._session.get(self.model_class, id)
|
|
32
|
+
|
|
33
|
+
async def get_or_raise(self, id: ID) -> T:
|
|
34
|
+
"""Fetch entity by primary key or raise :class:`NotFoundError`."""
|
|
35
|
+
obj = await self.get(id)
|
|
36
|
+
if obj is None:
|
|
37
|
+
raise NotFoundError(
|
|
38
|
+
resource_type=self.model_class.__name__,
|
|
39
|
+
resource_id=str(id),
|
|
40
|
+
)
|
|
41
|
+
return obj
|
|
42
|
+
|
|
43
|
+
async def list(
|
|
44
|
+
self,
|
|
45
|
+
filters: dict[str, Any] | None = None,
|
|
46
|
+
pagination: PaginationParams | None = None,
|
|
47
|
+
order_by: str | None = None,
|
|
48
|
+
) -> Paginated[T]:
|
|
49
|
+
"""List entities with optional equality filters and pagination."""
|
|
50
|
+
params = (pagination or PaginationParams()).validate()
|
|
51
|
+
|
|
52
|
+
count_stmt = select(func.count()).select_from(self.model_class)
|
|
53
|
+
stmt = select(self.model_class)
|
|
54
|
+
if filters:
|
|
55
|
+
for key, value in filters.items():
|
|
56
|
+
if hasattr(self.model_class, key) and value is not None:
|
|
57
|
+
col = getattr(self.model_class, key)
|
|
58
|
+
count_stmt = count_stmt.where(col == value)
|
|
59
|
+
stmt = stmt.where(col == value)
|
|
60
|
+
|
|
61
|
+
if order_by:
|
|
62
|
+
desc = order_by.startswith("-")
|
|
63
|
+
field_name = order_by.lstrip("-")
|
|
64
|
+
if hasattr(self.model_class, field_name):
|
|
65
|
+
col = getattr(self.model_class, field_name)
|
|
66
|
+
stmt = stmt.order_by(col.desc() if desc else col.asc())
|
|
67
|
+
|
|
68
|
+
total = int((await self._session.execute(count_stmt)).scalar_one())
|
|
69
|
+
stmt = stmt.offset(params.offset).limit(params.limit)
|
|
70
|
+
items = list((await self._session.execute(stmt)).scalars().all())
|
|
71
|
+
return params.build_paginated(items, total)
|
|
72
|
+
|
|
73
|
+
async def create(self, obj: T) -> T:
|
|
74
|
+
"""Persist a new ORM instance."""
|
|
75
|
+
self._session.add(obj)
|
|
76
|
+
await self._session.flush()
|
|
77
|
+
await self._session.refresh(obj)
|
|
78
|
+
return obj
|
|
79
|
+
|
|
80
|
+
async def update(self, obj: T) -> T:
|
|
81
|
+
"""Flush and refresh changes on an ORM instance."""
|
|
82
|
+
await self._session.flush()
|
|
83
|
+
await self._session.refresh(obj)
|
|
84
|
+
return obj
|
|
85
|
+
|
|
86
|
+
async def delete(self, id: ID) -> bool:
|
|
87
|
+
"""Delete entity by primary key."""
|
|
88
|
+
obj = await self.get(id)
|
|
89
|
+
if obj is None:
|
|
90
|
+
return False
|
|
91
|
+
await self._session.delete(obj)
|
|
92
|
+
await self._session.flush()
|
|
93
|
+
return True
|
|
94
|
+
|
|
95
|
+
async def exists(self, id: ID) -> bool:
|
|
96
|
+
"""Return True if entity exists."""
|
|
97
|
+
return await self.get(id) is not None
|
|
98
|
+
|
|
99
|
+
async def count(self, filters: dict[str, Any] | None = None) -> int:
|
|
100
|
+
"""Count entities matching optional *filters*."""
|
|
101
|
+
stmt = select(func.count()).select_from(self.model_class)
|
|
102
|
+
if filters:
|
|
103
|
+
for key, value in filters.items():
|
|
104
|
+
if hasattr(self.model_class, key) and value is not None:
|
|
105
|
+
stmt = stmt.where(getattr(self.model_class, key) == value)
|
|
106
|
+
return int((await self._session.execute(stmt)).scalar_one())
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Django Admin registrations for Khitish Backend Core models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from django.contrib import admin
|
|
6
|
+
from django.contrib.auth.admin import UserAdmin
|
|
7
|
+
from django.utils.translation import gettext_lazy as _
|
|
8
|
+
|
|
9
|
+
from khitish_backend.adapters.django.models import (
|
|
10
|
+
AuditLog,
|
|
11
|
+
FileRecord,
|
|
12
|
+
KhitishUser,
|
|
13
|
+
Organization,
|
|
14
|
+
PaymentRecord,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"AuditLogAdmin",
|
|
19
|
+
"FileRecordAdmin",
|
|
20
|
+
"KhitishUserAdmin",
|
|
21
|
+
"OrganizationAdmin",
|
|
22
|
+
"PaymentRecordAdmin",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@admin.register(KhitishUser)
|
|
27
|
+
class KhitishUserAdmin(UserAdmin):
|
|
28
|
+
"""Admin configuration for :class:`KhitishUser`."""
|
|
29
|
+
|
|
30
|
+
list_display = (
|
|
31
|
+
"email",
|
|
32
|
+
"username",
|
|
33
|
+
"full_name",
|
|
34
|
+
"status",
|
|
35
|
+
"is_email_verified",
|
|
36
|
+
"is_active",
|
|
37
|
+
"created_at",
|
|
38
|
+
)
|
|
39
|
+
list_filter = ("status", "is_email_verified", "is_active", "is_staff")
|
|
40
|
+
search_fields = ("email", "username", "first_name", "last_name")
|
|
41
|
+
ordering = ("-created_at",)
|
|
42
|
+
readonly_fields = ("id", "created_at", "updated_at", "last_login")
|
|
43
|
+
|
|
44
|
+
fieldsets = (
|
|
45
|
+
(None, {"fields": ("id", "email", "username", "password")}),
|
|
46
|
+
(
|
|
47
|
+
_("Personal info"),
|
|
48
|
+
{"fields": ("first_name", "last_name", "bio", "phone", "timezone", "locale")},
|
|
49
|
+
),
|
|
50
|
+
(_("Status"), {"fields": ("status", "is_email_verified", "is_active")}),
|
|
51
|
+
(_("Permissions"), {"fields": ("is_staff", "is_superuser", "groups", "user_permissions")}),
|
|
52
|
+
(
|
|
53
|
+
_("Important dates"),
|
|
54
|
+
{"fields": ("last_login", "created_at", "updated_at", "deleted_at")},
|
|
55
|
+
),
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
add_fieldsets = (
|
|
59
|
+
(
|
|
60
|
+
None,
|
|
61
|
+
{
|
|
62
|
+
"classes": ("wide",),
|
|
63
|
+
"fields": ("email", "username", "password1", "password2"),
|
|
64
|
+
},
|
|
65
|
+
),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@admin.register(AuditLog)
|
|
70
|
+
class AuditLogAdmin(admin.ModelAdmin): # type: ignore[type-arg]
|
|
71
|
+
"""Read-only admin view for :class:`AuditLog`."""
|
|
72
|
+
|
|
73
|
+
list_display = (
|
|
74
|
+
"event_type",
|
|
75
|
+
"actor_email",
|
|
76
|
+
"resource_type",
|
|
77
|
+
"resource_id",
|
|
78
|
+
"severity",
|
|
79
|
+
"created_at",
|
|
80
|
+
)
|
|
81
|
+
list_filter = ("event_type", "severity", "resource_type")
|
|
82
|
+
search_fields = ("actor_email", "resource_id", "event_type")
|
|
83
|
+
readonly_fields = tuple(f.name for f in AuditLog._meta.fields)
|
|
84
|
+
ordering = ("-created_at",)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@admin.register(Organization)
|
|
88
|
+
class OrganizationAdmin(admin.ModelAdmin): # type: ignore[type-arg]
|
|
89
|
+
"""Admin configuration for :class:`Organization`."""
|
|
90
|
+
|
|
91
|
+
list_display = ("name", "slug", "plan", "status", "created_at")
|
|
92
|
+
list_filter = ("plan", "status")
|
|
93
|
+
search_fields = ("name", "slug")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@admin.register(PaymentRecord)
|
|
97
|
+
class PaymentRecordAdmin(admin.ModelAdmin): # type: ignore[type-arg]
|
|
98
|
+
"""Admin configuration for :class:`PaymentRecord`."""
|
|
99
|
+
|
|
100
|
+
list_display = ("id", "provider", "status", "amount_cents", "currency", "created_at")
|
|
101
|
+
list_filter = ("provider", "status", "currency")
|
|
102
|
+
readonly_fields = ("id", "provider_id", "created_at", "updated_at")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@admin.register(FileRecord)
|
|
106
|
+
class FileRecordAdmin(admin.ModelAdmin): # type: ignore[type-arg]
|
|
107
|
+
"""Admin configuration for :class:`FileRecord`."""
|
|
108
|
+
|
|
109
|
+
list_display = (
|
|
110
|
+
"filename",
|
|
111
|
+
"content_type",
|
|
112
|
+
"size",
|
|
113
|
+
"storage_backend",
|
|
114
|
+
"is_public",
|
|
115
|
+
"created_at",
|
|
116
|
+
)
|
|
117
|
+
list_filter = ("storage_backend", "is_public")
|
|
118
|
+
search_fields = ("filename", "key")
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Django AppConfig for Khitish Backend Core."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from django.apps import AppConfig
|
|
6
|
+
|
|
7
|
+
__all__ = ["KhitishBackendConfig"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class KhitishBackendConfig(AppConfig):
|
|
11
|
+
"""Django application configuration registering signals and structured logging."""
|
|
12
|
+
|
|
13
|
+
name = "khitish_backend.adapters.django"
|
|
14
|
+
label = "khitish_backend"
|
|
15
|
+
verbose_name = "Khitish Backend Core"
|
|
16
|
+
default_auto_field = "django.db.models.BigAutoField"
|
|
17
|
+
|
|
18
|
+
def ready(self) -> None:
|
|
19
|
+
from khitish_backend.adapters.django import signals # noqa: F401
|
|
20
|
+
from khitish_backend.core.config import LoggingSettings
|
|
21
|
+
from khitish_backend.core.logging import configure_logging
|
|
22
|
+
|
|
23
|
+
configure_logging(LoggingSettings())
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""DRF exception handler mapping Khitish domain exceptions to JSON error responses."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from rest_framework import status
|
|
8
|
+
from rest_framework.response import Response
|
|
9
|
+
from rest_framework.views import exception_handler as drf_exception_handler
|
|
10
|
+
|
|
11
|
+
from khitish_backend.core.exceptions import (
|
|
12
|
+
AuthenticationError,
|
|
13
|
+
AuthorizationError,
|
|
14
|
+
ConflictError,
|
|
15
|
+
KhitishBackendError,
|
|
16
|
+
NotFoundError,
|
|
17
|
+
RateLimitError,
|
|
18
|
+
TokenError,
|
|
19
|
+
)
|
|
20
|
+
from khitish_backend.core.exceptions import (
|
|
21
|
+
ValidationError as KhitishValidationError,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
__all__ = ["khitish_exception_handler"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def khitish_exception_handler(exc: Exception, context: dict[str, Any]) -> Response | None:
|
|
28
|
+
"""Map :class:`KhitishBackendError` instances to consistent DRF error envelopes."""
|
|
29
|
+
if isinstance(exc, KhitishBackendError):
|
|
30
|
+
status_code = _get_status_code(exc)
|
|
31
|
+
return Response(
|
|
32
|
+
{
|
|
33
|
+
"error": {
|
|
34
|
+
"code": exc.error_code,
|
|
35
|
+
"message": str(exc),
|
|
36
|
+
"details": exc.to_dict() if hasattr(exc, "to_dict") else {},
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
status=status_code,
|
|
40
|
+
)
|
|
41
|
+
return drf_exception_handler(exc, context)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _get_status_code(exc: KhitishBackendError) -> int:
|
|
45
|
+
if isinstance(exc, (AuthenticationError, TokenError)):
|
|
46
|
+
return status.HTTP_401_UNAUTHORIZED
|
|
47
|
+
if isinstance(exc, AuthorizationError):
|
|
48
|
+
return status.HTTP_403_FORBIDDEN
|
|
49
|
+
if isinstance(exc, NotFoundError):
|
|
50
|
+
return status.HTTP_404_NOT_FOUND
|
|
51
|
+
if isinstance(exc, ConflictError):
|
|
52
|
+
return status.HTTP_409_CONFLICT
|
|
53
|
+
if isinstance(exc, RateLimitError):
|
|
54
|
+
return status.HTTP_429_TOO_MANY_REQUESTS
|
|
55
|
+
if isinstance(exc, KhitishValidationError):
|
|
56
|
+
return status.HTTP_400_BAD_REQUEST
|
|
57
|
+
return status.HTTP_500_INTERNAL_SERVER_ERROR
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Django middleware for request correlation IDs, security headers, and performance logging."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
import uuid
|
|
7
|
+
|
|
8
|
+
import structlog
|
|
9
|
+
from django.http import HttpRequest, HttpResponse
|
|
10
|
+
from django.utils.deprecation import MiddlewareMixin
|
|
11
|
+
|
|
12
|
+
from khitish_backend.core.logging import set_correlation_id
|
|
13
|
+
from khitish_backend.core.security import SecurityHeaders
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"PerformanceLoggingMiddleware",
|
|
17
|
+
"RequestIdMiddleware",
|
|
18
|
+
"SecurityHeadersMiddleware",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class RequestIdMiddleware(MiddlewareMixin):
|
|
23
|
+
"""Attach ``X-Request-ID`` to every Django request and response."""
|
|
24
|
+
|
|
25
|
+
def process_request(self, request: HttpRequest) -> None:
|
|
26
|
+
request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4())
|
|
27
|
+
request.request_id = request_id # type: ignore[attr-defined]
|
|
28
|
+
set_correlation_id(request_id)
|
|
29
|
+
|
|
30
|
+
def process_response(
|
|
31
|
+
self,
|
|
32
|
+
request: HttpRequest,
|
|
33
|
+
response: HttpResponse,
|
|
34
|
+
) -> HttpResponse:
|
|
35
|
+
response["X-Request-ID"] = getattr(request, "request_id", "")
|
|
36
|
+
return response
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class SecurityHeadersMiddleware(MiddlewareMixin):
|
|
40
|
+
"""Add defensive security headers to every Django response."""
|
|
41
|
+
|
|
42
|
+
_HEADERS = SecurityHeaders().to_dict()
|
|
43
|
+
|
|
44
|
+
def process_response(
|
|
45
|
+
self,
|
|
46
|
+
request: HttpRequest,
|
|
47
|
+
response: HttpResponse,
|
|
48
|
+
) -> HttpResponse:
|
|
49
|
+
_ = request
|
|
50
|
+
for header, value in self._HEADERS.items():
|
|
51
|
+
response.setdefault(header, value)
|
|
52
|
+
return response
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class PerformanceLoggingMiddleware(MiddlewareMixin):
|
|
56
|
+
"""Log Django HTTP request latency using structlog."""
|
|
57
|
+
|
|
58
|
+
def process_request(self, request: HttpRequest) -> None:
|
|
59
|
+
request._start_time = time.perf_counter() # type: ignore[attr-defined]
|
|
60
|
+
|
|
61
|
+
def process_response(
|
|
62
|
+
self,
|
|
63
|
+
request: HttpRequest,
|
|
64
|
+
response: HttpResponse,
|
|
65
|
+
) -> HttpResponse:
|
|
66
|
+
start = getattr(request, "_start_time", None)
|
|
67
|
+
if start is not None:
|
|
68
|
+
duration_ms = (time.perf_counter() - start) * 1000
|
|
69
|
+
structlog.get_logger(__name__).info(
|
|
70
|
+
"http.request",
|
|
71
|
+
method=request.method,
|
|
72
|
+
path=request.path,
|
|
73
|
+
status=response.status_code,
|
|
74
|
+
duration_ms=round(duration_ms, 2),
|
|
75
|
+
request_id=getattr(request, "request_id", ""),
|
|
76
|
+
)
|
|
77
|
+
return response
|