mycelium-http-tools 0.1.0a2__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.
- myc_http_tools/__init__.py +13 -0
- myc_http_tools/__main__.py +0 -0
- myc_http_tools/__version__.py +1 -0
- myc_http_tools/exceptions.py +30 -0
- myc_http_tools/models/__init__.py +17 -0
- myc_http_tools/models/licensed_resources.py +173 -0
- myc_http_tools/models/owner.py +16 -0
- myc_http_tools/models/permission.py +19 -0
- myc_http_tools/models/profile.py +264 -0
- myc_http_tools/models/related_accounts.py +56 -0
- myc_http_tools/models/tenants_ownership.py +20 -0
- myc_http_tools/models/verbose_status.py +10 -0
- mycelium_http_tools-0.1.0a2.dist-info/METADATA +21 -0
- mycelium_http_tools-0.1.0a2.dist-info/RECORD +20 -0
- mycelium_http_tools-0.1.0a2.dist-info/WHEEL +4 -0
- tests/__init__.py +0 -0
- tests/test_licensed_resource.py +293 -0
- tests/test_licensed_resources.py +290 -0
- tests/test_permission.py +64 -0
- tests/test_profile.py +1897 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Mycelium HTTP Tools - A Python library to integrate Python APIs in Mycelium API Gateway."""
|
|
2
|
+
|
|
3
|
+
from .exceptions import (
|
|
4
|
+
InsufficientLicensesError,
|
|
5
|
+
InsufficientPrivilegesError,
|
|
6
|
+
MyceliumError,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"MyceliumError",
|
|
11
|
+
"InsufficientLicensesError",
|
|
12
|
+
"InsufficientPrivilegesError",
|
|
13
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
version = "0.1.0a2"
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Custom exceptions for mycelium-http-tools."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MyceliumError(Exception):
|
|
7
|
+
"""Base exception for Mycelium HTTP Tools."""
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self, message: str, code: Optional[str] = None, exp_true: bool = False
|
|
11
|
+
):
|
|
12
|
+
self.message = message
|
|
13
|
+
self.code = code
|
|
14
|
+
self.exp_true = exp_true
|
|
15
|
+
super().__init__(self.message)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class InsufficientPrivilegesError(MyceliumError):
|
|
19
|
+
"""Raised when there are insufficient privileges to perform an action."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, message: str, filtering_state: Optional[list[str]] = None):
|
|
22
|
+
self.filtering_state = filtering_state or []
|
|
23
|
+
super().__init__(message=message, code="MYC00019", exp_true=True)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class InsufficientLicensesError(MyceliumError):
|
|
27
|
+
"""Raised when there are insufficient licenses to perform an action."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, message: str = "Insufficient licenses to perform these action"):
|
|
30
|
+
super().__init__(message=message, code="MYC00019", exp_true=True)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .licensed_resources import LicensedResources
|
|
2
|
+
from .owner import Owner
|
|
3
|
+
from .permission import Permission
|
|
4
|
+
from .profile import Profile
|
|
5
|
+
from .related_accounts import RelatedAccounts
|
|
6
|
+
from .tenants_ownership import TenantsOwnership
|
|
7
|
+
from .verbose_status import VerboseStatus
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"LicensedResources",
|
|
11
|
+
"Owner",
|
|
12
|
+
"Permission",
|
|
13
|
+
"Profile",
|
|
14
|
+
"RelatedAccounts",
|
|
15
|
+
"TenantsOwnership",
|
|
16
|
+
"VerboseStatus",
|
|
17
|
+
]
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
from typing import Optional, Self
|
|
3
|
+
from urllib.parse import parse_qs, urlparse
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
7
|
+
from pydantic.alias_generators import to_camel
|
|
8
|
+
|
|
9
|
+
from .permission import Permission
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LicensedResource(BaseModel):
|
|
13
|
+
model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)
|
|
14
|
+
|
|
15
|
+
acc_id: UUID
|
|
16
|
+
sys_acc: bool
|
|
17
|
+
tenant_id: UUID
|
|
18
|
+
acc_name: str
|
|
19
|
+
role: str
|
|
20
|
+
role_id: UUID
|
|
21
|
+
perm: Permission
|
|
22
|
+
verified: bool
|
|
23
|
+
|
|
24
|
+
# --------------------------------------------------------------------------
|
|
25
|
+
# PRIVATE METHODS
|
|
26
|
+
# --------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def _is_uuid(value: str) -> bool:
|
|
30
|
+
"""Check if a string is a valid UUID."""
|
|
31
|
+
try:
|
|
32
|
+
UUID(value)
|
|
33
|
+
return True
|
|
34
|
+
except ValueError:
|
|
35
|
+
return False
|
|
36
|
+
|
|
37
|
+
# --------------------------------------------------------------------------
|
|
38
|
+
# PUBLIC METHODS
|
|
39
|
+
# --------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def from_str(cls, value: str) -> Self:
|
|
43
|
+
"""Parse a licensed resource from a URL string.
|
|
44
|
+
|
|
45
|
+
Expected URL format: https://localhost.local/tid/{tenant_id}/aid/{account_id}/rid/{role_id}?pr={role_name}:{permission_code}&sys={0|1}&v={0|1}&name={base64_encoded_name}
|
|
46
|
+
"""
|
|
47
|
+
# Construct full URL with localhost.local domain
|
|
48
|
+
full_url = f"https://localhost.local/{value}"
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
# Parse the URL
|
|
52
|
+
parsed_url = urlparse(full_url)
|
|
53
|
+
except Exception as e:
|
|
54
|
+
raise ValueError(f"Unexpected error on check license URL: {e}")
|
|
55
|
+
|
|
56
|
+
# Extract path segments
|
|
57
|
+
path_segments = [seg for seg in parsed_url.path.split("/") if seg]
|
|
58
|
+
|
|
59
|
+
if (
|
|
60
|
+
len(path_segments) != 6
|
|
61
|
+
or path_segments[0] != "tid"
|
|
62
|
+
or path_segments[2] != "aid"
|
|
63
|
+
or path_segments[4] != "rid"
|
|
64
|
+
):
|
|
65
|
+
raise ValueError("Invalid path format")
|
|
66
|
+
|
|
67
|
+
tenant_id = path_segments[1]
|
|
68
|
+
account_id = path_segments[3]
|
|
69
|
+
role_id = path_segments[5]
|
|
70
|
+
|
|
71
|
+
# Validate UUIDs
|
|
72
|
+
if not cls._is_uuid(tenant_id):
|
|
73
|
+
raise ValueError("Invalid tenant UUID")
|
|
74
|
+
|
|
75
|
+
if not cls._is_uuid(account_id):
|
|
76
|
+
raise ValueError("Invalid account UUID")
|
|
77
|
+
|
|
78
|
+
if not cls._is_uuid(role_id):
|
|
79
|
+
raise ValueError("Invalid role UUID")
|
|
80
|
+
|
|
81
|
+
# Parse query parameters
|
|
82
|
+
query_params = parse_qs(parsed_url.query)
|
|
83
|
+
|
|
84
|
+
# Extract permissioned role (pr parameter)
|
|
85
|
+
if "pr" not in query_params:
|
|
86
|
+
raise ValueError("Parameter pr not found")
|
|
87
|
+
|
|
88
|
+
permissioned_role = query_params["pr"][0]
|
|
89
|
+
permissioned_role_parts = permissioned_role.split(":")
|
|
90
|
+
|
|
91
|
+
if len(permissioned_role_parts) != 2:
|
|
92
|
+
raise ValueError("Invalid permissioned role format")
|
|
93
|
+
|
|
94
|
+
role_name = permissioned_role_parts[0]
|
|
95
|
+
permission_code = permissioned_role_parts[1]
|
|
96
|
+
|
|
97
|
+
# Extract system account flag (sys parameter)
|
|
98
|
+
if "sys" not in query_params:
|
|
99
|
+
raise ValueError("Parameter sys not found")
|
|
100
|
+
|
|
101
|
+
try:
|
|
102
|
+
sys_value = int(query_params["sys"][0])
|
|
103
|
+
if sys_value == 0:
|
|
104
|
+
sys_acc = False
|
|
105
|
+
elif sys_value == 1:
|
|
106
|
+
sys_acc = True
|
|
107
|
+
else:
|
|
108
|
+
raise ValueError("Invalid account standard")
|
|
109
|
+
except ValueError as e:
|
|
110
|
+
if "Invalid account standard" in str(e):
|
|
111
|
+
raise
|
|
112
|
+
raise ValueError("Failed to parse account standard")
|
|
113
|
+
|
|
114
|
+
# Extract verification flag (v parameter)
|
|
115
|
+
if "v" not in query_params:
|
|
116
|
+
raise ValueError("Parameter v not found")
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
verified_value = int(query_params["v"][0])
|
|
120
|
+
if verified_value == 0:
|
|
121
|
+
verified = False
|
|
122
|
+
elif verified_value == 1:
|
|
123
|
+
verified = True
|
|
124
|
+
else:
|
|
125
|
+
raise ValueError("Invalid account verification")
|
|
126
|
+
except ValueError as e:
|
|
127
|
+
if "Invalid account verification" in str(e):
|
|
128
|
+
raise
|
|
129
|
+
raise ValueError("Failed to parse account verification")
|
|
130
|
+
|
|
131
|
+
# Extract and decode account name (name parameter)
|
|
132
|
+
if "name" not in query_params:
|
|
133
|
+
raise ValueError("Parameter name not found")
|
|
134
|
+
|
|
135
|
+
name_encoded = query_params["name"][0]
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
name_decoded = base64.b64decode(name_encoded).decode("utf-8")
|
|
139
|
+
except Exception:
|
|
140
|
+
raise ValueError("Failed to decode account name")
|
|
141
|
+
|
|
142
|
+
# Create and return the LicensedResource instance
|
|
143
|
+
return cls(
|
|
144
|
+
tenant_id=UUID(tenant_id),
|
|
145
|
+
acc_id=UUID(account_id),
|
|
146
|
+
role_id=UUID(role_id),
|
|
147
|
+
role=role_name,
|
|
148
|
+
perm=Permission.from_i32(int(permission_code)),
|
|
149
|
+
sys_acc=sys_acc,
|
|
150
|
+
acc_name=name_decoded,
|
|
151
|
+
verified=verified,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class LicensedResources(BaseModel):
|
|
156
|
+
model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)
|
|
157
|
+
|
|
158
|
+
records: Optional[list[LicensedResource]] = Field(default=None)
|
|
159
|
+
urls: Optional[list[str]] = Field(default=None)
|
|
160
|
+
|
|
161
|
+
# --------------------------------------------------------------------------
|
|
162
|
+
# PUBLIC METHODS
|
|
163
|
+
# --------------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def to_licenses_vector(self) -> list[LicensedResource]:
|
|
166
|
+
if self.records is None and self.urls is None:
|
|
167
|
+
return []
|
|
168
|
+
|
|
169
|
+
if self.records is not None:
|
|
170
|
+
return self.records
|
|
171
|
+
|
|
172
|
+
if self.urls is not None:
|
|
173
|
+
return [LicensedResource.from_str(url) for url in self.urls]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
from uuid import UUID
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, ConfigDict
|
|
5
|
+
from pydantic.alias_generators import to_camel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Owner(BaseModel):
|
|
9
|
+
model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)
|
|
10
|
+
|
|
11
|
+
id: UUID
|
|
12
|
+
email: str
|
|
13
|
+
first_name: Optional[str] = None
|
|
14
|
+
last_name: Optional[str] = None
|
|
15
|
+
username: Optional[str] = None
|
|
16
|
+
is_principal: bool
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Permission(Enum):
|
|
5
|
+
READ = "read"
|
|
6
|
+
WRITE = "write"
|
|
7
|
+
|
|
8
|
+
def to_int(self) -> int:
|
|
9
|
+
return 0 if self == Permission.READ else 1
|
|
10
|
+
|
|
11
|
+
@classmethod
|
|
12
|
+
def from_i32(cls, value: int) -> "Permission":
|
|
13
|
+
"""Convert integer code to Permission enum."""
|
|
14
|
+
if value == 0:
|
|
15
|
+
return cls.READ
|
|
16
|
+
elif value == 1:
|
|
17
|
+
return cls.WRITE
|
|
18
|
+
else:
|
|
19
|
+
raise ValueError(f"Invalid permission code: {value}")
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
from typing import Optional, Self, Union
|
|
2
|
+
from uuid import UUID
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
5
|
+
from pydantic.alias_generators import to_camel
|
|
6
|
+
|
|
7
|
+
from myc_http_tools.exceptions import (
|
|
8
|
+
InsufficientLicensesError,
|
|
9
|
+
InsufficientPrivilegesError,
|
|
10
|
+
)
|
|
11
|
+
from myc_http_tools.models.licensed_resources import LicensedResources
|
|
12
|
+
from myc_http_tools.models.owner import Owner
|
|
13
|
+
from myc_http_tools.models.permission import Permission
|
|
14
|
+
from myc_http_tools.models.related_accounts import (
|
|
15
|
+
RelatedAccounts,
|
|
16
|
+
AllowedAccounts,
|
|
17
|
+
HasStaffPrivileges,
|
|
18
|
+
HasManagerPrivileges,
|
|
19
|
+
)
|
|
20
|
+
from myc_http_tools.models.tenants_ownership import TenantsOwnership
|
|
21
|
+
from myc_http_tools.models.verbose_status import VerboseStatus
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Profile(BaseModel):
|
|
25
|
+
"""Profile model"""
|
|
26
|
+
|
|
27
|
+
model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)
|
|
28
|
+
|
|
29
|
+
# --------------------------------------------------------------------------
|
|
30
|
+
# PUBLIC ATTRIBUTES
|
|
31
|
+
# --------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
owners: list[Owner] = Field(default_factory=list)
|
|
34
|
+
acc_id: UUID = Field()
|
|
35
|
+
is_subscription: bool
|
|
36
|
+
is_admin: bool
|
|
37
|
+
is_staff: bool
|
|
38
|
+
is_manager: bool = Field(default=False)
|
|
39
|
+
owner_is_active: bool
|
|
40
|
+
account_is_active: bool
|
|
41
|
+
account_was_approved: bool
|
|
42
|
+
account_was_archived: bool
|
|
43
|
+
account_was_deleted: bool
|
|
44
|
+
verbose_status: Optional[VerboseStatus] = None
|
|
45
|
+
licensed_resources: Optional[LicensedResources] = None
|
|
46
|
+
tenants_ownership: Optional[TenantsOwnership] = None
|
|
47
|
+
meta: Optional[dict] = None
|
|
48
|
+
filtering_state: Optional[list[str]] = None
|
|
49
|
+
|
|
50
|
+
# --------------------------------------------------------------------------
|
|
51
|
+
# PUBLIC METHODS
|
|
52
|
+
# --------------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
def with_read_access(self) -> Self:
|
|
55
|
+
return self.__with_permission(Permission.READ)
|
|
56
|
+
|
|
57
|
+
def with_write_access(self) -> Self:
|
|
58
|
+
return self.__with_permission(Permission.WRITE)
|
|
59
|
+
|
|
60
|
+
def on_tenant(self, tenant_id: UUID) -> Self:
|
|
61
|
+
"""Filter the licensed resources to the tenant.
|
|
62
|
+
|
|
63
|
+
This method should be used to filter licensed resources to the tenant
|
|
64
|
+
that the profile is currently working on.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
tenant_id: The UUID of the tenant to filter by
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
A new Profile instance with filtered licensed resources
|
|
71
|
+
"""
|
|
72
|
+
# Filter the licensed resources to the tenant
|
|
73
|
+
licensed_resources = None
|
|
74
|
+
if self.licensed_resources is not None:
|
|
75
|
+
# Get all licensed resources
|
|
76
|
+
all_resources = self.licensed_resources.to_licenses_vector()
|
|
77
|
+
|
|
78
|
+
# Filter by tenant_id
|
|
79
|
+
filtered_resources = [
|
|
80
|
+
resource
|
|
81
|
+
for resource in all_resources
|
|
82
|
+
if resource.tenant_id == tenant_id
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
# Create new LicensedResources if we have filtered results
|
|
86
|
+
if filtered_resources:
|
|
87
|
+
licensed_resources = LicensedResources(records=filtered_resources)
|
|
88
|
+
|
|
89
|
+
# Update filtering state to track the tenant filter (incremental)
|
|
90
|
+
updated_filtering_state = (
|
|
91
|
+
self.filtering_state.copy() if self.filtering_state else []
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
# Get the next filter number
|
|
95
|
+
next_filter_number = len(updated_filtering_state) + 1
|
|
96
|
+
tenant_filter = f"{next_filter_number}:tenantId:{tenant_id}"
|
|
97
|
+
|
|
98
|
+
# Add the new filter (incremental behavior)
|
|
99
|
+
updated_filtering_state.append(tenant_filter)
|
|
100
|
+
|
|
101
|
+
# Return the new profile
|
|
102
|
+
return self.model_copy(
|
|
103
|
+
update={
|
|
104
|
+
"licensed_resources": licensed_resources,
|
|
105
|
+
"filtering_state": updated_filtering_state,
|
|
106
|
+
}
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
def with_roles(self, roles: list[str]) -> Self:
|
|
110
|
+
"""Filter the licensed resources to the specified roles.
|
|
111
|
+
|
|
112
|
+
This method should be used to filter licensed resources to only include
|
|
113
|
+
those that match any of the specified roles.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
roles: List of role names to filter by
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
A new Profile instance with filtered licensed resources
|
|
120
|
+
"""
|
|
121
|
+
# Filter the licensed resources to the roles
|
|
122
|
+
licensed_resources = None
|
|
123
|
+
if self.licensed_resources is not None:
|
|
124
|
+
# Get all licensed resources
|
|
125
|
+
all_resources = self.licensed_resources.to_licenses_vector()
|
|
126
|
+
|
|
127
|
+
# Filter by roles (any role that matches any of the specified roles)
|
|
128
|
+
filtered_resources = [
|
|
129
|
+
resource for resource in all_resources if resource.role in roles
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
# Create new LicensedResources if we have filtered results
|
|
133
|
+
if filtered_resources:
|
|
134
|
+
licensed_resources = LicensedResources(records=filtered_resources)
|
|
135
|
+
|
|
136
|
+
# Update filtering state to track the role filter (incremental)
|
|
137
|
+
updated_filtering_state = (
|
|
138
|
+
self.filtering_state.copy() if self.filtering_state else []
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
# Get the next filter number
|
|
142
|
+
next_filter_number = len(updated_filtering_state) + 1
|
|
143
|
+
roles_str = ",".join(roles)
|
|
144
|
+
role_filter = f"{next_filter_number}:role:{roles_str}"
|
|
145
|
+
|
|
146
|
+
# Add the new filter (incremental behavior)
|
|
147
|
+
updated_filtering_state.append(role_filter)
|
|
148
|
+
|
|
149
|
+
# Return the new profile
|
|
150
|
+
return self.model_copy(
|
|
151
|
+
update={
|
|
152
|
+
"licensed_resources": licensed_resources,
|
|
153
|
+
"filtering_state": updated_filtering_state,
|
|
154
|
+
}
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
def on_account(self, account_id: UUID) -> Self:
|
|
158
|
+
"""Filter the licensed resources to the account.
|
|
159
|
+
|
|
160
|
+
This method should be used to filter licensed resources to the account
|
|
161
|
+
that the profile is currently working on.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
account_id: The UUID of the account to filter by
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
A new Profile instance with filtered licensed resources
|
|
168
|
+
"""
|
|
169
|
+
# Filter the licensed resources to the account
|
|
170
|
+
licensed_resources = None
|
|
171
|
+
if self.licensed_resources is not None:
|
|
172
|
+
# Get all licensed resources
|
|
173
|
+
all_resources = self.licensed_resources.to_licenses_vector()
|
|
174
|
+
|
|
175
|
+
# Filter by account_id
|
|
176
|
+
filtered_resources = [
|
|
177
|
+
resource for resource in all_resources if resource.acc_id == account_id
|
|
178
|
+
]
|
|
179
|
+
|
|
180
|
+
# Create new LicensedResources if we have filtered results
|
|
181
|
+
if filtered_resources:
|
|
182
|
+
licensed_resources = LicensedResources(records=filtered_resources)
|
|
183
|
+
|
|
184
|
+
# Update filtering state to track the account filter (incremental)
|
|
185
|
+
updated_filtering_state = (
|
|
186
|
+
self.filtering_state.copy() if self.filtering_state else []
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
# Get the next filter number
|
|
190
|
+
next_filter_number = len(updated_filtering_state) + 1
|
|
191
|
+
account_filter = f"{next_filter_number}:accountId:{account_id}"
|
|
192
|
+
|
|
193
|
+
# Add the new filter (incremental behavior)
|
|
194
|
+
updated_filtering_state.append(account_filter)
|
|
195
|
+
|
|
196
|
+
# Return the new profile
|
|
197
|
+
return self.model_copy(
|
|
198
|
+
update={
|
|
199
|
+
"licensed_resources": licensed_resources,
|
|
200
|
+
"filtering_state": updated_filtering_state,
|
|
201
|
+
}
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
def get_related_account_or_error(self) -> RelatedAccounts:
|
|
205
|
+
"""Get related accounts based on profile privileges.
|
|
206
|
+
|
|
207
|
+
This method determines the appropriate RelatedAccounts variant based on
|
|
208
|
+
the profile's privileges and available licensed resources.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
RelatedAccounts: The appropriate variant based on privileges
|
|
212
|
+
|
|
213
|
+
Raises:
|
|
214
|
+
InsufficientLicensesError: When there are no licensed resources
|
|
215
|
+
InsufficientPrivilegesError: When there are insufficient privileges
|
|
216
|
+
"""
|
|
217
|
+
# Check for staff privileges first
|
|
218
|
+
if self.is_staff:
|
|
219
|
+
return HasStaffPrivileges()
|
|
220
|
+
|
|
221
|
+
# Check for manager privileges
|
|
222
|
+
if self.is_manager:
|
|
223
|
+
return HasManagerPrivileges()
|
|
224
|
+
|
|
225
|
+
# Check for licensed resources
|
|
226
|
+
if self.licensed_resources is not None:
|
|
227
|
+
records = self.licensed_resources.to_licenses_vector()
|
|
228
|
+
|
|
229
|
+
if not records:
|
|
230
|
+
raise InsufficientLicensesError()
|
|
231
|
+
|
|
232
|
+
# Extract account IDs from licensed resources
|
|
233
|
+
account_ids = [record.acc_id for record in records]
|
|
234
|
+
return AllowedAccounts(accounts=account_ids)
|
|
235
|
+
|
|
236
|
+
# No privileges available
|
|
237
|
+
filtering_state_str = (
|
|
238
|
+
", ".join(self.filtering_state) if self.filtering_state else ""
|
|
239
|
+
)
|
|
240
|
+
raise InsufficientPrivilegesError(
|
|
241
|
+
f"Insufficient privileges to perform these action (no accounts): {filtering_state_str}",
|
|
242
|
+
filtering_state=self.filtering_state,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
# --------------------------------------------------------------------------
|
|
246
|
+
# PRIVATE METHODS
|
|
247
|
+
# --------------------------------------------------------------------------
|
|
248
|
+
|
|
249
|
+
def __with_permission(self, permission: Permission) -> Self:
|
|
250
|
+
if self.licensed_resources is None:
|
|
251
|
+
return self
|
|
252
|
+
|
|
253
|
+
licensed_resources = self.licensed_resources.model_copy()
|
|
254
|
+
|
|
255
|
+
licensed_resources.records = list(
|
|
256
|
+
filter(
|
|
257
|
+
lambda x: x.perm.to_int() >= permission.to_int(),
|
|
258
|
+
licensed_resources.to_licenses_vector(),
|
|
259
|
+
)
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
licensed_resources.urls = None
|
|
263
|
+
|
|
264
|
+
return self.model_copy(update={"licensed_resources": licensed_resources})
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
from typing import Union, Literal
|
|
2
|
+
from uuid import UUID
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, Field
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AllowedAccounts(BaseModel):
|
|
8
|
+
"""Represents accounts that are allowed access."""
|
|
9
|
+
|
|
10
|
+
type: Literal["allowed_accounts"] = Field(default="allowed_accounts", alias="type")
|
|
11
|
+
accounts: list[UUID] = Field(alias="accounts")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class HasTenantWidePrivileges(BaseModel):
|
|
15
|
+
"""Represents tenant-wide privileges for a specific tenant."""
|
|
16
|
+
|
|
17
|
+
type: Literal["has_tenant_wide_privileges"] = Field(
|
|
18
|
+
default="has_tenant_wide_privileges", alias="type"
|
|
19
|
+
)
|
|
20
|
+
tenant_id: UUID = Field(alias="tenant_id")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class HasStaffPrivileges(BaseModel):
|
|
24
|
+
"""Represents staff privileges."""
|
|
25
|
+
|
|
26
|
+
type: Literal["has_staff_privileges"] = Field(
|
|
27
|
+
default="has_staff_privileges", alias="type"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class HasManagerPrivileges(BaseModel):
|
|
32
|
+
"""Represents manager privileges."""
|
|
33
|
+
|
|
34
|
+
type: Literal["has_manager_privileges"] = Field(
|
|
35
|
+
default="has_manager_privileges", alias="type"
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_discriminator_value(
|
|
40
|
+
v: Union[
|
|
41
|
+
AllowedAccounts,
|
|
42
|
+
HasTenantWidePrivileges,
|
|
43
|
+
HasStaffPrivileges,
|
|
44
|
+
HasManagerPrivileges,
|
|
45
|
+
],
|
|
46
|
+
) -> str:
|
|
47
|
+
"""Discriminator function for the union type."""
|
|
48
|
+
return v.type
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
RelatedAccounts = Union[
|
|
52
|
+
AllowedAccounts,
|
|
53
|
+
HasTenantWidePrivileges,
|
|
54
|
+
HasStaffPrivileges,
|
|
55
|
+
HasManagerPrivileges,
|
|
56
|
+
]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
from uuid import UUID
|
|
3
|
+
|
|
4
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
5
|
+
from pydantic.alias_generators import to_camel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TenantOwnership(BaseModel):
|
|
9
|
+
model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)
|
|
10
|
+
|
|
11
|
+
id: UUID
|
|
12
|
+
name: str
|
|
13
|
+
since: str
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TenantsOwnership(BaseModel):
|
|
17
|
+
model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)
|
|
18
|
+
|
|
19
|
+
records: Optional[list[TenantOwnership]] = Field(default=None)
|
|
20
|
+
urls: Optional[list[str]] = Field(default=None)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: mycelium-http-tools
|
|
3
|
+
Version: 0.1.0a2
|
|
4
|
+
Summary: A python library to integrate python APIs in Mycelium API Gateway
|
|
5
|
+
License: Apache 2.0
|
|
6
|
+
Author: Samuel Galvão Elias
|
|
7
|
+
Author-email: sgelias@outlook.com
|
|
8
|
+
Requires-Python: >=3.12,<4.0
|
|
9
|
+
Classifier: License :: Other/Proprietary License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: commitizen (>=4.9.1) ; extra == "dev"
|
|
15
|
+
Requires-Dist: mypy (>=1.18.2) ; extra == "dev"
|
|
16
|
+
Requires-Dist: pre-commit (>=4.3.0) ; extra == "dev"
|
|
17
|
+
Requires-Dist: pydantic (>=2.11.9,<3.0.0)
|
|
18
|
+
Requires-Dist: urllib3 (>=2.5.0,<3.0.0)
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
myc_http_tools/__init__.py,sha256=zA3rGpqWwrUIeuDTuyGLJ18TOfAFOY2bb6L1vvLQKhg,311
|
|
2
|
+
myc_http_tools/__main__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
myc_http_tools/__version__.py,sha256=nYDL2_COM9L6goSZ-iJy9kd2kwnRJksMxxMH46E3nmg,20
|
|
4
|
+
myc_http_tools/exceptions.py,sha256=4hOw8hFJtDqwhtMZg7pknljDSh8AXnOPoPc2vt9xM64,1025
|
|
5
|
+
myc_http_tools/models/__init__.py,sha256=WyDvnqrVtOAX6zJO-R1yexOXQDv00JAtCqsfa7UQ2xw,429
|
|
6
|
+
myc_http_tools/models/licensed_resources.py,sha256=Akn0e023a6im-yv88NSFGtaGVbZXUOaPMAPkeUx8YYk,5728
|
|
7
|
+
myc_http_tools/models/owner.py,sha256=6BZbHO2w1bnllngFwEWdqNlgLfjTcW3YKgbS2vym528,406
|
|
8
|
+
myc_http_tools/models/permission.py,sha256=BLu9p4di97ODk68MmebCTI_fcXmlwVsEZKf85OjPUAk,476
|
|
9
|
+
myc_http_tools/models/profile.py,sha256=7BRdEcxiVhXrFq3tHROYpB4sSknZ8Nr-Xz50T708AsE,9533
|
|
10
|
+
myc_http_tools/models/related_accounts.py,sha256=lJqvyeVzdmQaX4cawejQ65vFHfR_zRunk9E3WS2ZOto,1371
|
|
11
|
+
myc_http_tools/models/tenants_ownership.py,sha256=3978CL_oSFRZTFwX5TvUbH3jMRo2UB17zkOY4_Gr7vk,542
|
|
12
|
+
myc_http_tools/models/verbose_status.py,sha256=2XGcWdC4Z-MnHuyUXuBNuHWDWgWzuixYoJJr6ffjAcg,207
|
|
13
|
+
tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
14
|
+
tests/test_licensed_resource.py,sha256=dhPskY0urdx3lzxEamQTv_aYh_m5ZMl0Kb5RftN303s,13962
|
|
15
|
+
tests/test_licensed_resources.py,sha256=y3OrDqTFWLSIfefeIAkuzB7aaE0uKrDYuRC0Qf1VuVQ,11865
|
|
16
|
+
tests/test_permission.py,sha256=FcZWpbt3LJqf0TVJsyyHlRimKPWys1QFm1vcN12KAgk,2447
|
|
17
|
+
tests/test_profile.py,sha256=iE2LnW1o6tJ7VTnRftAEbQaetrZ-JKmKXWKwm3Kntw8,70806
|
|
18
|
+
mycelium_http_tools-0.1.0a2.dist-info/METADATA,sha256=PYdgNmsPqv5IawPUmjYUkpNQKjcS513RZcq8LWx5wN0,749
|
|
19
|
+
mycelium_http_tools-0.1.0a2.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
|
|
20
|
+
mycelium_http_tools-0.1.0a2.dist-info/RECORD,,
|
tests/__init__.py
ADDED
|
File without changes
|