-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathorganization.py
245 lines (210 loc) · 8.48 KB
/
organization.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
from typing import TYPE_CHECKING, Dict, List, Optional
from lbox.exceptions import LabelboxError
from labelbox import utils
from labelbox.orm.db_object import DbObject, Entity, query
from labelbox.orm.model import Field, Relationship
from labelbox.schema.invite import InviteLimit
from labelbox.schema.resource_tag import ResourceTag
if TYPE_CHECKING:
from labelbox import (
IAMIntegration,
Invite,
InviteLimit,
ProjectRole,
Role,
User,
)
class Organization(DbObject):
"""An Organization is a group of Users.
It is associated with data created by Users within that Organization.
Typically all Users within an Organization have access to data created by any User in the same Organization.
Attributes:
updated_at (datetime)
created_at (datetime)
name (str)
users (Relationship): `ToMany` relationship to User
projects (Relationship): `ToMany` relationship to Project
webhooks (Relationship): `ToMany` relationship to Webhook
"""
# RelationshipManagers in Organization use the type in Query (and
# not the source object) because the server-side does not support
# filtering on ID in the query for getting a single organization.
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for relationship in self.relationships():
getattr(self, relationship.name).filter_on_id = False
updated_at = Field.DateTime("updated_at")
created_at = Field.DateTime("created_at")
name = Field.String("name")
# Relationships
users = Relationship.ToMany("User", False)
projects = Relationship.ToMany("Project", True)
webhooks = Relationship.ToMany("Webhook", False)
resource_tags = Relationship.ToMany("ResourceTags", False)
tasks = Relationship.ToMany("Task", False, "tasks")
def invite_user(
self,
email: str,
role: "Role",
project_roles: Optional[List["ProjectRole"]] = None,
) -> "Invite":
"""
Invite a new member to the org. This will send the user an email invite
Args:
email (str): email address of the user to invite
role (Role): Role to assign to the user
project_roles (Optional[List[ProjectRoles]]): List of project roles to assign to the User (if they have a project based org role).
Returns:
Invite for the user
Notes:
1. Multiple invites can be sent for the same email. This can only be resolved in the UI for now.
- Future releases of the SDK will support the ability to query and revoke invites to solve this problem (and/or checking on the backend)
2. Some server side response are unclear (e.g. if the user invites themself `None` is returned which the SDK raises as a `LabelboxError` )
"""
if project_roles and role.name != "NONE":
raise ValueError(
f"Project roles cannot be set for a user with organization level permissions. Found role name `{role.name}`, expected `NONE`"
)
data_param = "data"
query_str = """mutation createInvitesPyApi($%s: [CreateInviteInput!]){
createInvites(data: $%s){ invite { id createdAt organizationRoleName inviteeEmail inviter { %s } }}}""" % (
data_param,
data_param,
query.results_query_part(Entity.User),
)
projects = [
{
"projectId": project_role.project.uid,
"projectRoleId": project_role.role.uid,
}
for project_role in project_roles or []
]
res = self.client.execute(
query_str,
{
data_param: [
{
"inviterId": self.client.get_user().uid,
"inviteeEmail": email,
"organizationId": self.uid,
"organizationRoleId": role.uid,
"projects": projects,
}
]
},
)
invite_response = res["createInvites"][0]["invite"]
if not invite_response:
raise LabelboxError(f"Unable to send invite for email {email}")
return Entity.Invite(self.client, invite_response)
def invite_limit(self) -> InviteLimit:
"""Retrieve invite limits for the org
This already accounts for users currently in the org
Meaining that `used = users + invites, remaining = limit - (users + invites)`
Returns:
InviteLimit
"""
org_id_param = "organizationId"
res = self.client.execute(
"""query InvitesLimitPyApi($%s: ID!) {
invitesLimit(where: {id: $%s}) { used limit remaining }
}"""
% (org_id_param, org_id_param),
{org_id_param: self.uid},
)
return InviteLimit(
**{utils.snake_case(k): v for k, v in res["invitesLimit"].items()}
)
def remove_user(self, user: "User") -> None:
"""
Deletes a user from the organization. This cannot be undone without sending another invite.
Args:
user (User): The user to delete from the org
"""
user_id_param = "userId"
self.client.execute(
"""mutation DeleteMemberPyApi($%s: ID!) {
updateUser(where: {id: $%s}, data: {deleted: true}) { id deleted }
}"""
% (user_id_param, user_id_param),
{user_id_param: user.uid},
)
def create_resource_tag(self, tag: Dict[str, str]) -> ResourceTag:
"""
Creates a resource tag.
>>> tag = {'text': 'tag-1', 'color': 'ffffff'}
Args:
tag (dict): A resource tag {'text': 'tag-1', 'color': 'fffff'}
Returns:
The created resource tag.
"""
tag_text_param = "text"
tag_color_param = "color"
query_str = """mutation CreateResourceTagPyApi($text:String!,$color:String!) {
createResourceTag(input:{text:$%s,color:$%s}) {%s}}
""" % (
tag_text_param,
tag_color_param,
query.results_query_part(ResourceTag),
)
params = {
tag_text_param: tag.get("text", None),
tag_color_param: tag.get("color", None),
}
if not all(params.values()):
raise ValueError(
f"tag must contain 'text' and 'color' keys. received: {tag}"
)
res = self.client.execute(query_str, params)
return ResourceTag(self.client, res["createResourceTag"])
def get_resource_tags(self) -> List[ResourceTag]:
"""
Returns all resource tags for an organization
"""
query_str = (
"""query GetOrganizationResourceTagsPyApi{organization{resourceTag{%s}}}"""
% (query.results_query_part(ResourceTag))
)
return [
ResourceTag(self.client, tag)
for tag in self.client.execute(query_str)["organization"][
"resourceTag"
]
]
def get_iam_integrations(self) -> List["IAMIntegration"]:
"""
Returns all IAM Integrations for an organization
"""
res = self.client.execute(
"""query getAllIntegrationsPyApi { iamIntegrations {
%s
settings {
__typename
... on AwsIamIntegrationSettings {roleArn}
... on GcpIamIntegrationSettings {serviceAccountEmailId readBucket}
}
} } """
% query.results_query_part(Entity.IAMIntegration)
)
return [
Entity.IAMIntegration(self.client, integration_data)
for integration_data in res["iamIntegrations"]
]
def get_default_iam_integration(self) -> Optional["IAMIntegration"]:
"""
Returns the default IAM integration for the organization.
Will return None if there are no default integrations for the org.
"""
integrations = self.get_iam_integrations()
default_integration = [
integration
for integration in integrations
if integration.is_org_default
]
if len(default_integration) > 1:
raise ValueError(
"Found more than one default signer. Please contact Labelbox to resolve"
)
return (
None if not len(default_integration) else default_integration.pop()
)