-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathexample1.py
More file actions
410 lines (362 loc) · 14.1 KB
/
Copy pathexample1.py
File metadata and controls
410 lines (362 loc) · 14.1 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# ruff: noqa: E402
"""
Python SDK for OpenFGA
API version: 1.x
Website: https://openfga.dev
Documentation: https://openfga.dev/docs
Support: https://openfga.dev/community
License: [Apache-2.0](https://github.com/openfga/python-sdk/blob/main/LICENSE)
NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT.
"""
import asyncio
import os
import sys
import uuid
from dotenv import load_dotenv
sdk_path = os.path.realpath(os.path.join(os.path.abspath(__file__), "..", "..", ".."))
sys.path.insert(0, sdk_path)
from openfga_sdk import (
ClientConfiguration,
Condition,
ConditionParamTypeRef,
CreateStoreRequest,
Metadata,
ObjectRelation,
OpenFgaClient,
ReadRequestTupleKey,
RelationMetadata,
RelationReference,
RelationshipCondition,
TypeDefinition,
Userset,
Usersets,
UserTypeFilter,
WriteAuthorizationModelRequest,
)
from openfga_sdk.client.models import (
ClientAssertion,
ClientBatchCheckItem,
ClientBatchCheckRequest,
ClientCheckRequest,
ClientListObjectsRequest,
ClientListRelationsRequest,
ClientReadChangesRequest,
ClientTuple,
ClientWriteRequest,
WriteTransactionOpts,
)
from openfga_sdk.client.models.list_users_request import ClientListUsersRequest
from openfga_sdk.credentials import CredentialConfiguration, Credentials
from openfga_sdk.models.fga_object import FgaObject
async def main():
load_dotenv()
credentials = Credentials()
if os.getenv("FGA_CLIENT_ID") is not None:
credentials = Credentials(
method="client_credentials",
configuration=CredentialConfiguration(
api_issuer=os.getenv("FGA_API_TOKEN_ISSUER"),
api_audience=os.getenv("FGA_API_AUDIENCE"),
client_id=os.getenv("FGA_CLIENT_ID"),
client_secret=os.getenv("FGA_CLIENT_SECRET"),
),
)
if os.getenv("FGA_API_URL") is not None:
configuration = ClientConfiguration(
api_url=os.getenv("FGA_API_URL"), credentials=credentials
)
else:
configuration = ClientConfiguration(
api_url="http://localhost:8080", credentials=credentials
)
async with OpenFgaClient(configuration) as fga_client:
# ListStores (before create)
print("Listing Stores")
response = await fga_client.list_stores()
print(f"Stores Count: {len(response.stores)}")
store_name = "Test Store"
# CreateStore (before create)
print("Creating Test Store")
body = CreateStoreRequest(name=store_name)
response = await fga_client.create_store(body)
print(f"Test Store ID: {response.id}")
# Set the store ID
fga_client.set_store_id(response.id)
# ListStores (after create)
print("Listing Stores")
response = await fga_client.list_stores()
print(f"Stores Count: {len(response.stores)}")
# GetStore (after create)
print("Getting Current Store")
response = await fga_client.get_store()
print(f"Current Store Name: {response.name}")
# ReadAuthorizationModels (before write)
print("Reading Authorization Models")
response = await fga_client.read_authorization_models()
print(f"Models Count: {len(response.authorization_models)}")
# ReadLatestAuthorizationModel (before write)
try:
response = await fga_client.read_latest_authorization_model()
if response.authorization_model is not None:
print(
f"Latest Authorization Model ID: {response.authorization_model.id}"
)
except Exception as err:
print("Latest Authorization Model not found")
raise err
# WriteAuthorizationModel
print("Writing an Authorization Model")
response = await fga_client.write_authorization_model(
WriteAuthorizationModelRequest(
schema_version="1.1",
type_definitions=[
TypeDefinition(type="user"),
TypeDefinition(
type="document",
relations=dict(
writer=Userset(
this=dict(),
),
viewer=Userset(
union=Usersets(
child=[
Userset(this=dict()),
Userset(
computed_userset=ObjectRelation(
object="",
relation="writer",
)
),
],
),
),
),
metadata=Metadata(
relations=dict(
writer=RelationMetadata(
directly_related_user_types=[
RelationReference(type="user"),
RelationReference(
type="user",
condition="ViewCountLessThan200",
),
]
),
viewer=RelationMetadata(
directly_related_user_types=[
RelationReference(type="user"),
]
),
)
),
),
],
conditions=dict(
ViewCountLessThan200=Condition(
name="ViewCountLessThan200",
expression="ViewCount < 200",
parameters=dict(
ViewCount=ConditionParamTypeRef(type_name="TYPE_NAME_INT"),
Type=ConditionParamTypeRef(type_name="TYPE_NAME_STRING"),
Name=ConditionParamTypeRef(type_name="TYPE_NAME_STRING"),
),
)
),
)
)
print(f"Authorization Model ID: {response.authorization_model_id}")
# ReadAuthorizationModels (after write)
print("Reading Authorization Models")
response = await fga_client.read_authorization_models()
print(f"Models Count: {len(response.authorization_models)}")
# ReadLatestAuthorizationModel (after write)
response = await fga_client.read_latest_authorization_model()
if response.authorization_model is not None:
print(f"Latest Authorization Model ID: {response.authorization_model.id}")
auth_model_id = response.authorization_model.id
# Write
print("Writing Tuples")
body = ClientWriteRequest(
writes=[
ClientTuple(
user="user:anne",
relation="writer",
object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
condition=RelationshipCondition(
name="ViewCountLessThan200",
context=dict(
Name="Roadmap",
Type="Document",
),
),
),
],
)
options = {
# You can rely on the model id set in the configuration or override it for this specific request
"authorization_model_id": auth_model_id
}
await fga_client.write(body, options)
print("Done Writing Tuples")
# Write
print("Writing Tuples - non txn")
body = ClientWriteRequest(
writes=[
ClientTuple(
user="user:beth",
relation="writer",
object="document:1",
condition=RelationshipCondition(
name="ViewCountLessThan200",
context=dict(
Name="Roadmap",
Type="Document",
),
),
),
ClientTuple(user="user:beth", relation="viewer", object="document:2"),
],
)
options = {
# You can rely on the model id set in the configuration or override it for this specific request
"authorization_model_id": auth_model_id,
"transaction": WriteTransactionOpts(max_per_chunk=1),
}
await fga_client.write(body, options)
print("Done Writing Tuples")
# Set the model ID
fga_client.set_authorization_model_id(auth_model_id)
# Read
print("Reading Tuples")
response = await fga_client.read(
ReadRequestTupleKey(user="user:anne", object="document:")
)
print(f"Read Tuples: {response.tuples}")
# ReadChanges
print("Reading Tuple Changes")
body = ClientReadChangesRequest(type="document")
response = await fga_client.read_changes(body)
print(f"Read Changes Tuples: {response.changes}")
# Check
print("Checking for access w/o context")
try:
response = await fga_client.check(
ClientCheckRequest(
user="user:anne",
relation="viewer",
object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
)
)
print(f"Allowed: {response.allowed}")
except Exception as err:
print(f"Failed due to: {err}")
# Checking for access with context
print("Checking for access with context")
response = await fga_client.check(
ClientCheckRequest(
user="user:anne",
relation="viewer",
object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
context=dict(ViewCount=100),
)
)
print(f"Allowed: {response.allowed}")
# Performing a BatchCheck
print("Checking for access via BatchCheck")
anne_cor_id = str(uuid.uuid4())
response = await fga_client.batch_check(
ClientBatchCheckRequest(
checks=[
ClientBatchCheckItem(
user="user:anne",
relation="viewer",
object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
context=dict(ViewCount=100),
correlation_id=anne_cor_id, # correlation_id is an optional parameter, the SDK will insert a value if not provided.
),
ClientBatchCheckItem(
user="user:bob",
relation="viewer",
object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
context=dict(ViewCount=100),
),
]
)
)
for result in response.result:
if result.correlation_id == anne_cor_id:
print(f"Anne allowed: {result.allowed}")
else:
print(f"{result.request.user} allowed: {result.allowed}")
# List objects with context
print("Listing objects for access with context")
response = await fga_client.list_objects(
ClientListObjectsRequest(
user="user:anne",
relation="viewer",
type="document",
context=dict(ViewCount=100),
)
)
print(f"Objects: {response.objects}")
# List relations w/o context
print("Listing relations for access w/o context")
response = await fga_client.list_relations(
ClientListRelationsRequest(
user="user:anne",
relations=["viewer", "writer"],
object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
)
)
print(f"Relations: {response}")
# List relations with context
print("Listing relations for access with context")
response = await fga_client.list_relations(
ClientListRelationsRequest(
user="user:anne",
relations=["viewer", "writer"],
object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
context=dict(ViewCount=100),
)
)
print(f"Relations: {response}")
# ListUsers
print("Listing user who have access to object")
response = await fga_client.list_users(
ClientListUsersRequest(
relation="viewer",
object=FgaObject(type="document", id="roadmap"),
user_filters=[
UserTypeFilter(type="user"),
],
context=dict(ViewCount=100),
)
)
print(f"Users: {response.users}")
# WriteAssertions
await fga_client.write_assertions(
[
ClientAssertion(
user="user:carl",
relation="writer",
object="document:budget",
expectation=True,
),
ClientAssertion(
user="user:anne",
relation="viewer",
object="document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
expectation=False,
),
]
)
print("Assertions updated")
# ReadAssertions
print("Reading Assertions")
response = await fga_client.read_assertions()
print(f"Assertions: {response.assertions}")
# DeleteStore
print("Deleting Current Store")
await fga_client.delete_store()
print(f"Deleted Store: {store_name}")
asyncio.run(main())