pineloco
05/23/2023, 5:43 PMpython
from authzed.api.v1 import (
Client,
Consistency,
ObjectReference,
LookupSubjectsRequest,
LookupResourcesRequest
)
from grpcutil import insecure_bearer_token_credentials
from config import HOST, PORT, TOKEN_CREDENTIAL
client = Client(
f"{HOST}:{PORT}",
insecure_bearer_token_credentials(TOKEN_CREDENTIAL),
)
def query_subject(resource_type: str, relation: str, s_type: str, s_id: str):
"""."""
subject = ObjectReference(object_type=s_type, object_id=s_id)
return client.LookupSubjects(
LookupSubjectsRequest(
subject_object_type=resource_type,
permission=relation,
resource=subject,
consistency=Consistency(fully_consistent=True),
)
)
def get_roles_by_user_and_institution(usr: str, institution: str):
"""This function returns all roles associated with a user filtered by an institution."""
roles = query_subject("rol", "belongs", "institution", institution)
users = {}
for role in roles:
user_associated = [
user.subject_object_id
for user in query_subject("user", "associated", "rol", role.subject_object_id)
if user.subject_object_id == usr
]
if user_associated:
users[role.subject_object_id] = user_associated[0]
return users
user_roles = get_roles_by_user_and_institution("Pepe", "Acme")
for user in user_roles:
print(user)
maybe is not best solution but found for me.