cinema-shared-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.
@@ -0,0 +1,3 @@
1
+ from pkgutil import extend_path
2
+
3
+ __path__ = extend_path(__path__, __name__)
File without changes
@@ -0,0 +1,35 @@
1
+ from abc import ABC, abstractmethod
2
+ from datetime import datetime, timezone
3
+ from typing import Any
4
+ from uuid import UUID, uuid4
5
+
6
+ from pydantic import BaseModel, ConfigDict, Field
7
+
8
+
9
+ class DomainEvent(BaseModel, ABC):
10
+ """Base class for domain/integration events (outbox/Kafka friendly)."""
11
+
12
+ model_config = ConfigDict(frozen=True)
13
+
14
+ event_id: UUID = Field(default_factory=uuid4)
15
+ occurred_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
16
+ aggregate_id: UUID | None = None
17
+ version: int = 1
18
+
19
+ @abstractmethod
20
+ def event_type(self) -> str:
21
+ """Stable integration name, e.g. ``showtime.created``."""
22
+
23
+ @abstractmethod
24
+ def _get_event_data(self) -> dict[str, Any]:
25
+ """Payload merged under ``data`` in :meth:`to_dict`."""
26
+
27
+ def to_dict(self) -> dict[str, Any]:
28
+ return {
29
+ "event_id": str(self.event_id),
30
+ "event_type": self.event_type(),
31
+ "occurred_at": self.occurred_at.isoformat(),
32
+ "aggregate_id": str(self.aggregate_id) if self.aggregate_id else None,
33
+ "version": self.version,
34
+ "data": self._get_event_data(),
35
+ }
@@ -0,0 +1,137 @@
1
+ from enum import StrEnum
2
+ from typing import Any
3
+
4
+
5
+ class DomainException(Exception):
6
+ """Business rule violation — safe to expose to clients (4xx)."""
7
+
8
+ def __init__(
9
+ self,
10
+ message: str,
11
+ *,
12
+ error_code: str = "DOMAIN_ERROR",
13
+ status_code: int | None = None,
14
+ details: Any | None = None,
15
+ ) -> None:
16
+ super().__init__(message)
17
+ self.message = message
18
+ self.error_code = error_code
19
+ self.details = details
20
+
21
+ if status_code is not None:
22
+ resolved = status_code
23
+ else:
24
+ class_status = None
25
+ for klass in type(self).__mro__:
26
+ if "status_code" in klass.__dict__:
27
+ class_status = klass.__dict__["status_code"]
28
+ break
29
+ if isinstance(class_status, int):
30
+ resolved = class_status
31
+ else:
32
+ resolved = 400
33
+ self.status_code = resolved
34
+
35
+
36
+ class ApplicationException(Exception):
37
+ """Internal application failure — details hidden from clients (5xx)."""
38
+
39
+ def __init__(
40
+ self,
41
+ message: str,
42
+ *,
43
+ error_code: str = "APPLICATION_ERROR",
44
+ status_code: int = 500,
45
+ details: Any | None = None,
46
+ ) -> None:
47
+ super().__init__(message)
48
+ self.message = message
49
+ self.error_code = error_code
50
+ self.status_code = status_code
51
+ self.details = details
52
+
53
+
54
+ class AuthorizationException(Exception):
55
+ """Auth / permission failure."""
56
+
57
+ def __init__(
58
+ self,
59
+ message: str,
60
+ *,
61
+ error_code: str = "AUTHORIZATION_ERROR",
62
+ status_code: int = 401,
63
+ details: Any | None = None,
64
+ ) -> None:
65
+ super().__init__(message)
66
+ self.message = message
67
+ self.error_code = error_code
68
+ self.status_code = status_code
69
+ self.details = details
70
+
71
+
72
+ class AuthErrorCode(StrEnum):
73
+ AUTHENTICATION_REQUIRED = "AUTHENTICATION_REQUIRED"
74
+ FORBIDDEN = "FORBIDDEN"
75
+ AUTH_ERROR = "AUTH_ERROR"
76
+ AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED"
77
+ AUTH_TOKEN_INVALID = "AUTH_TOKEN_INVALID"
78
+ AUTH_TOKEN_UNSUPPORTED = "AUTH_TOKEN_UNSUPPORTED"
79
+
80
+
81
+ def auth_error(
82
+ error_code: AuthErrorCode = AuthErrorCode.AUTHENTICATION_REQUIRED,
83
+ message: str = "",
84
+ *,
85
+ details: Any | None = None,
86
+ ) -> AuthorizationException:
87
+ return AuthorizationException(
88
+ message=message or "Authentication is required.",
89
+ error_code=str(error_code),
90
+ status_code=401,
91
+ details=details,
92
+ )
93
+
94
+
95
+ def forbidden_error(
96
+ error_code: AuthErrorCode = AuthErrorCode.FORBIDDEN,
97
+ message: str = "",
98
+ *,
99
+ details: Any | None = None,
100
+ ) -> AuthorizationException:
101
+ return AuthorizationException(
102
+ message=message or "You do not have permission to perform this action.",
103
+ error_code=str(error_code),
104
+ status_code=403,
105
+ details=details,
106
+ )
107
+
108
+
109
+ class NotFoundException(DomainException):
110
+ def __init__(self, entity_name: str, entity_id: Any, id_name: str = "id"):
111
+ sid = str(entity_id)
112
+ super().__init__(
113
+ f"{entity_name} with {id_name} {sid} was not found.",
114
+ error_code=f"{entity_name.upper()}_NOT_FOUND",
115
+ status_code=404,
116
+ details={"entity": entity_name, "id": sid},
117
+ )
118
+
119
+
120
+ class ValidationException(DomainException):
121
+ def __init__(self, field: str, reason: str):
122
+ super().__init__(
123
+ f"Validation failed for field '{field}': {reason}",
124
+ error_code="VALIDATION_ERROR",
125
+ status_code=422,
126
+ details={"field": field, "reason": reason},
127
+ )
128
+
129
+
130
+ class ConflictException(DomainException):
131
+ def __init__(self, message: str, *, details: dict | None = None):
132
+ super().__init__(
133
+ message,
134
+ error_code="CONFLICT",
135
+ status_code=409,
136
+ details=details or {},
137
+ )
@@ -0,0 +1,176 @@
1
+ import logging
2
+ from http import HTTPStatus
3
+ from typing import Any
4
+
5
+ from fastapi import FastAPI, Request
6
+ from fastapi.exceptions import RequestValidationError
7
+ from fastapi.responses import JSONResponse
8
+ from pydantic import ValidationError
9
+ from starlette.exceptions import HTTPException as StarletteHTTPException
10
+
11
+ from cinema_shared.core.exceptions import (
12
+ ApplicationException,
13
+ AuthorizationException,
14
+ DomainException,
15
+ )
16
+ from cinema_shared.core.response import ErrorResponse
17
+
18
+ logger = logging.getLogger("app")
19
+
20
+
21
+ def coerce_error_details(details: Any) -> list[Any]:
22
+ if details is None:
23
+ return []
24
+ if isinstance(details, list):
25
+ return details
26
+ if isinstance(details, dict):
27
+ return [details] if details else []
28
+ return [{"info": str(details)}]
29
+
30
+
31
+ def error_json_response(
32
+ status_code: int,
33
+ *,
34
+ code: str | None = None,
35
+ message: str | None = None,
36
+ details: Any = None,
37
+ headers: dict[str, str] | None = None,
38
+ ) -> JSONResponse:
39
+ body = ErrorResponse(
40
+ code=code or "ERROR",
41
+ message=message or "",
42
+ details=coerce_error_details(details),
43
+ ).model_dump(mode="json")
44
+ return JSONResponse(status_code=status_code, content=body, headers=headers)
45
+
46
+
47
+ def _flatten_validation_errors(errors: list[dict]) -> list[dict]:
48
+ return [
49
+ {
50
+ "field": ".".join(str(loc) for loc in err.get("loc", ["unknown"])),
51
+ "message": err.get("msg", "Validation error"),
52
+ }
53
+ for err in errors
54
+ ]
55
+
56
+
57
+ async def handle_domain_exceptions(
58
+ request: Request, exc: DomainException
59
+ ) -> JSONResponse:
60
+ logger.warning(
61
+ "Domain error [%s] %s | path=%s",
62
+ exc.error_code,
63
+ exc.message,
64
+ request.url.path,
65
+ )
66
+ return error_json_response(
67
+ status_code=exc.status_code,
68
+ code=exc.error_code,
69
+ message=exc.message,
70
+ details=exc.details,
71
+ )
72
+
73
+
74
+ async def handle_auth_exceptions(
75
+ request: Request, exc: AuthorizationException
76
+ ) -> JSONResponse:
77
+ logger.warning(
78
+ "Auth error [%s] %s | path=%s",
79
+ exc.error_code,
80
+ exc.message,
81
+ request.url.path,
82
+ )
83
+ return error_json_response(
84
+ status_code=exc.status_code,
85
+ code=exc.error_code,
86
+ message=exc.message,
87
+ details=exc.details,
88
+ )
89
+
90
+
91
+ async def handle_application_exceptions(
92
+ request: Request, exc: ApplicationException
93
+ ) -> JSONResponse:
94
+ logger.error(
95
+ "Application error [%s] %s | path=%s",
96
+ exc.error_code,
97
+ exc.message,
98
+ request.url.path,
99
+ exc_info=exc,
100
+ )
101
+ return error_json_response(
102
+ status_code=exc.status_code,
103
+ code=exc.error_code,
104
+ message="An internal server error occurred. Please try again later.",
105
+ )
106
+
107
+
108
+ async def handle_pydantic_validation_errors(
109
+ request: Request, exc: ValidationError
110
+ ) -> JSONResponse:
111
+ details = _flatten_validation_errors(exc.errors())
112
+ logger.warning(
113
+ "Pydantic validation error | path=%s | fields=%s",
114
+ request.url.path,
115
+ [d["field"] for d in details],
116
+ )
117
+ return error_json_response(
118
+ status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
119
+ code="VALIDATION_ERROR",
120
+ message="One or more fields failed validation.",
121
+ details=details,
122
+ )
123
+
124
+
125
+ async def handle_request_validation_errors(
126
+ request: Request, exc: RequestValidationError
127
+ ) -> JSONResponse:
128
+ details = _flatten_validation_errors(exc.errors())
129
+ logger.warning(
130
+ "Request validation error | path=%s | fields=%s",
131
+ request.url.path,
132
+ [d["field"] for d in details],
133
+ )
134
+ return error_json_response(
135
+ status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
136
+ code="VALIDATION_ERROR",
137
+ message="One or more fields failed validation.",
138
+ details=details,
139
+ )
140
+
141
+
142
+ async def handle_http_exceptions(
143
+ request: Request, exc: StarletteHTTPException
144
+ ) -> JSONResponse:
145
+ return error_json_response(
146
+ status_code=exc.status_code,
147
+ code="HTTP_ERROR",
148
+ message=str(exc.detail),
149
+ headers=getattr(exc, "headers", None),
150
+ )
151
+
152
+
153
+ async def handle_generic_exceptions(
154
+ request: Request, exc: Exception
155
+ ) -> JSONResponse:
156
+ logger.critical(
157
+ "Unhandled exception [%s] | path=%s",
158
+ type(exc).__name__,
159
+ request.url.path,
160
+ exc_info=exc,
161
+ )
162
+ return error_json_response(
163
+ status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
164
+ code="INTERNAL_SERVER_ERROR",
165
+ message="An unexpected error occurred.",
166
+ )
167
+
168
+
169
+ def register_exception_handlers(app: FastAPI) -> None:
170
+ app.add_exception_handler(DomainException, handle_domain_exceptions)
171
+ app.add_exception_handler(AuthorizationException, handle_auth_exceptions)
172
+ app.add_exception_handler(ApplicationException, handle_application_exceptions)
173
+ app.add_exception_handler(ValidationError, handle_pydantic_validation_errors)
174
+ app.add_exception_handler(RequestValidationError, handle_request_validation_errors)
175
+ app.add_exception_handler(StarletteHTTPException, handle_http_exceptions)
176
+ app.add_exception_handler(Exception, handle_generic_exceptions)
@@ -0,0 +1,192 @@
1
+ import logging
2
+ from collections.abc import Callable
3
+ from typing import Any, Protocol, cast
4
+
5
+ import jwt
6
+ from fastapi import Request, status
7
+ from fastapi.responses import JSONResponse
8
+ from jwt.types import Options
9
+ from pydantic import BaseModel, ConfigDict, Field
10
+
11
+ from cinema_shared.core.exceptions import AuthErrorCode, auth_error, forbidden_error
12
+ from cinema_shared.core.http import error_json_response
13
+
14
+ logger = logging.getLogger("app")
15
+
16
+
17
+ class JwtSettings(Protocol):
18
+ JWT_SECRET_KEY: str
19
+ JWT_ALGORITHM: str
20
+ JWT_AUDIENCE: str | None
21
+ JWT_ISSUER: str | None
22
+ JWT_LEEWAY_SECONDS: int
23
+
24
+
25
+ def build_jwt_decode_options(
26
+ *, jwt_audience: str | None, jwt_issuer: str | None
27
+ ) -> Options:
28
+ """PyJWT options aligned with optional audience / issuer validation."""
29
+ return cast(
30
+ Options,
31
+ {
32
+ "verify_aud": bool(jwt_audience),
33
+ "verify_iss": bool(jwt_issuer),
34
+ },
35
+ )
36
+
37
+
38
+ def decode_jwt_token(token: str, settings: JwtSettings) -> dict[str, Any]:
39
+ """Decode and validate a JWT using settings-driven audience/issuer rules."""
40
+ return jwt.decode(
41
+ token,
42
+ settings.JWT_SECRET_KEY,
43
+ algorithms=[settings.JWT_ALGORITHM],
44
+ audience=settings.JWT_AUDIENCE or None,
45
+ issuer=settings.JWT_ISSUER or None,
46
+ options=build_jwt_decode_options(
47
+ jwt_audience=settings.JWT_AUDIENCE,
48
+ jwt_issuer=settings.JWT_ISSUER,
49
+ ),
50
+ leeway=settings.JWT_LEEWAY_SECONDS,
51
+ )
52
+
53
+
54
+ def _is_blank(value: Any) -> bool:
55
+ if value is None:
56
+ return True
57
+ if isinstance(value, str) and not value.strip():
58
+ return True
59
+ return False
60
+
61
+
62
+ def _first_text_claim(claims: dict[str, Any], *keys: str) -> str | None:
63
+ for key in keys:
64
+ value = claims.get(key)
65
+ if _is_blank(value):
66
+ continue
67
+ return str(value)
68
+ return None
69
+
70
+
71
+ def _parse_roles(claims: dict[str, Any]) -> list[str]:
72
+ if "roles" in claims:
73
+ roles_raw = claims["roles"]
74
+ elif "role" in claims:
75
+ roles_raw = claims["role"]
76
+ else:
77
+ return []
78
+
79
+ if isinstance(roles_raw, str):
80
+ return [roles_raw]
81
+ if isinstance(roles_raw, bool):
82
+ return []
83
+ if isinstance(roles_raw, (int, float)):
84
+ return [str(roles_raw)]
85
+ if isinstance(roles_raw, list):
86
+ roles: list[str] = []
87
+ for item in roles_raw:
88
+ if _is_blank(item):
89
+ continue
90
+ roles.append(str(item))
91
+ return roles
92
+ return []
93
+
94
+
95
+ class AuthUserContext(BaseModel):
96
+ model_config = ConfigDict(extra="ignore", frozen=True)
97
+
98
+ user_id: str | None = None
99
+ subject: str | None = None
100
+ email: str | None = None
101
+ username: str | None = None
102
+ roles: list[str] = Field(default_factory=list)
103
+ claims: dict[str, Any] = Field(default_factory=dict)
104
+
105
+ @classmethod
106
+ def from_claims(cls, claims: dict[str, Any]) -> "AuthUserContext":
107
+ if not isinstance(claims, dict):
108
+ raise TypeError("claims must be a dict")
109
+ return cls(
110
+ user_id=_first_text_claim(claims, "user_id", "uid", "id", "sub"),
111
+ subject=_first_text_claim(claims, "sub"),
112
+ email=_first_text_claim(claims, "email"),
113
+ username=_first_text_claim(
114
+ claims, "username", "preferred_username", "name"
115
+ ),
116
+ roles=_parse_roles(claims),
117
+ claims=dict(claims),
118
+ )
119
+
120
+
121
+ def unauthorized_response(message: str) -> JSONResponse:
122
+ return error_json_response(
123
+ status_code=status.HTTP_401_UNAUTHORIZED,
124
+ code="UNAUTHORIZED",
125
+ message=message,
126
+ details=[],
127
+ headers={"WWW-Authenticate": "Bearer"},
128
+ )
129
+
130
+
131
+ def get_current_user(request: Request) -> AuthUserContext | None:
132
+ return getattr(request.state, "current_user", None)
133
+
134
+
135
+ def require_authenticated_user(request: Request) -> AuthUserContext:
136
+ user = get_current_user(request)
137
+ if user is None:
138
+ raise auth_error(AuthErrorCode.AUTHENTICATION_REQUIRED)
139
+ return user
140
+
141
+
142
+ def require_roles(*allowed_roles: str) -> Callable[[Request], AuthUserContext]:
143
+ normalized_allowed = {
144
+ role.strip().lower() for role in allowed_roles if role.strip()
145
+ }
146
+
147
+ def dependency(request: Request) -> AuthUserContext:
148
+ user = require_authenticated_user(request)
149
+
150
+ user_roles = {role.strip().lower() for role in user.roles if role.strip()}
151
+ if normalized_allowed and not (user_roles & normalized_allowed):
152
+ logger.warning(
153
+ "User is authenticated but does not have required role",
154
+ extra={
155
+ "props": {
156
+ "path": request.url.path,
157
+ "required_roles": sorted(normalized_allowed),
158
+ "user_roles": sorted(user_roles),
159
+ "user_id": user.user_id,
160
+ }
161
+ },
162
+ )
163
+ raise forbidden_error(
164
+ details={
165
+ "required_roles": sorted(normalized_allowed),
166
+ "user_roles": sorted(user_roles),
167
+ },
168
+ )
169
+
170
+ return user
171
+
172
+ return dependency
173
+
174
+
175
+ def get_jwt_claims(request: Request) -> dict[str, Any] | None:
176
+ return getattr(request.state, "jwt_claims", None)
177
+
178
+
179
+ def current_user_dep(request: Request) -> AuthUserContext:
180
+ return require_authenticated_user(request)
181
+
182
+
183
+ STAFF_ROLE_NAMES = frozenset({"admin", "manager", "employee"})
184
+ ADMIN_ROLE_NAMES = frozenset({"admin", "superadmin"})
185
+
186
+
187
+ def is_staff_user(user: AuthUserContext) -> bool:
188
+ return any(r.strip().lower() in STAFF_ROLE_NAMES for r in user.roles)
189
+
190
+
191
+ def is_admin_user(user: AuthUserContext) -> bool:
192
+ return any(r.strip().lower() in ADMIN_ROLE_NAMES for r in user.roles)