Skip to content

Commit

Permalink
fix(conditions): update example and fix list relations
Browse files Browse the repository at this point in the history
  • Loading branch information
rhamzeh committed Jan 9, 2024
1 parent 02f29ce commit 30a6362
Show file tree
Hide file tree
Showing 6 changed files with 211 additions and 131 deletions.
73 changes: 0 additions & 73 deletions example/example1/auth-model.json

This file was deleted.

181 changes: 160 additions & 21 deletions example/example1/example1.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import asyncio
import json

import openfga_sdk
from openfga_sdk.client.models import ClientAssertion, ClientCheckRequest, ClientReadChangesRequest, ClientTuple, ClientWriteRequest
from openfga_sdk.models import CreateStoreRequest, Metadata, ObjectRelation, RelationMetadata, TupleKey, TypeDefinition, Userset, Usersets, WriteAuthorizationModelRequest
from openfga_sdk import ClientConfiguration, OpenFgaClient
from openfga_sdk.client.models import ClientAssertion, ClientCheckRequest, ClientReadChangesRequest, ClientTuple, \
ClientWriteRequest, ClientListRelationsRequest, ClientListObjectsRequest, WriteTransactionOpts
from openfga_sdk.models import CreateStoreRequest, Metadata, ObjectRelation, RelationMetadata, TypeDefinition, \
Userset, Usersets, WriteAuthorizationModelRequest
from openfga_sdk import ClientConfiguration, OpenFgaClient, RelationReference, RelationshipCondition, \
ConditionParamTypeRef, Condition, ReadRequestTupleKey
from openfga_sdk.credentials import CredentialConfiguration, Credentials
import os

Expand Down Expand Up @@ -76,9 +77,65 @@ async def main():

# WriteAuthorizationModel
print('Writing an Authorization Model')
with open(os.path.join(os.path.dirname(__file__), 'auth-model.json')) as f:
auth_model_request = json.load(f)
response = await fga_client.write_authorization_model(auth_model_request)
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)
Expand All @@ -101,13 +158,13 @@ async def main():
user='user:anne',
relation='writer',
object='document:roadmap',
# condition=RelationshipCondition(
# name='ViewCountLessThan200',
# context=dict(
# Name='Roadmap',
# Type='Document',
# ),
# ),
condition=RelationshipCondition(
name='ViewCountLessThan200',
context=dict(
Name='Roadmap',
Type='Document',
),
),
),
],
)
Expand All @@ -118,12 +175,45 @@ async def main():
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(TupleKey(user='user:anne', object='document:'))
response = await fga_client.read(ReadRequestTupleKey(user='user:anne', object='document:'))
print(f"Read Tuples: {response.tuples}")

# ReadChanges
Expand All @@ -133,16 +223,65 @@ async def main():
print(f"Read Changes Tuples: {response.changes}")

# Check
print('Checking for access')
print('Checking for access w/o context')
try:
response = await fga_client.check(ClientCheckRequest(
user='user:anne',
relation='viewer',
object='document:roadmap'
))
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='reader',
relation='viewer',
object='document:roadmap',
context=dict(
ViewCount=100
)
))
print(f"Allowed: {response.allowed}")

# Checking for access with context
# TODO
# 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:roadmap'
))
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:roadmap',
context=dict(
ViewCount=100
)
))
print(f"Relations: {response}")

# WriteAssertions
await fga_client.write_assertions([
Expand All @@ -154,7 +293,7 @@ async def main():
),
ClientAssertion(
user='user:anne',
relation='reader',
relation='viewer',
object='document:roadmap',
expectation=False,
),
Expand Down
2 changes: 1 addition & 1 deletion openfga_sdk/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,7 @@ async def list_relations(self, body: ClientListRelationsRequest, options: dict[s
options = set_heading_if_not_set(options, CLIENT_BULK_REQUEST_ID_HEADER, str(uuid.uuid4()))

request_body = [construct_check_request(
user=body.user, relation=i, object=body.object, contextual_tuples=body.contextual_tuples) for i in body.relations]
user=body.user, relation=i, object=body.object, contextual_tuples=body.contextual_tuples, context=body.context) for i in body.relations]
result = await self.batch_check(request_body, options)
# need to filter with the allowed response
result_iterator = filter(_check_allowed, result)
Expand Down
Loading

0 comments on commit 30a6362

Please sign in to comment.