|
| 1 | +import logging |
| 2 | +from urllib.parse import quote |
| 3 | + |
| 4 | +# TODO: Polyfill. Replace with `from dataclasses import asdict` once support |
| 5 | +# for Python 3.6 is dropped. |
| 6 | +from okdata.sdk.permission.user_types import asdict |
| 7 | +from okdata.sdk import SDK |
| 8 | + |
| 9 | +log = logging.getLogger() |
| 10 | + |
| 11 | + |
| 12 | +class PermissionClient(SDK): |
| 13 | + def __init__(self, config=None, auth=None, env=None): |
| 14 | + self.__name__ = "permission" |
| 15 | + super().__init__(config, auth, env) |
| 16 | + self.api_url = self.config.get("permissionApiUrl") |
| 17 | + |
| 18 | + def update_permission( |
| 19 | + self, resource_name, scope, add_users=[], remove_users=[], retries=0 |
| 20 | + ): |
| 21 | + """Grant or revoke permissions for a resource. |
| 22 | +
|
| 23 | + `resource_name` must be given on the form "namespace:type:id", while |
| 24 | + `scope` must be given on the form "namespace:type:permission". |
| 25 | +
|
| 26 | + `add_users` and `remove_users` are iterables containing the users to |
| 27 | + give access to and to revoke access from, respectively. The users |
| 28 | + should be instances of the user types defined in |
| 29 | + `okdata.sdk.permission.user_types`. |
| 30 | +
|
| 31 | + Usage example giving read access to the dataset "my-dataset" to the |
| 32 | + user "janedoe": |
| 33 | +
|
| 34 | + update_permission( |
| 35 | + "okdata:dataset:my-dataset", |
| 36 | + "okdata:dataset:read", |
| 37 | + add_users=[User("janedoe")], |
| 38 | + ) |
| 39 | + """ |
| 40 | + url = "{}/permissions/{}".format(self.api_url, quote(resource_name)) |
| 41 | + data = { |
| 42 | + "add_users": list(map(asdict, add_users)), |
| 43 | + "remove_users": list(map(asdict, remove_users)), |
| 44 | + "scope": scope, |
| 45 | + } |
| 46 | + log.info(f"SDK:Updating permissions for {resource_name} with {data}") |
| 47 | + return self.put(url, data, retries=retries).json() |
| 48 | + |
| 49 | + def get_my_permissions(self, retries=0): |
| 50 | + """Return a dictionary of permissions associated with the current user. |
| 51 | +
|
| 52 | + The dictionary is on the form: |
| 53 | +
|
| 54 | + { |
| 55 | + "resource-name-1": {"scopes": ["scope-1", "scope-2"]}, |
| 56 | + "resource-name-2": ... |
| 57 | + } |
| 58 | + """ |
| 59 | + url = f"{self.api_url}/my_permissions" |
| 60 | + log.info(f"SDK:Listing permissions from: {url}") |
| 61 | + return self.get(url, retries=retries).json() |
| 62 | + |
| 63 | + def get_permissions(self, resource_name, retries=0): |
| 64 | + """Return a list of permissions associated with `resource_name`.""" |
| 65 | + url = "{}/permissions/{}".format(self.api_url, quote(resource_name)) |
| 66 | + log.info(f"SDK:Getting permissions for {resource_name} from: {url}") |
| 67 | + return self.get(url, retries=retries).json() |
0 commit comments