pax_global_header00006660000000000000000000000064145672104010014512gustar00rootroot0000000000000052 comment=4a6f112978ed05ed8cecedf85320b12b7ceb152c golang-github-openfga-go-sdk-0.3.5/000077500000000000000000000000001456721040100170455ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/.fossa.yml000066400000000000000000000002531456721040100207610ustar00rootroot00000000000000version: 3 server: https://app.fossa.com project: id: github.com/openfga/go-sdk name: github.com/openfga/go-sdk link: openfga.dev url: github.com/openfga/go-sdk golang-github-openfga-go-sdk-0.3.5/.github/000077500000000000000000000000001456721040100204055ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/.github/CODEOWNERS000066400000000000000000000000241456721040100217740ustar00rootroot00000000000000* @openfga/dx golang-github-openfga-go-sdk-0.3.5/.github/ISSUE_TEMPLATE/000077500000000000000000000000001456721040100225705ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000036221456721040100252650ustar00rootroot00000000000000--- name: Report an issue about: Create a bug report about an existing issue. title: '' labels: 'bug' assignees: '' --- **Please do not report security vulnerabilities here**. See the [Responsible Disclosure Program](https://github.com/openfga/go-sdk/blob/main/.github/SECURITY.md). **Thank you in advance for helping us to improve this library!** Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. By submitting an issue to this repository, you agree to the terms within the [OpenFGA Code of Conduct](https://github.com/openfga/rfcs/blob/main/CODE-OF-CONDUCT.md). ### Description > Provide a clear and concise description of the issue, including what you expected to happen. ### Version of SDK > v0.2.0 ### Version of OpenFGA (if known) > v1.1.0 ### OpenFGA Flags/Custom Configuration Applicable > environment: > - OPENFGA_DATASTORE_ENGINE=postgres > - OPENFGA_DATASTORE_URI=postgres://postgres:password@postgres:5432/postgres?sslmode=disable > - OPENFGA_TRACE_ENABLED=true > - OPENFGA_TRACE_SAMPLE_RATIO=1 > - OPENFGA_TRACE_OTLP_ENDPOINT=otel-collector:4317 > - OPENFGA_METRICS_ENABLE_RPC_HISTOGRAMS=true ### Reproduction > Detail the steps taken to reproduce this error, what was expected, and whether this issue can be reproduced consistently or if it is intermittent. > > 1. Initialize OpenFgaClient with openfga_sdk.ClientConfiguration parameter api_host=127.0.0.1, credentials method client_credentials > 2. Invoke method read_authorization_models > 3. See exception thrown ### Sample Code the Produces Issues > > ``` > > ``` ### Backtrace (if applicable) > ``` > > ``` ### Expected behavior > A clear and concise description of what you expected to happen. ### Additional context > Add any other context about the problem here. golang-github-openfga-go-sdk-0.3.5/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000022531456721040100263170ustar00rootroot00000000000000--- name: Feature request about: Suggest new functionality for this project. title: '' labels: 'feature' assignees: '' --- **Please do not report security vulnerabilities here**. See the [Responsible Disclosure Program](https://github.com/openfga/go-sdk/blob/main/.github/SECURITY.md). **Thank you in advance for helping us to improve this library!** Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. By submitting an issue to this repository, you agree to the terms within the [OpenFGA Code of Conduct](https://github.com/openfga/rfcs/blob/main/CODE-OF-CONDUCT.md). ### Describe the problem you'd like to have solved > A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] ### Describe the ideal solution > A clear and concise description of what you want to happen. ## Alternatives and current workarounds > A clear and concise description of any alternatives you've considered or any workarounds that are currently in place. ### Additional context > Add any other context or screenshots about the feature request here. golang-github-openfga-go-sdk-0.3.5/.github/dependabot.yaml000066400000000000000000000005211456721040100233740ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "gomod" directory: "/" schedule: interval: "weekly" groups: dependencies: patterns: - "*" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" groups: dependencies: patterns: - "*" golang-github-openfga-go-sdk-0.3.5/.github/dependabot.yml000066400000000000000000000005211456721040100232330ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "gomod" directory: "/" schedule: interval: "weekly" groups: dependencies: patterns: - "*" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" groups: dependencies: patterns: - "*" golang-github-openfga-go-sdk-0.3.5/.github/workflows/000077500000000000000000000000001456721040100224425ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/.github/workflows/main.yaml000066400000000000000000000022441456721040100242540ustar00rootroot00000000000000name: Build, Test and Publish on: merge_group: push: pull_request: workflow_dispatch: jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.5.4 with: fetch-depth: 0 - uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0 with: cache-dependency-path: './go.sum' check-latest: true go-version: '>=1.21.1' - name: Build run: go build -v ./... - name: Test run: go test -v ./... - name: Install govulncheck run: go install golang.org/x/vuln/cmd/govulncheck@latest - name: Run govulncheck run: govulncheck ./... create-release: runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/tags/v') needs: [test] steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.5.4 with: fetch-depth: 0 - uses: Roang-zero1/github-create-release-action@57eb9bdce7a964e48788b9e78b5ac766cb684803 with: version_regex: ^v[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+ env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} golang-github-openfga-go-sdk-0.3.5/.github/workflows/semgrep.yaml000066400000000000000000000007321456721040100247720ustar00rootroot00000000000000name: Semgrep on: push: branches: - main jobs: semgrep: name: Scan runs-on: ubuntu-latest container: image: returntocorp/semgrep if: (github.actor != 'dependabot[bot]' && github.actor != 'snyk-bot') steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 with: fetch-depth: 0 - run: semgrep ci --no-suppress-errors env: SEMGREP_APP_TOKEN: ${{ secrets.SEMGREP_APP_TOKEN }} golang-github-openfga-go-sdk-0.3.5/.gitignore000066400000000000000000000007301456721040100210350ustar00rootroot00000000000000# Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *.test *.prof # IDEs .idea .vscode .sublime-workspace .sublime-project .idea/ .vscode/ # Possible credential files .env credentials.json # git conflict leftover files *.orig # Mac .DS_Store VERSION.txt git_push.sh golang-github-openfga-go-sdk-0.3.5/.openapi-generator-ignore000066400000000000000000000001011456721040100237360ustar00rootroot00000000000000.travis.yml api/openapi.yaml test/api_open_fga_test.go client.go golang-github-openfga-go-sdk-0.3.5/.openapi-generator/000077500000000000000000000000001456721040100225425ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/.openapi-generator/FILES000066400000000000000000000106261456721040100233340ustar00rootroot00000000000000.fossa.yml .github/CODEOWNERS .github/ISSUE_TEMPLATE/bug_report.md .github/ISSUE_TEMPLATE/feature_request.md .github/dependabot.yaml .github/workflows/main.yaml .github/workflows/semgrep.yaml .gitignore CHANGELOG.md CONTRIBUTING.md LICENSE NOTICE.txt README.md VERSION.txt api_client.go api_open_fga.go api_open_fga_test.go client/client.go client/client_test.go client/errors.go configuration.go credentials/credentials.go docs/AbortedMessageResponse.md docs/Any.md docs/Assertion.md docs/AssertionTupleKey.md docs/AuthorizationModel.md docs/CheckRequest.md docs/CheckRequestTupleKey.md docs/CheckResponse.md docs/Computed.md docs/Condition.md docs/ConditionParamTypeRef.md docs/ContextualTupleKeys.md docs/CreateStoreRequest.md docs/CreateStoreResponse.md docs/Difference.md docs/ErrorCode.md docs/ExpandRequest.md docs/ExpandRequestTupleKey.md docs/ExpandResponse.md docs/GetStoreResponse.md docs/InternalErrorCode.md docs/InternalErrorMessageResponse.md docs/Leaf.md docs/ListObjectsRequest.md docs/ListObjectsResponse.md docs/ListStoresResponse.md docs/Metadata.md docs/Node.md docs/Nodes.md docs/NotFoundErrorCode.md docs/NullValue.md docs/ObjectRelation.md docs/OpenFgaApi.md docs/PathUnknownErrorMessageResponse.md docs/ReadAssertionsResponse.md docs/ReadAuthorizationModelResponse.md docs/ReadAuthorizationModelsResponse.md docs/ReadChangesResponse.md docs/ReadRequest.md docs/ReadRequestTupleKey.md docs/ReadResponse.md docs/RelationMetadata.md docs/RelationReference.md docs/RelationshipCondition.md docs/Status.md docs/Store.md docs/Tuple.md docs/TupleChange.md docs/TupleKey.md docs/TupleKeyWithoutCondition.md docs/TupleOperation.md docs/TupleToUserset.md docs/TypeDefinition.md docs/TypeName.md docs/Users.md docs/Userset.md docs/UsersetTree.md docs/UsersetTreeDifference.md docs/UsersetTreeTupleToUserset.md docs/Usersets.md docs/ValidationErrorMessageResponse.md docs/WriteAssertionsRequest.md docs/WriteAuthorizationModelRequest.md docs/WriteAuthorizationModelResponse.md docs/WriteRequest.md docs/WriteRequestDeletes.md docs/WriteRequestWrites.md example/Makefile example/README.md example/example1/example1.go example/example1/go.mod example/example1/go.sum git_push.sh go.mod go.sum internal/utils/randomtime.go internal/utils/ulid.go internal/utils/ulid_test.go model_aborted_message_response.go model_any.go model_assertion.go model_assertion_tuple_key.go model_authorization_model.go model_check_request.go model_check_request_tuple_key.go model_check_response.go model_computed.go model_condition.go model_condition_param_type_ref.go model_contextual_tuple_keys.go model_create_store_request.go model_create_store_response.go model_difference.go model_error_code.go model_expand_request.go model_expand_request_tuple_key.go model_expand_response.go model_get_store_response.go model_internal_error_code.go model_internal_error_message_response.go model_leaf.go model_list_objects_request.go model_list_objects_response.go model_list_stores_response.go model_metadata.go model_node.go model_nodes.go model_not_found_error_code.go model_null_value.go model_object_relation.go model_path_unknown_error_message_response.go model_read_assertions_response.go model_read_authorization_model_response.go model_read_authorization_models_response.go model_read_changes_response.go model_read_request.go model_read_request_tuple_key.go model_read_response.go model_relation_metadata.go model_relation_reference.go model_relationship_condition.go model_status.go model_store.go model_tuple.go model_tuple_change.go model_tuple_key.go model_tuple_key_without_condition.go model_tuple_operation.go model_tuple_to_userset.go model_type_definition.go model_type_name.go model_users.go model_userset.go model_userset_tree.go model_userset_tree_difference.go model_userset_tree_tuple_to_userset.go model_usersets.go model_validation_error_message_response.go model_write_assertions_request.go model_write_authorization_model_request.go model_write_authorization_model_response.go model_write_request.go model_write_request_deletes.go model_write_request_writes.go oauth2/LICENSE oauth2/ORIGINAL_AUTHORS oauth2/ORIGINAL_CONTRIBUTORS oauth2/README.md oauth2/clientcredentials/clientcredentials.go oauth2/clientcredentials/clientcredentials_test.go oauth2/internal/doc.go oauth2/internal/token.go oauth2/internal/token_test.go oauth2/internal/transport.go oauth2/oauth2.go oauth2/oauth2_test.go oauth2/token.go oauth2/token_test.go oauth2/transport.go oauth2/transport_test.go response.go utils.go golang-github-openfga-go-sdk-0.3.5/.openapi-generator/VERSION000066400000000000000000000000051456721040100236050ustar00rootroot000000000000006.4.0golang-github-openfga-go-sdk-0.3.5/CHANGELOG.md000066400000000000000000000166001456721040100206610ustar00rootroot00000000000000# Changelog ## v0.3.5 ### [0.3.5](https://github.com/openfga/go-sdk/compare/v0.3.4...v0.3.5) (2024-02-13) - fix: don't escape HTML characters in conditions when marshalling a model ## v0.3.4 ### [0.3.4](https://github.com/openfga/go-sdk/compare/v0.3.3...v0.3.4) (2024-01-22) - feat: configurable client credentials token url - thanks @le-yams - fix: WriteAuthorizationModel was not passing conditions to API ## v0.3.3 ### [0.3.3](https://github.com/openfga/go-sdk/compare/v0.3.2...v0.3.3) (2023-12-21) - fix: WriteAuthorizationModel was not passing conditions to API - chore: add [example project](./example) ## v0.3.2 ### [0.3.2](https://github.com/openfga/go-sdk/compare/v0.3.1...v0.3.2) (2023-12-20) - fix: ListObjects was not passing context to API - chore: downgrade target go version to 1.20 ## v0.3.1 ### [0.3.1](https://github.com/openfga/go-sdk/compare/v0.3.0...v0.3.1) (2023-12-19) - feat: oauth2 client credentials support (#62), thanks @le-yams - fix: remove canonical import path from oauth2 packages (#64), thanks @bketelsen ## v0.3.0 ### [0.3.0](https://github.com/openfga/go-sdk/compare/v0.2.3...v0.3.0) (2023-12-11) - feat!: initial support for [conditions](https://openfga.dev/blog/conditional-tuples-announcement) - feat: support specifying a port and path for the API (You can now set the `ApiUrl` to something like: `https://api.fga.exampleL8080/some_path`) - fix: resolve a bug in `NewCredentials` (#60) - thanks @harper - chore!: use latest API interfaces - chore: dependency updates BREAKING CHANGES: Note: This release comes with substantial breaking changes, especially to the interfaces due to the protobuf changes in the last release. While the http interfaces did not break (you can still use `v0.2.3` SDK with a `v1.3.8+` server), the grpc interface did and this caused a few changes in the interfaces of the SDK. You will have to modify some parts of your code, but we hope this will be to the better as a lot of the parameters are now correctly marked as required, and so the Pointer-to-String conversion is no longer needed. Some of the changes to expect: * When initializing a client, please use `ApiUrl`. The separate `ApiScheme` and `ApiHost` fields have been deprecated ```go fgaClient, err := NewSdkClient(&ClientConfiguration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` AuthorizationModelId: os.Getenv("FGA_AUTHORIZATION_MODEL_ID"), // optional, recommended to be set for production }) ``` - When initializing a client, `AuthorizationModelId` is no longer a pointer, and you can just pass the string directly - The `OpenFgaClient` now has methods to get and set the model ID `GetAuthorizationModelId` and `SetAuthorizationModelId` - The following request interfaces changed: - `CheckRequest`: the `TupleKey` field is now of interface `CheckRequestTupleKey`, you can also now pass in `Context` - `ExpandRequest`: the `TupleKey` field is now of interface `ExpandRequestTupleKey` - `ReadRequest`: the `TupleKey` field is now of interface `ReadRequestTupleKey` - `WriteRequest`: now takes `WriteRequestWrites` and `WriteRequestDeletes` - And more - The following interfaces had fields that were pointers are are now the direct value: - `CreateStoreResponse` - `GetStoreResponse` - `ListStoresResponse` - `ListObjectsResponse` - `ReadChangesResponse` - `ReadResponse` - `AuthorizationModel` and several interfaces under it - And more ## v0.2.3 ### [0.2.3](https://github.com/openfga/go-sdk/compare/v0.2.2...v0.2.3) (2023-10-13) - fix: allow setting user agent - fix(client): resolve null pointer exceptions when getting auth model id - fix(client): allow read to contain empty fields - fix(client): require auth model id and store id to be ulids - fix(client): resolve cases where req options was not respected - fix: add retry logic to oauth - chore: target go1.21.3 and upgrade dependencies ## v0.2.2 ### [0.2.2](https://github.com/openfga/go-sdk/compare/v0.2.1...v0.2.2) (2023-04-21) - feat(client): add OpenFgaClient wrapper see [docs](https://github.com/openfga/go-sdk/tree/main#readme), see the `v0.2.1` docs for [the OpenFgaApi docs](https://github.com/openfga/go-sdk/tree/v0.2.1#readme) - feat(client): implement `BatchCheck` to check multiple tuples in parallel - feat(client): implement `ListRelations` to check in one call whether a user has multiple relations to an objects - feat(client): add support for a non-transactional `Write` - chore(config): bump default max retries to `15` - fix(config)!: make the capitalization of the json equivalent of the configuration consistent - fix: retry on 5xx errors ## v0.2.1 ### [0.2.1](https://github.com/openfga/go-sdk/compare/v0.2.0...v0.2.1) (2023-01-17) - chore(deps): upgrade `golang.org/x/net` dependency ## v0.2.0 ### [0.2.0](https://github.com/openfga/go-sdk/compare/v0.1.1...v0.2.0) (2022-12-14) Updated to include support for [OpenFGA 0.3.0](https://github.com/openfga/openfga/releases/tag/v0.3.0) Changes: - [BREAKING] feat(list-objects)!: response has been changed to include the object type e.g. response that was `{"object_ids":["roadmap"]}`, will now be `{"objects":["document:roadmap"]}` Fixes: - [BREAKING] fix(models): update interfaces that had incorrectly optional fields to make them required Chore: - chore(deps): update dev dependencies ## v0.1.1 ### [0.1.1](https://github.com/openfga/go-sdk/compare/v0.1.0...v0.1.1) (2022-09-30) - chore(deps): upgrade dependencies - dependency updates were accidentally reverted in v0.1.0 release ## v0.1.0 ### [0.1.0](https://github.com/openfga/go-sdk/compare/v0.0.3...v0.1.0) (2022-09-29) - BREAKING: exported interface `TypeDefinitions` is now `WriteAuthorizationModelRequest` This is only a breaking change on the SDK, not the API. It was changed to conform to the proto changes in [openfga/api](https://github.com/openfga/api/pull/27). - chore(deps): upgrade dependencies ## v0.0.3 ### [0.0.3](https://github.com/openfga/go-sdk/compare/v0.0.2...v0.0.3) (2022-09-07) - Fix incorrectly applying client_credentials validation to api_token cred method [openfga/sdk-generator#21](https://github.com/openfga/sdk-generator/pull/21) - Target go 1.19 - Bump golang.org/x/net - Use [govulncheck](https://go.dev/blog/vuln) in CI to check for issues ## v0.0.2 ### [0.0.2](https://github.com/openfga/go-sdk/compare/v0.0.1...v0.0.2) (2022-08-15) Support for [ListObjects API]](https://openfga.dev/api/service#/Relationship%20Queries/ListObjects) You call the API and receive the list of object ids from a particular type that the user has a certain relation with. For example, to find the list of documents that Anne can read: ```golang body := openfga.ListObjectsRequest{ AuthorizationModelId: PtrString(""), User: PtrString("anne"), Relation: PtrString("can_view"), Type: PtrString("document"), } data, response, err := apiClient.OpenFgaApi.ListObjects(context.Background()).Body(body).Execute() // response.object_ids = ["roadmap"] ``` ## v0.0.1 ### [0.0.1](https://github.com/openfga/go-sdk/releases/tag/v0.0.1) (2022-06-16) Initial OpenFGA Go SDK release - Support for [OpenFGA](https://github.com/openfga/openfga) API - CRUD stores - Create, read & list authorization models - Writing and Reading Tuples - Checking authorization - Using Expand to understand why access was granted golang-github-openfga-go-sdk-0.3.5/CONTRIBUTING.md000066400000000000000000000054361456721040100213060ustar00rootroot00000000000000# Contributing to OpenFGA projects A big welcome and thank you for considering contributing to the OpenFGA open source projects. It’s people like you that make it a reality for users in our community. Reading and following these guidelines will help us make the contribution process easy and effective for everyone involved. It also communicates that you agree to respect the time of the developers managing and developing these open source projects. In return, we will reciprocate that respect by addressing your issue, assessing changes, and helping you finalize your pull requests. ### Table of Contents * [Code of Conduct](#code-of-conduct) * [Getting Started](#getting-started) * [Making Changes](#making-changes) * [Opening Issues](#opening-issues) * [Submitting Pull Requests](#submitting-pull-requests) [Note: We are not accepting Pull Requests at this time!] * [Getting in Touch](#getting-in-touch) * [Have a question or problem?](#have-a-question-or-problem) * [Vulnerability Reporting](#vulnerability-reporting) ## Code of Conduct By participating and contributing to this project, you are expected to uphold our [Code of Conduct](https://github.com/openfga/.github/blob/main/CODE_OF_CONDUCT.md). ## Getting Started ### Making Changes When contributing to a repository, the first step is to open an issue on [sdk-generator](https://github.com/openfga/sdk-generator) to discuss the change you wish to make before making them. ### Opening Issues Before you submit a new issue please make sure to search all open and closed issues. It is possible your feature request/issue has already been answered. Make sure to also check the [OpenFGA discussions](https://github.com/orgs/openfga/discussions). That repo includes an issue template that will walk through all the places to check before submitting your issue here. Please follow the instructions there to make sure this is not a duplicate issue and that we have everything we need to research and reproduce this problem. ### Submitting Pull Requests Considering that the SDKs are autogenerated, please make sure to submit your Pull Requests to the [sdk-generator](https://github.com/openfga/sdk-generator). We will not accept PRs to this repository because they will be overwritten on the next sdk generation. ## Getting in touch ### Have a question or problem? Please do not open issues for general support or usage questions. Instead, join us over in the [OpenFGA discussions](https://github.com/orgs/openfga/discussions) or [support community](https://discord.gg/8naAwJfWN6). ### Vulnerability Reporting Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://github.com/openfga/go-sdk/blob/main/.github/SECURITY.md) details the procedure for disclosing security issues. golang-github-openfga-go-sdk-0.3.5/LICENSE000066400000000000000000000237001456721040100200540ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS golang-github-openfga-go-sdk-0.3.5/NOTICE.txt000066400000000000000000000467371456721040100206100ustar00rootroot00000000000000Go SDK for OpenFGA github.com/openfga/go-sdk Copyright (c) 2022 the OpenFGA contributors (https://openfga.dev) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- ================================================================================ ================================================================================ Third-Party Software for go-sdk -------------------------------------------------------------------------------- The following 3rd-party software packages may be used by or distributed with go-sdk. Any information relevant to third-party vendors listed below are collected using common, reasonable means. Date generated: 2023-3-2 Revision ID: 0150dad4c6eb338d4c808a15505c6f80453d6b7f ================================================================================ ================================================================================ ================================================================================ Dependencies ================================================================================ - github.com/jarcoal/httpmock (v1.2.0) [MIT] -------------------------------------------------------------------------------- Package Title: github.com/jarcoal/httpmock (v1.2.0) -------------------------------------------------------------------------------- * Declared Licenses * MIT The MIT License (MIT) Copyright (c) 2014 Jared Morse Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ Licenses ================================================================================ * Apache-2.0 * Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * BSD-2-Clause * Copyright (c) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * BSD-3-Clause * Copyright (c) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ISC * ISC License Copyright (c) 2004-2010 by Internet Systems Consortium, Inc. ("ISC") Copyright (c) 1995-2003 by Internet Software Consortium Permission to use, copy, modify, and /or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * MIT * MIT License Copyright (c) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * MIT * The MIT License (MIT) Copyright (c) 2014 Jared Morse Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Report Generated by FOSSA on 2023-3-2 golang-github-openfga-go-sdk-0.3.5/README.md000066400000000000000000001032321456721040100203250ustar00rootroot00000000000000# Go SDK for OpenFGA [![Go Reference](https://pkg.go.dev/badge/github.com/openfga/go-sdk.svg)](https://pkg.go.dev/github.com/openfga/go-sdk) [![Release](https://img.shields.io/github/v/release/openfga/go-sdk?sort=semver&color=green)](https://github.com/openfga/go-sdk/releases) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](./LICENSE) [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fopenfga%2Fgo-sdk.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fopenfga%2Fgo-sdk?ref=badge_shield) [![Discord Server](https://img.shields.io/discord/759188666072825867?color=7289da&logo=discord "Discord Server")](https://discord.gg/8naAwJfWN6) [![Twitter](https://img.shields.io/twitter/follow/openfga?color=%23179CF0&logo=twitter&style=flat-square "@openfga on Twitter")](https://twitter.com/openfga) This is an autogenerated Go SDK for OpenFGA. It provides a wrapper around the [OpenFGA API definition](https://openfga.dev/api). ## Table of Contents - [About OpenFGA](#about) - [Resources](#resources) - [Installation](#installation) - [Getting Started](#getting-started) - [Initializing the API Client](#initializing-the-api-client) - [Get your Store ID](#get-your-store-id) - [Calling the API](#calling-the-api) - [Stores](#stores) - [List All Stores](#list-stores) - [Create a Store](#create-store) - [Get a Store](#get-store) - [Delete a Store](#delete-store) - [Authorization Models](#authorization-models) - [Read Authorization Models](#read-authorization-models) - [Write Authorization Model](#write-authorization-model) - [Read a Single Authorization Model](#read-a-single-authorization-model) - [Read the Latest Authorization Model](#read-the-latest-authorization-model) - [Relationship Tuples](#relationship-tuples) - [Read Relationship Tuple Changes (Watch)](#read-relationship-tuple-changes-watch) - [Read Relationship Tuples](#read-relationship-tuples) - [Write (Create and Delete) Relationship Tuples](#write-create-and-delete-relationship-tuples) - [Relationship Queries](#relationship-queries) - [Check](#check) - [Batch Check](#batch-check) - [Expand](#expand) - [List Objects](#list-objects) - [List Relations](#list-relations) - [Assertions](#assertions) - [Read Assertions](#read-assertions) - [Write Assertions](#write-assertions) - [API Endpoints](#api-endpoints) - [Models](#models) - [Contributing](#contributing) - [Issues](#issues) - [Pull Requests](#pull-requests) - [License](#license) ## About [OpenFGA](https://openfga.dev) is an open source Fine-Grained Authorization solution inspired by [Google's Zanzibar paper](https://research.google/pubs/pub48190/). It was created by the FGA team at [Auth0](https://auth0.com) based on [Auth0 Fine-Grained Authorization (FGA)](https://fga.dev), available under [a permissive license (Apache-2)](https://github.com/openfga/rfcs/blob/main/LICENSE) and welcomes community contributions. OpenFGA is designed to make it easy for application builders to model their permission layer, and to add and integrate fine-grained authorization into their applications. OpenFGA’s design is optimized for reliability and low latency at a high scale. ## Resources - [OpenFGA Documentation](https://openfga.dev/docs) - [OpenFGA API Documentation](https://openfga.dev/api/service) - [Twitter](https://twitter.com/openfga) - [OpenFGA Discord Community](https://discord.gg/8naAwJfWN6) - [Zanzibar Academy](https://zanzibar.academy) - [Google's Zanzibar Paper (2019)](https://research.google/pubs/pub48190/) ## Installation To install: ``` go get -u github.com/openfga/go-sdk ``` In your code, import the module and use it: ```go import "github.com/openfga/go-sdk" func Main() { configuration, err := openfga.NewConfiguration(openfga.Configuration{}) } ``` You can then run ```shell go mod tidy ``` to update `go.mod` and `go.sum` if you are using them. ## Getting Started ### Initializing the API Client [Learn how to initialize your SDK](https://openfga.dev/docs/getting-started/setup-sdk-client) The documentation below refers to the `openfgaClient`, to read the documentation for `openfgaApi`, check out the [`v0.2.1` documentation](https://github.com/openfga/go-sdk/tree/v0.2.1#readme). > The openfgaClient will by default retry API requests up to 15 times on 429 and 5xx errors. #### No Credentials ```golang import ( . "github.com/openfga/go-sdk/client" "os" ) func main() { fgaClient, err := NewSdkClient(&ClientConfiguration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` AuthorizationModelId: os.Getenv("FGA_AUTHORIZATION_MODEL_ID"), // optional, recommended to be set for production }) if err != nil { // .. Handle error } } ``` #### API Token ```golang import ( . "github.com/openfga/go-sdk/client" "github.com/openfga/go-sdk/credentials" "os" ) func main() { fgaClient, err := NewSdkClient(&ClientConfiguration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` AuthorizationModelId: os.Getenv("FGA_AUTHORIZATION_MODEL_ID"), // optional, recommended to be set for production Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodApiToken, Config: &credentials.Config{ ApiToken: os.Getenv("FGA_API_TOKEN"), // will be passed as the "Authorization: Bearer ${ApiToken}" request header }, }, }) if err != nil { // .. Handle error } } ``` #### Auth0 Client Credentials ```golang import ( openfga "github.com/openfga/go-sdk" . "github.com/openfga/go-sdk/client" "github.com/openfga/go-sdk/credentials" "os" ) func main() { fgaClient, err := NewSdkClient(&ClientConfiguration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` AuthorizationModelId: os.Getenv("FGA_AUTHORIZATION_MODEL_ID"), // optional, recommended to be set for production Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodClientCredentials, Config: &credentials.Config{ ClientCredentialsClientId: os.Getenv("FGA_CLIENT_ID"), ClientCredentialsClientSecret: os.Getenv("FGA_CLIENT_SECRET"), ClientCredentialsApiAudience: os.Getenv("FGA_API_AUDIENCE"), ClientCredentialsApiTokenIssuer: os.Getenv("FGA_API_TOKEN_ISSUER"), }, }, }) if err != nil { // .. Handle error } } ``` #### OAuth2 Client Credentials ```golang import ( openfga "github.com/openfga/go-sdk" . "github.com/openfga/go-sdk/client" "github.com/openfga/go-sdk/credentials" "os" ) func main() { fgaClient, err := NewSdkClient(&ClientConfiguration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` AuthorizationModelId: os.Getenv("FGA_AUTHORIZATION_MODEL_ID"), // optional, recommended to be set for production Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodClientCredentials, Config: &credentials.Config{ ClientCredentialsClientId: os.Getenv("FGA_CLIENT_ID"), ClientCredentialsClientSecret: os.Getenv("FGA_CLIENT_SECRET"), ClientCredentialsScopes: os.Getenv("FGA_API_SCOPES"), // optional space separated scopes ClientCredentialsApiTokenIssuer: os.Getenv("FGA_API_TOKEN_ISSUER"), }, }, }) if err != nil { // .. Handle error } } ``` ### Get your Store ID You need your store id to call the OpenFGA API (unless it is to call the [CreateStore](#create-store) or [ListStores](#list-stores) methods). If your server is configured with [authentication enabled](https://openfga.dev/docs/getting-started/setup-openfga#configuring-authentication), you also need to have your credentials ready. ### Calling the API #### Stores ##### List Stores Get a paginated list of stores. [API Documentation](https://openfga.dev/api/service/docs/api#/Stores/ListStores) ```golang options := ClientListStoresOptions{ PageSize: openfga.PtrInt32(10), ContinuationToken: openfga.PtrString("..."), } stores, err := fgaClient.ListStores(context.Background()).Options(options).Execute() // stores = [{ "id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z" }] ``` ##### Create Store Create and initialize a store. [API Documentation](https://openfga.dev/api/service/docs/api#/Stores/CreateStore) ```golang body := ClientCreateStoreRequest{Name: "FGA Demo"} store, err := fgaClient.CreateStore(context.Background()).Body(body).Execute() if err != nil { // handle error } // store.Id = "01FQH7V8BEG3GPQW93KTRFR8JB" // store store.Id in database // update the storeId of the current instance fgaClient.SetStoreId(store.Id) // continue calling the API normally, scoped to this store ``` ##### Get Store Get information about the current store. [API Documentation](https://openfga.dev/api/service/docs/api#/Stores/GetStore) > Requires a client initialized with a storeId ```golang store, err := fgaClient.GetStore(context.Background()).Execute() if err != nil { // handle error } // store = { "id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z" } ``` ##### Delete Store Delete a store. [API Documentation](https://openfga.dev/api/service/docs/api#/Stores/DeleteStore) > Requires a client initialized with a storeId ```golang _, err := fgaClient.DeleteStore(context.Background()).Execute() if err != nil { // handle error } ``` #### Authorization Models ##### Read Authorization Models Read all authorization models in the store. [API Documentation](https://openfga.dev/api/service#/Authorization%20Models/ReadAuthorizationModels) ```golang options := ClientReadAuthorizationModelsOptions{ PageSize: openfga.PtrInt32(10), ContinuationToken: openfga.PtrString("..."), } data, err := fgaClient.ReadAuthorizationModels(context.Background()).Options(options).Execute() // data.AuthorizationModels = [ // { Id: "01GXSA8YR785C4FYS3C0RTG7B1", SchemaVersion: "1.1", TypeDefinitions: [...] }, // { Id: "01GXSBM5PVYHCJNRNKXMB4QZTW", SchemaVersion: "1.1", TypeDefinitions: [...] }]; ``` ##### Write Authorization Model Create a new authorization model. [API Documentation](https://openfga.dev/api/service#/Authorization%20Models/WriteAuthorizationModel) > Note: To learn how to build your authorization model, check the Docs at https://openfga.dev/docs. > Learn more about [the OpenFGA configuration language](https://openfga.dev/docs/configuration-language). > You can use the [OpenFGA Syntax Transformer](https://github.com/openfga/syntax-transformer) to convert between the friendly DSL and the JSON authorization model. ```golang body := ClientWriteAuthorizationModelRequest{ SchemaVersion: "1.1", TypeDefinitions: []openfga.TypeDefinition{ {Type: "user", Relations: &map[string]openfga.Userset{}}, { Type: "document", Relations: &map[string]openfga.Userset{ "writer": { This: &map[string]interface{}{}, }, "viewer": {Union: &openfga.Usersets{ Child: &[]openfga.Userset{ {This: &map[string]interface{}{}}, {ComputedUserset: &openfga.ObjectRelation{ Object: openfga.PtrString(""), Relation: openfga.PtrString("writer"), }}, }, }}, }, Metadata: &openfga.Metadata{ Relations: &map[string]openfga.RelationMetadata{ "writer": { DirectlyRelatedUserTypes: &[]openfga.RelationReference{ {Type: "user"}, }, }, "viewer": { DirectlyRelatedUserTypes: &[]openfga.RelationReference{ {Type: "user"}, }, }, }, }, }}, } data, err := fgaClient.WriteAuthorizationModel(context.Background()).Body(body).Execute() fmt.Printf("%s", data.AuthorizationModelId) // 01GXSA8YR785C4FYS3C0RTG7B1 ``` ##### Read a Single Authorization Model Read a particular authorization model. [API Documentation](https://openfga.dev/api/service#/Authorization%20Models/ReadAuthorizationModel) ```golang options := ClientReadAuthorizationModelOptions{ // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId: openfga.PtrString(modelId), } data, err := fgaClient.ReadAuthorizationModel(context.Background()).Options(options).Execute() // data = {"authorization_model":{"id":"01GXSA8YR785C4FYS3C0RTG7B1","schema_version":"1.1","type_definitions":[{"type":"document","relations":{"writer":{"this":{}},"viewer":{ ... }}},{"type":"user"}]}} // JSON fmt.Printf("%s", data.AuthorizationModel.Id) // 01GXSA8YR785C4FYS3C0RTG7B1 ``` ##### Read the Latest Authorization Model Reads the latest authorization model (note: this ignores the model id in configuration). [API Documentation](https://openfga.dev/api/service#/Authorization%20Models/ReadAuthorizationModel) ```golang data, err := fgaClient.ReadLatestAuthorizationModel(context.Background()).Execute() // data.AuthorizationModel.Id = "01GXSA8YR785C4FYS3C0RTG7B1" // data.AuthorizationModel.SchemaVersion = "1.1" // data.AuthorizationModel.TypeDefinitions = [{ "type": "document", "relations": { ... } }, { "type": "user", "relations": { ... }}] fmt.Printf("%s", (*data.AuthorizationModel).GetId()) // 01GXSA8YR785C4FYS3C0RTG7B1 ``` #### Relationship Tuples ##### Read Relationship Tuple Changes (Watch) Reads the list of historical relationship tuple writes and deletes. [API Documentation](https://openfga.dev/api/service#/Relationship%20Tuples/ReadChanges) ```golang body := ClientReadChangesRequest{ Type: "document", } options := ClientReadChangesOptions{ PageSize: openfga.PtrInt32(10), ContinuationToken: openfga.PtrString("eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="), } data, err := fgaClient.ReadChanges(context.Background()).Body(body).Options(options).Execute() // data.ContinuationToken = ... // data.Changes = [ // { TupleKey: { User, Relation, Object }, Operation: TupleOperation.WRITE, Timestamp: ... }, // { TupleKey: { User, Relation, Object }, Operation: TupleOperation.DELETE, Timestamp: ... } // ] ``` ##### Read Relationship Tuples Reads the relationship tuples stored in the database. It does not evaluate nor exclude invalid tuples according to the authorization model. [API Documentation](https://openfga.dev/api/service#/Relationship%20Tuples/Read) ```golang // Find if a relationship tuple stating that a certain user is a viewer of a certain document body := ClientReadRequest{ User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"), Relation: openfga.PtrString("viewer"), Object: openfga.PtrString("document:roadmap"), } // Find all relationship tuples where a certain user has a relationship as any relation to a certain document body := ClientReadRequest{ User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"), Object: openfga.PtrString("document:roadmap"), } // Find all relationship tuples where a certain user is a viewer of any document body := ClientReadRequest{ User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"), Relation: openfga.PtrString("viewer"), Object: openfga.PtrString("document:"), } // Find all relationship tuples where any user has a relationship as any relation with a particular document body := ClientReadRequest{ Object: openfga.PtrString("document:roadmap"), } // Read all stored relationship tuples body := ClientReadRequest{} options := ClientReadOptions{ PageSize: openfga.PtrInt32(10), ContinuationToken: openfga.PtrString("eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="), } data, err := fgaClient.Read(context.Background()).Body(requestBody).Options(options).Execute() // In all the above situations, the response will be of the form: // data = { Tuples: [{ Key: { User, Relation, Object }, Timestamp }, ...]} ``` ##### Write (Create and Delete) Relationship Tuples Create and/or delete relationship tuples to update the system state. [API Documentation](https://openfga.dev/api/service#/Relationship%20Tuples/Write) ###### Transaction mode (default) By default, write runs in a transaction mode where any invalid operation (deleting a non-existing tuple, creating an existing tuple, one of the tuples was invalid) or a server error will fail the entire operation. ```golang body := ClientWriteRequest{ Writes: &[]ClientTupleKey{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:budget", } }, Deletes: &[]ClientTupleKeyWithoutCondition{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "writer", Object: "document:roadmap", } } } options := ClientWriteOptions{ // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } data, err := fgaClient.Write(context.Background()).Body(requestBody).Options(options).Execute() ``` Convenience `WriteTuples` and `DeleteTuples` methods are also available. ###### Non-transaction mode The SDK will split the writes into separate chunks and send them in separate requests. Each chunk is a transaction. By default, each chunk is set to 1, but you may override that. ```golang body := ClientWriteRequest{ Writes: &[]ClientTupleKey{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:budget", } }, Deletes: &[]ClientTupleKeyWithoutCondition{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "writer", Object: "document:roadmap", } } } options := ClientWriteOptions{ // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), Transaction: &TransactionOptions{ Disable: true, MaxParallelRequests: 5, // Maximum number of requests to issue in parallel MaxPerChunk: 1, // Maximum number of requests to be sent in a transaction in a particular chunk }, } data, err := fgaClient.Write(context.Background()).Body(requestBody).Options(options).Execute() // data.Writes = [{ // TupleKey: { User, Relation, Object }, // Status: "CLIENT_WRITE_STATUS_SUCCESS // HttpResponse: ... // http response" // }, { // TupleKey: { User, Relation, Object }, // Status: "CLIENT_WRITE_STATUS_FAILURE // HttpResponse: ... // http response" // Error: ... // }] // data.Deletes = [{ // TupleKey: { User, Relation, Object }, // Status: "CLIENT_WRITE_STATUS_SUCCESS // HttpResponse: ... // http response" // }] ``` #### Relationship Queries ##### Check Check if a user has a particular relation with an object. [API Documentation](https://openfga.dev/api/service#/Relationship%20Queries/Check) > Provide a tuple and ask the OpenFGA API to check for a relationship ```golang body := ClientCheckRequest{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", ContextualTuples: &[]ClientTupleKey{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", } }, } options := ClientCheckOptions{ AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } data, err := fgaClient.Check(context.Background()).Body(body).Options(options).Execute() // data = {"allowed":true,"resolution":""} // in JSON fmt.Printf("%t", data.GetAllowed()) // True ``` ##### Batch Check Run a set of [checks](#check). Batch Check will return `allowed: false` if it encounters an error, and will return the error in the body. If 429s or 5xxs are encountered, the underlying check will retry up to 15 times before giving up. ```golang options := ClientBatchCheckOptions{ // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), MaxParallelRequests: openfga.PtrInt32(5), // Max number of requests to issue in parallel, defaults to 10 } body := ClientBatchCheckBody{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", ContextualTuples: &[]ClientTupleKey{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", } }, }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "admin", Object: "document:roadmap", ContextualTuples: &[]ClientTupleKey{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", } }, }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "creator", Object: "document:roadmap", }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "deleter", Object: "document:roadmap", } } data, err := fgaClient.BatchCheck(context.Background()).Body(requestBody).Options(options).Execute() /* data = [{ Allowed: false, Request: { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", ContextualTuples: [{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap" }] }, HttpResponse: ... }, { Allowed: false, Request: { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "admin", Object: "document:roadmap", ContextualTuples: [{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap" }] }, HttpResponse: ... }, { Allowed: false, Request: { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "creator", Object: "document:roadmap", }, HttpResponse: ..., Error: }, { Allowed: true, Request: { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "deleter", Object: "document:roadmap", }}, HttpResponse: ..., ] */ ``` ##### Expand Expands the relationships in userset tree format. [API Documentation](https://openfga.dev/api/service#/Relationship%20Queries/Expand) ```golang options := ClientExpandOptions{ // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } body := ClientExpandRequest{ Relation: "viewer", Object: "document:roadmap", } data, err := fgaClient.Expand(context.Background()).Body(requestBody).Options(options).Execute() // data.Tree.Root = {"name":"document:roadmap#viewer","leaf":{"users":{"users":["user:81684243-9356-4421-8fbf-a4f8d36aa31b","user:f52a4f7a-054d-47ff-bb6e-3ac81269988f"]}}} ``` #### List Objects List the objects of a particular type a user has access to. [API Documentation](https://openfga.dev/api/service#/Relationship%20Queries/ListObjects) ```golang options := ClientListObjectsOptions{ // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } body := ClientListObjectsRequest{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "can_read", Type: "document", ContextualTuples: &[]ClientTupleKey{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "folder:product", }, { User: "folder:product", Relation: "parent", Object: "document:roadmap", } }, } data, err := fgaClient.ListObjects(context.Background()). Body(requestBody). Options(options). Execute() // data.Objects = ["document:roadmap"] ``` #### List Relations List the relations a user has on an object. ```golang options := ClientListRelationsOptions{ // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } body := ClientListRelationsRequest{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Object: "document:roadmap", Relations: []string{"can_view", "can_edit", "can_delete", "can_rename"}, ContextualTuples: &[]ClientTupleKey{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", } }, } data, err := fgaClient.ListRelations(context.Background()). Body(requestBody). Options(options). Execute() // data.Relations = ["can_view", "can_edit"] ``` ### Assertions #### Read Assertions Read assertions for a particular authorization model. [API Documentation](https://openfga.dev/api/service#/Assertions/Read%20Assertions) ```golang options := ClientReadAssertionsOptions{ // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } data, err := fgaClient.ReadAssertions(context.Background()). Options(options). Execute() ``` #### Write Assertions Update the assertions for a particular authorization model. [API Documentation](https://openfga.dev/api/service#/Assertions/Write%20Assertions) ```golang options := ClientWriteAssertionsOptions{ // You can rely on the model id set in the configuration or override it for this specific request AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } requestBody := ClientWriteAssertionsRequest{ ClientAssertion{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "can_view", Object: "document:roadmap", Expectation: true, }, } data, err := fgaClient.WriteAssertions(context.Background()). Body(requestBody). Options(options). Execute() ``` ### API Endpoints Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *OpenFgaApi* | [**Check**](docs/OpenFgaApi.md#check) | **Post** /stores/{store_id}/check | Check whether a user is authorized to access an object *OpenFgaApi* | [**CreateStore**](docs/OpenFgaApi.md#createstore) | **Post** /stores | Create a store *OpenFgaApi* | [**DeleteStore**](docs/OpenFgaApi.md#deletestore) | **Delete** /stores/{store_id} | Delete a store *OpenFgaApi* | [**Expand**](docs/OpenFgaApi.md#expand) | **Post** /stores/{store_id}/expand | Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship *OpenFgaApi* | [**GetStore**](docs/OpenFgaApi.md#getstore) | **Get** /stores/{store_id} | Get a store *OpenFgaApi* | [**ListObjects**](docs/OpenFgaApi.md#listobjects) | **Post** /stores/{store_id}/list-objects | List all objects of the given type that the user has a relation with *OpenFgaApi* | [**ListStores**](docs/OpenFgaApi.md#liststores) | **Get** /stores | List all stores *OpenFgaApi* | [**Read**](docs/OpenFgaApi.md#read) | **Post** /stores/{store_id}/read | Get tuples from the store that matches a query, without following userset rewrite rules *OpenFgaApi* | [**ReadAssertions**](docs/OpenFgaApi.md#readassertions) | **Get** /stores/{store_id}/assertions/{authorization_model_id} | Read assertions for an authorization model ID *OpenFgaApi* | [**ReadAuthorizationModel**](docs/OpenFgaApi.md#readauthorizationmodel) | **Get** /stores/{store_id}/authorization-models/{id} | Return a particular version of an authorization model *OpenFgaApi* | [**ReadAuthorizationModels**](docs/OpenFgaApi.md#readauthorizationmodels) | **Get** /stores/{store_id}/authorization-models | Return all the authorization models for a particular store *OpenFgaApi* | [**ReadChanges**](docs/OpenFgaApi.md#readchanges) | **Get** /stores/{store_id}/changes | Return a list of all the tuple changes *OpenFgaApi* | [**Write**](docs/OpenFgaApi.md#write) | **Post** /stores/{store_id}/write | Add or delete tuples from the store *OpenFgaApi* | [**WriteAssertions**](docs/OpenFgaApi.md#writeassertions) | **Put** /stores/{store_id}/assertions/{authorization_model_id} | Upsert assertions for an authorization model ID *OpenFgaApi* | [**WriteAuthorizationModel**](docs/OpenFgaApi.md#writeauthorizationmodel) | **Post** /stores/{store_id}/authorization-models | Create a new authorization model ### Models - [AbortedMessageResponse](docs/AbortedMessageResponse.md) - [Any](docs/Any.md) - [Assertion](docs/Assertion.md) - [AssertionTupleKey](docs/AssertionTupleKey.md) - [AuthorizationModel](docs/AuthorizationModel.md) - [CheckRequest](docs/CheckRequest.md) - [CheckRequestTupleKey](docs/CheckRequestTupleKey.md) - [CheckResponse](docs/CheckResponse.md) - [Computed](docs/Computed.md) - [Condition](docs/Condition.md) - [ConditionParamTypeRef](docs/ConditionParamTypeRef.md) - [ContextualTupleKeys](docs/ContextualTupleKeys.md) - [CreateStoreRequest](docs/CreateStoreRequest.md) - [CreateStoreResponse](docs/CreateStoreResponse.md) - [Difference](docs/Difference.md) - [ErrorCode](docs/ErrorCode.md) - [ExpandRequest](docs/ExpandRequest.md) - [ExpandRequestTupleKey](docs/ExpandRequestTupleKey.md) - [ExpandResponse](docs/ExpandResponse.md) - [GetStoreResponse](docs/GetStoreResponse.md) - [InternalErrorCode](docs/InternalErrorCode.md) - [InternalErrorMessageResponse](docs/InternalErrorMessageResponse.md) - [Leaf](docs/Leaf.md) - [ListObjectsRequest](docs/ListObjectsRequest.md) - [ListObjectsResponse](docs/ListObjectsResponse.md) - [ListStoresResponse](docs/ListStoresResponse.md) - [Metadata](docs/Metadata.md) - [Node](docs/Node.md) - [Nodes](docs/Nodes.md) - [NotFoundErrorCode](docs/NotFoundErrorCode.md) - [NullValue](docs/NullValue.md) - [ObjectRelation](docs/ObjectRelation.md) - [PathUnknownErrorMessageResponse](docs/PathUnknownErrorMessageResponse.md) - [ReadAssertionsResponse](docs/ReadAssertionsResponse.md) - [ReadAuthorizationModelResponse](docs/ReadAuthorizationModelResponse.md) - [ReadAuthorizationModelsResponse](docs/ReadAuthorizationModelsResponse.md) - [ReadChangesResponse](docs/ReadChangesResponse.md) - [ReadRequest](docs/ReadRequest.md) - [ReadRequestTupleKey](docs/ReadRequestTupleKey.md) - [ReadResponse](docs/ReadResponse.md) - [RelationMetadata](docs/RelationMetadata.md) - [RelationReference](docs/RelationReference.md) - [RelationshipCondition](docs/RelationshipCondition.md) - [Status](docs/Status.md) - [Store](docs/Store.md) - [Tuple](docs/Tuple.md) - [TupleChange](docs/TupleChange.md) - [TupleKey](docs/TupleKey.md) - [TupleKeyWithoutCondition](docs/TupleKeyWithoutCondition.md) - [TupleOperation](docs/TupleOperation.md) - [TupleToUserset](docs/TupleToUserset.md) - [TypeDefinition](docs/TypeDefinition.md) - [TypeName](docs/TypeName.md) - [Users](docs/Users.md) - [Userset](docs/Userset.md) - [UsersetTree](docs/UsersetTree.md) - [UsersetTreeDifference](docs/UsersetTreeDifference.md) - [UsersetTreeTupleToUserset](docs/UsersetTreeTupleToUserset.md) - [Usersets](docs/Usersets.md) - [ValidationErrorMessageResponse](docs/ValidationErrorMessageResponse.md) - [WriteAssertionsRequest](docs/WriteAssertionsRequest.md) - [WriteAuthorizationModelRequest](docs/WriteAuthorizationModelRequest.md) - [WriteAuthorizationModelResponse](docs/WriteAuthorizationModelResponse.md) - [WriteRequest](docs/WriteRequest.md) - [WriteRequestDeletes](docs/WriteRequestDeletes.md) - [WriteRequestWrites](docs/WriteRequestWrites.md) ## Contributing ### Issues If you have found a bug or if you have a feature request, please report them on the [sdk-generator repo](https://github.com/openfga/sdk-generator/issues) issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. ### Pull Requests All changes made to this repo will be overwritten on the next generation, so we kindly ask that you send all pull requests related to the SDKs to the [sdk-generator repo](https://github.com/openfga/sdk-generator) instead. ## Author [OpenFGA](https://github.com/openfga) ## License This project is licensed under the Apache-2.0 license. See the [LICENSE](https://github.com/openfga/go-sdk/blob/main/LICENSE) file for more info. The code in this repo was auto generated by [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator) from a template based on the [go template](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator/src/main/resources/go), licensed under the [Apache License 2.0](https://github.com/OpenAPITools/openapi-generator/blob/master/LICENSE). This repo bundles some code from the [golang.org/x/oauth2](https://pkg.go.dev/golang.org/x/oauth2) package. You can find the code [here](./oauth2) and corresponding [BSD-3 License](./oauth2/LICENSE). golang-github-openfga-go-sdk-0.3.5/api_client.go000066400000000000000000000565271456721040100215220ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "context" "encoding/json" "encoding/xml" "errors" "fmt" "io" "log" "net/http" "net/http/httputil" "net/url" "os" "reflect" "regexp" "strings" "time" "unicode/utf8" ) var ( jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) ) // ErrorResponse defines the error that will be asserted by FGA API. // This will only be used for error that is not defined type ErrorResponse struct { Code string `json:"code"` Message string `json:"message"` } // APIClient manages communication with the OpenFGA API v0.1 // In most cases there should be only one, shared, APIClient. type APIClient struct { cfg *Configuration common service // Reuse a single struct instead of allocating one for each service on the heap. // API Services OpenFgaApi OpenFgaApi } type service struct { client *APIClient RetryParams *RetryParams } // NewAPIClient creates a new API client. Requires a userAgent string describing your application. // optionally a custom http.Client to allow for advanced features such as caching. func NewAPIClient(cfg *Configuration) *APIClient { if cfg.HTTPClient == nil { if cfg.Credentials == nil { cfg.HTTPClient = http.DefaultClient } else { var httpClient, headers = cfg.Credentials.GetHttpClientAndHeaderOverrides() if len(headers) > 0 { for idx := range headers { cfg.AddDefaultHeader(headers[idx].Key, headers[idx].Value) } } if httpClient != nil { cfg.HTTPClient = httpClient } } } c := &APIClient{} c.cfg = cfg c.common.client = c c.common.RetryParams = cfg.RetryParams // API Services c.OpenFgaApi = (*OpenFgaApiService)(&c.common) return c } func (a APIClient) GetStoreId() string { return a.cfg.StoreId } func (a APIClient) SetStoreId(storeId string) { a.cfg.StoreId = storeId } // selectHeaderContentType select a content type from the available list. func selectHeaderContentType(contentTypes []string) string { if len(contentTypes) == 0 { return "" } if contains(contentTypes, "application/json") { return "application/json" } return contentTypes[0] // use the first content type specified in 'consumes' } // selectHeaderAccept join all accept types and return func selectHeaderAccept(accepts []string) string { if len(accepts) == 0 { return "" } if contains(accepts, "application/json") { return "application/json" } return strings.Join(accepts, ",") } // contains is a case insensitive match, finding needle in a haystack func contains(haystack []string, needle string) bool { loweredNeedle := strings.ToLower(needle) for _, a := range haystack { if strings.ToLower(a) == loweredNeedle { return true } } return false } // Verify optional parameters are of the correct type. func typeCheckParameter(obj interface{}, expected string, name string) error { // Make sure there is an object. if obj == nil { return nil } // Check the type is as expected. if reflect.TypeOf(obj).String() != expected { return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) } return nil } // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. func parameterToString(obj interface{}, collectionFormat string) string { var delimiter string switch collectionFormat { case "pipes": delimiter = "|" case "ssv": delimiter = " " case "tsv": delimiter = "\t" case "csv": delimiter = "," } if reflect.TypeOf(obj).Kind() == reflect.Slice { return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") } else if t, ok := obj.(time.Time); ok { return t.Format(time.RFC3339) } return fmt.Sprintf("%v", obj) } // helper for converting interface{} parameters to json strings func parameterToJson(obj interface{}) (string, error) { jsonBuf, err := json.Marshal(obj) if err != nil { return "", err } return string(jsonBuf), err } // callAPI do the request. func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { if c.cfg.Debug { dump, err := httputil.DumpRequestOut(request, true) if err != nil { return nil, err } log.Printf("\n%s\n", string(dump)) } resp, err := c.cfg.HTTPClient.Do(request) if err != nil { return resp, err } if c.cfg.Debug { dump, err := httputil.DumpResponse(resp, true) if err != nil { return resp, err } log.Printf("\n%s\n", string(dump)) } return resp, err } // Allow modification of underlying config for alternate implementations and testing // Caution: modifying the configuration while live can cause data races and potentially unwanted behavior func (c *APIClient) GetConfig() *Configuration { return c.cfg } // prepareRequest build the request func (c *APIClient) prepareRequest( ctx context.Context, path string, method string, postBody interface{}, headerParams map[string]string, queryParams url.Values) (localVarRequest *http.Request, err error) { var body *bytes.Buffer // Detect postBody type and post. if postBody != nil { contentType := headerParams["Content-Type"] if contentType == "" { contentType = detectContentType(postBody) headerParams["Content-Type"] = contentType } body, err = setBody(postBody, contentType) if err != nil { return nil, err } } // Setup path and query parameters uri, err := url.Parse(c.cfg.ApiUrl + path) if err != nil { return nil, err } // Adding Query Param query := uri.Query() for k, v := range queryParams { for _, iv := range v { query.Add(k, iv) } } // Encode the parameters. uri.RawQuery = query.Encode() // Generate a new request if body != nil { localVarRequest, err = http.NewRequest(method, uri.String(), body) } else { localVarRequest, err = http.NewRequest(method, uri.String(), nil) } if err != nil { return nil, err } // add header parameters, if any if len(headerParams) > 0 { headers := http.Header{} for h, v := range headerParams { headers.Set(h, v) } localVarRequest.Header = headers } // Add the user agent to the request. localVarRequest.Header.Set("User-Agent", c.cfg.UserAgent) for header, value := range c.cfg.DefaultHeaders { localVarRequest.Header.Set(header, value) } if ctx != nil { // add context to the request localVarRequest = localVarRequest.WithContext(ctx) } return localVarRequest, nil } func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { if len(b) == 0 { return nil } if s, ok := v.(*string); ok { *s = string(b) return nil } if xmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } if jsonCheck.MatchString(contentType) { if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined if err = unmarshalObj.UnmarshalJSON(b); err != nil { return err } } else { return errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined") } } else if err = json.Unmarshal(b, v); err != nil { // simple model return err } return nil } return errors.New("undefined response type") } // Prevent trying to import "fmt" func reportError(format string, a ...interface{}) error { return fmt.Errorf(format, a...) } // Set request body from an interface{} func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { if bodyBuf == nil { bodyBuf = &bytes.Buffer{} } if reader, ok := body.(io.Reader); ok { _, err = bodyBuf.ReadFrom(reader) } else if fp, ok := body.(**os.File); ok { _, err = bodyBuf.ReadFrom(*fp) } else if b, ok := body.([]byte); ok { _, err = bodyBuf.Write(b) } else if s, ok := body.(string); ok { _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) } else if jsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) } else if xmlCheck.MatchString(contentType) { err = xml.NewEncoder(bodyBuf).Encode(body) } if err != nil { return nil, err } if bodyBuf.Len() == 0 { err = fmt.Errorf("Invalid body type %s\n", contentType) return nil, err } return bodyBuf, nil } // detectContentType method is used to figure out `Request.Body` content type for request header func detectContentType(body interface{}) string { contentType := "text/plain; charset=utf-8" kind := reflect.TypeOf(body).Kind() switch kind { case reflect.Struct, reflect.Map, reflect.Ptr: contentType = "application/json; charset=utf-8" case reflect.String: contentType = "text/plain; charset=utf-8" default: if b, ok := body.([]byte); ok { contentType = http.DetectContentType(b) } else if kind == reflect.Slice { contentType = "application/json; charset=utf-8" } } return contentType } // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go type cacheControl map[string]string func parseCacheControl(headers http.Header) cacheControl { cc := cacheControl{} ccHeader := headers.Get("Cache-Control") for _, part := range strings.Split(ccHeader, ",") { part = strings.Trim(part, " ") if part == "" { continue } if strings.ContainsRune(part, '=') { keyval := strings.Split(part, "=") cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") } else { cc[part] = "" } } return cc } // CacheExpires helper function to determine remaining time before repeating a request. func CacheExpires(r *http.Response) time.Time { // Figure out when the cache expires. var expires time.Time now, err := time.Parse(time.RFC1123, r.Header.Get("date")) if err != nil { return time.Now() } respCacheControl := parseCacheControl(r.Header) if maxAge, ok := respCacheControl["max-age"]; ok { lifetime, err := time.ParseDuration(maxAge + "s") if err != nil { expires = now } else { expires = now.Add(lifetime) } } else { expiresHeader := r.Header.Get("Expires") if expiresHeader != "" { expires, err = time.Parse(time.RFC1123, expiresHeader) if err != nil { expires = now } } } return expires } func strlen(s string) int { return utf8.RuneCountInString(s) } // GenericOpenAPIError Provides access to the body, error and model on returned errors. type GenericOpenAPIError struct { body []byte error string model interface{} } // Error returns non-empty string if there was an error. func (e GenericOpenAPIError) Error() string { return e.error } // Body returns the raw bytes of the response func (e GenericOpenAPIError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e GenericOpenAPIError) Model() interface{} { return e.model } // FgaApiAuthenticationError is raised when API has errors due to invalid authentication type FgaApiAuthenticationError struct { body []byte error string model interface{} storeId string endpointCategory string modelDecodeError error responseStatusCode int responseHeader http.Header requestId string responseCode string } // Error returns non-empty string if there was an error. func (e FgaApiAuthenticationError) Error() string { return e.error } // Body returns the raw bytes of the response func (e FgaApiAuthenticationError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e FgaApiAuthenticationError) Model() interface{} { return e.model } // StoreId returns the store ID for the API that causes the error func (e FgaApiAuthenticationError) StoreId() string { return e.storeId } // EndpointCategory returns the original API category func (e FgaApiAuthenticationError) EndpointCategory() string { return e.endpointCategory } // ModelDecodeError returns any error when decoding the unpacked model of the error func (e FgaApiAuthenticationError) ModelDecodeError() error { return e.modelDecodeError } // ResponseStatusCode returns the original API response status HTTP code func (e FgaApiAuthenticationError) ResponseStatusCode() int { return e.responseStatusCode } // ResponseHeader returns the original API response header func (e FgaApiAuthenticationError) ResponseHeader() http.Header { return e.responseHeader } // RequestId returns the FGA request ID associated with the response func (e FgaApiAuthenticationError) RequestId() string { return e.requestId } // ResponseCode returns response code func (e FgaApiAuthenticationError) ResponseCode() string { return e.responseCode } // FgaApiError will be returned if there are errors in the API type FgaApiError struct { body []byte error string model interface{} storeId string endpointCategory string requestBody interface{} requestMethod string modelDecodeError error responseStatusCode int responseHeader http.Header requestId string responseCode string } // Error returns non-empty string if there was an error. func (e FgaApiError) Error() string { return e.error } // Body returns the raw bytes of the response func (e FgaApiError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e FgaApiError) Model() interface{} { return e.model } // StoreId returns the store ID for the API that causes the error func (e FgaApiError) StoreId() string { return e.storeId } // RequestBody returns the original request body func (e FgaApiError) RequestBody() interface{} { return e.requestBody } // RequestMethod returns the method calling the API func (e FgaApiError) RequestMethod() string { return e.requestMethod } // EndpointCategory returns the original API category func (e FgaApiError) EndpointCategory() string { return e.endpointCategory } // ModelDecodeError returns any error when decoding the unpacked model of the error func (e FgaApiError) ModelDecodeError() error { return e.modelDecodeError } // ResponseStatusCode returns the original API response HTTP status code func (e FgaApiError) ResponseStatusCode() int { return e.responseStatusCode } // ResponseHeader returns the original API response header func (e FgaApiError) ResponseHeader() http.Header { return e.responseHeader } // RequestId returns the FGA request ID associated with the response func (e FgaApiError) RequestId() string { return e.requestId } // ResponseCode returns response code func (e FgaApiError) ResponseCode() string { return e.responseCode } // FgaApiValidationError will be returned if there are errors in the API's parameters type FgaApiValidationError struct { body []byte error string model interface{} storeId string endpointCategory string requestBody interface{} requestMethod string modelDecodeError error responseStatusCode int responseHeader http.Header requestId string responseCode ErrorCode } // Error returns non-empty string if there was an error. func (e FgaApiValidationError) Error() string { return e.error } // Body returns the raw bytes of the response func (e FgaApiValidationError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e FgaApiValidationError) Model() interface{} { return e.model } // StoreId returns the store ID for the API that causes the error func (e FgaApiValidationError) StoreId() string { return e.storeId } // RequestBody returns the original request body func (e FgaApiValidationError) RequestBody() interface{} { return e.requestBody } // RequestMethod returns the method calling the API func (e FgaApiValidationError) RequestMethod() string { return e.requestMethod } // EndpointCategory returns the original API category func (e FgaApiValidationError) EndpointCategory() string { return e.endpointCategory } // ModelDecodeError returns any error when decoding the unpacked model of the error func (e FgaApiValidationError) ModelDecodeError() error { return e.modelDecodeError } // ResponseStatusCode returns the original API response HTTP status code func (e FgaApiValidationError) ResponseStatusCode() int { return e.responseStatusCode } // ResponseHeader returns the original API response header func (e FgaApiValidationError) ResponseHeader() http.Header { return e.responseHeader } // RequestId returns the FGA request ID associated with the response func (e FgaApiValidationError) RequestId() string { return e.requestId } // ResponseCode returns response code func (e FgaApiValidationError) ResponseCode() ErrorCode { return e.responseCode } // FgaApiNotFoundError will be returned if the endpoint cannot be found type FgaApiNotFoundError struct { body []byte error string model interface{} storeId string endpointCategory string requestBody interface{} requestMethod string modelDecodeError error responseStatusCode int responseHeader http.Header requestId string responseCode NotFoundErrorCode } // Error returns non-empty string if there was an error. func (e FgaApiNotFoundError) Error() string { return e.error } // Body returns the raw bytes of the response func (e FgaApiNotFoundError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e FgaApiNotFoundError) Model() interface{} { return e.model } // StoreId returns the store ID for the API that causes the error func (e FgaApiNotFoundError) StoreId() string { return e.storeId } // RequestBody returns the original request body func (e FgaApiNotFoundError) RequestBody() interface{} { return e.requestBody } // RequestMethod returns the method calling the API func (e FgaApiNotFoundError) RequestMethod() string { return e.requestMethod } // EndpointCategory returns the original API category func (e FgaApiNotFoundError) EndpointCategory() string { return e.endpointCategory } // ModelDecodeError returns any error when decoding the unpacked model of the error func (e FgaApiNotFoundError) ModelDecodeError() error { return e.modelDecodeError } // ResponseStatusCode returns the original API response HTTP status code func (e FgaApiNotFoundError) ResponseStatusCode() int { return e.responseStatusCode } // ResponseHeader returns the original API response header func (e FgaApiNotFoundError) ResponseHeader() http.Header { return e.responseHeader } // RequestId returns the FGA request ID associated with the response func (e FgaApiNotFoundError) RequestId() string { return e.requestId } // ResponseCode returns response code func (e FgaApiNotFoundError) ResponseCode() NotFoundErrorCode { return e.responseCode } // FgaApiInternalError will be returned if there are internal errors in OpenFGA type FgaApiInternalError struct { body []byte error string model interface{} storeId string endpointCategory string requestBody interface{} requestMethod string modelDecodeError error responseStatusCode int responseHeader http.Header requestId string responseCode InternalErrorCode } // Error returns non-empty string if there was an error. func (e FgaApiInternalError) Error() string { return e.error } // Body returns the raw bytes of the response func (e FgaApiInternalError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e FgaApiInternalError) Model() interface{} { return e.model } // StoreId returns the store ID for the API that causes the error func (e FgaApiInternalError) StoreId() string { return e.storeId } // RequestBody returns the original request body func (e FgaApiInternalError) RequestBody() interface{} { return e.requestBody } // RequestMethod returns the method calling the API func (e FgaApiInternalError) RequestMethod() string { return e.requestMethod } // EndpointCategory returns the original API category func (e FgaApiInternalError) EndpointCategory() string { return e.endpointCategory } // ModelDecodeError returns any error when decoding the unpacked model of the error func (e FgaApiInternalError) ModelDecodeError() error { return e.modelDecodeError } // ResponseStatusCode returns the original API response HTTP status code func (e FgaApiInternalError) ResponseStatusCode() int { return e.responseStatusCode } // ResponseHeader returns the original API response header func (e FgaApiInternalError) ResponseHeader() http.Header { return e.responseHeader } // RequestId returns the FGA request ID associated with the response func (e FgaApiInternalError) RequestId() string { return e.requestId } // ResponseCode returns response code func (e FgaApiInternalError) ResponseCode() InternalErrorCode { return e.responseCode } // FgaApiRateLimitExceededError will be returned if error happens because the API's rate limit has been exceeded (429 HTTP response) type FgaApiRateLimitExceededError struct { body []byte error string model interface{} storeId string endpointCategory string requestBody interface{} requestMethod string modelDecodeError error responseStatusCode int responseHeader http.Header requestId string responseCode string rateLimit int rateUnit string rateLimitResetEpoch string } // Error returns non-empty string if there was an error. func (e FgaApiRateLimitExceededError) Error() string { return e.error } // Body returns the raw bytes of the response func (e FgaApiRateLimitExceededError) Body() []byte { return e.body } // Model returns the unpacked model of the error func (e FgaApiRateLimitExceededError) Model() interface{} { return e.model } // StoreId returns the store ID for the API that causes the error func (e FgaApiRateLimitExceededError) StoreId() string { return e.storeId } // RequestBody returns the original request body func (e FgaApiRateLimitExceededError) RequestBody() interface{} { return e.requestBody } // RequestMethod returns the method calling the API func (e FgaApiRateLimitExceededError) RequestMethod() string { return e.requestMethod } // RateLimit returns the limit for the API func (e FgaApiRateLimitExceededError) RateLimit() int { return e.rateLimit } // RateUnit returns the unit used for rate limit func (e FgaApiRateLimitExceededError) RateUnit() string { return e.rateUnit } // RateLimitResetEpoch returns the unit used for rate limit func (e FgaApiRateLimitExceededError) RateLimitResetEpoch() string { return e.rateLimitResetEpoch } // EndpointCategory returns the original API category func (e FgaApiRateLimitExceededError) EndpointCategory() string { return e.endpointCategory } // ModelDecodeError returns any error when decoding the unpacked model of the error func (e FgaApiRateLimitExceededError) ModelDecodeError() error { return e.modelDecodeError } // ResponseStatusCode returns the original API response HTTP status code func (e FgaApiRateLimitExceededError) ResponseStatusCode() int { return e.responseStatusCode } // ResponseHeader returns the original API response header func (e FgaApiRateLimitExceededError) ResponseHeader() http.Header { return e.responseHeader } // RequestId returns the FGA request ID associated with the response func (e FgaApiRateLimitExceededError) RequestId() string { return e.requestId } // ResponseCode returns response code func (e FgaApiRateLimitExceededError) ResponseCode() string { return e.responseCode } golang-github-openfga-go-sdk-0.3.5/api_open_fga.go000066400000000000000000005664111456721040100220200ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" _context "context" _ioutil "io/ioutil" _nethttp "net/http" _neturl "net/url" "strings" "time" "github.com/openfga/go-sdk/internal/utils" ) // Linger please var ( _ _context.Context ) type OpenFgaApi interface { /* * Check Check whether a user is authorized to access an object * The Check API queries to check if the user has a certain relationship with an object in a certain store. A `contextual_tuples` object may also be included in the body of the request. This object contains one field `tuple_keys`, which is an array of tuple keys. Each of these tuples may have an associated `condition`. You may also provide an `authorization_model_id` in the body. This will be used to assert that the input `tuple_key` is valid for the model specified. If not specified, the assertion will be made against the latest authorization model ID. It is strongly recommended to specify authorization model id for better performance. You may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly. The response will return whether the relationship exists in the field `allowed`. ## Example In order to check if user `user:anne` of type `user` has a `reader` relationship with object `document:2021-budget` given the following contextual tuple ```json { "user": "user:anne", "relation": "member", "object": "time_slot:office_hours" } ``` the Check API can be used with the following request body: ```json { "tuple_key": { "user": "user:anne", "relation": "reader", "object": "document:2021-budget" }, "contextual_tuples": { "tuple_keys": [ { "user": "user:anne", "relation": "member", "object": "time_slot:office_hours" } ] }, "authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC" } ``` OpenFGA's response will include `{ "allowed": true }` if there is a relationship and `{ "allowed": false }` if there isn't. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiCheckRequest */ Check(ctx _context.Context) ApiCheckRequest /* * CheckExecute executes the request * @return CheckResponse */ CheckExecute(r ApiCheckRequest) (CheckResponse, *_nethttp.Response, error) /* * CreateStore Create a store * Create a unique OpenFGA store which will be used to store authorization models and relationship tuples. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiCreateStoreRequest */ CreateStore(ctx _context.Context) ApiCreateStoreRequest /* * CreateStoreExecute executes the request * @return CreateStoreResponse */ CreateStoreExecute(r ApiCreateStoreRequest) (CreateStoreResponse, *_nethttp.Response, error) /* * DeleteStore Delete a store * Delete an OpenFGA store. This does not delete the data associated with the store, like tuples or authorization models. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiDeleteStoreRequest */ DeleteStore(ctx _context.Context) ApiDeleteStoreRequest /* * DeleteStoreExecute executes the request */ DeleteStoreExecute(r ApiDeleteStoreRequest) (*_nethttp.Response, error) /* * Expand Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship * The Expand API will return all users and usersets that have certain relationship with an object in a certain store. This is different from the `/stores/{store_id}/read` API in that both users and computed usersets are returned. Body parameters `tuple_key.object` and `tuple_key.relation` are all required. The response will return a tree whose leaves are the specific users and usersets. Union, intersection and difference operator are located in the intermediate nodes. ## Example To expand all users that have the `reader` relationship with object `document:2021-budget`, use the Expand API with the following request body ```json { "tuple_key": { "object": "document:2021-budget", "relation": "reader" }, "authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC" } ``` OpenFGA's response will be a userset tree of the users and usersets that have read access to the document. ```json { "tree":{ "root":{ "type":"document:2021-budget#reader", "union":{ "nodes":[ { "type":"document:2021-budget#reader", "leaf":{ "users":{ "users":[ "user:bob" ] } } }, { "type":"document:2021-budget#reader", "leaf":{ "computed":{ "userset":"document:2021-budget#writer" } } } ] } } } } ``` The caller can then call expand API for the `writer` relationship for the `document:2021-budget`. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiExpandRequest */ Expand(ctx _context.Context) ApiExpandRequest /* * ExpandExecute executes the request * @return ExpandResponse */ ExpandExecute(r ApiExpandRequest) (ExpandResponse, *_nethttp.Response, error) /* * GetStore Get a store * Returns an OpenFGA store by its identifier * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiGetStoreRequest */ GetStore(ctx _context.Context) ApiGetStoreRequest /* * GetStoreExecute executes the request * @return GetStoreResponse */ GetStoreExecute(r ApiGetStoreRequest) (GetStoreResponse, *_nethttp.Response, error) /* * ListObjects List all objects of the given type that the user has a relation with * The ListObjects API returns a list of all the objects of the given type that the user has a relation with. To achieve this, both the store tuples and the authorization model are used. An `authorization_model_id` may be specified in the body. If it is not specified, the latest authorization model ID will be used. It is strongly recommended to specify authorization model id for better performance. You may also specify `contextual_tuples` that will be treated as regular tuples. Each of these tuples may have an associated `condition`. You may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly. The response will contain the related objects in an array in the "objects" field of the response and they will be strings in the object format `:` (e.g. "document:roadmap"). The number of objects in the response array will be limited by the execution timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE and by the upper bound specified in the flag OPENFGA_LIST_OBJECTS_MAX_RESULTS, whichever is hit first. The objects given will not be sorted, and therefore two identical calls can give a given different set of objects. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiListObjectsRequest */ ListObjects(ctx _context.Context) ApiListObjectsRequest /* * ListObjectsExecute executes the request * @return ListObjectsResponse */ ListObjectsExecute(r ApiListObjectsRequest) (ListObjectsResponse, *_nethttp.Response, error) /* * ListStores List all stores * Returns a paginated list of OpenFGA stores and a continuation token to get additional stores. The continuation token will be empty if there are no more stores. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiListStoresRequest */ ListStores(ctx _context.Context) ApiListStoresRequest /* * ListStoresExecute executes the request * @return ListStoresResponse */ ListStoresExecute(r ApiListStoresRequest) (ListStoresResponse, *_nethttp.Response, error) /* * Read Get tuples from the store that matches a query, without following userset rewrite rules * The Read API will return the tuples for a certain store that match a query filter specified in the body of the request. The API doesn't guarantee order by any field. It is different from the `/stores/{store_id}/expand` API in that it only returns relationship tuples that are stored in the system and satisfy the query. In the body: 1. `tuple_key` is optional. If not specified, it will return all tuples in the store. 2. `tuple_key.object` is mandatory if `tuple_key` is specified. It can be a full object (e.g., `type:object_id`) or type only (e.g., `type:`). 3. `tuple_key.user` is mandatory if tuple_key is specified in the case the `tuple_key.object` is a type only. ## Examples ### Query for all objects in a type definition To query for all objects that `user:bob` has `reader` relationship in the `document` type definition, call read API with body of ```json { "tuple_key": { "user": "user:bob", "relation": "reader", "object": "document:" } } ``` The API will return tuples and a continuation token, something like ```json { "tuples": [ { "key": { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" }, "timestamp": "2021-10-06T15:32:11.128Z" } ], "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } ``` This means that `user:bob` has a `reader` relationship with 1 document `document:2021-budget`. Note that this API, unlike the List Objects API, does not evaluate the tuples in the store. The continuation token will be empty if there are no more tuples to query. ### Query for all stored relationship tuples that have a particular relation and object To query for all users that have `reader` relationship with `document:2021-budget`, call read API with body of ```json { "tuple_key": { "object": "document:2021-budget", "relation": "reader" } } ``` The API will return something like ```json { "tuples": [ { "key": { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" }, "timestamp": "2021-10-06T15:32:11.128Z" } ], "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } ``` This means that `document:2021-budget` has 1 `reader` (`user:bob`). Note that, even if the model said that all `writers` are also `readers`, the API will not return writers such as `user:anne` because it only returns tuples and does not evaluate them. ### Query for all users with all relationships for a particular document To query for all users that have any relationship with `document:2021-budget`, call read API with body of ```json { "tuple_key": { "object": "document:2021-budget" } } ``` The API will return something like ```json { "tuples": [ { "key": { "user": "user:anne", "relation": "writer", "object": "document:2021-budget" }, "timestamp": "2021-10-05T13:42:12.356Z" }, { "key": { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" }, "timestamp": "2021-10-06T15:32:11.128Z" } ], "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } ``` This means that `document:2021-budget` has 1 `reader` (`user:bob`) and 1 `writer` (`user:anne`). * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiReadRequest */ Read(ctx _context.Context) ApiReadRequest /* * ReadExecute executes the request * @return ReadResponse */ ReadExecute(r ApiReadRequest) (ReadResponse, *_nethttp.Response, error) /* * ReadAssertions Read assertions for an authorization model ID * The ReadAssertions API will return, for a given authorization model id, all the assertions stored for it. An assertion is an object that contains a tuple key, and the expectation of whether a call to the Check API of that tuple key will return true or false. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param authorizationModelId * @return ApiReadAssertionsRequest */ ReadAssertions(ctx _context.Context, authorizationModelId string) ApiReadAssertionsRequest /* * ReadAssertionsExecute executes the request * @return ReadAssertionsResponse */ ReadAssertionsExecute(r ApiReadAssertionsRequest) (ReadAssertionsResponse, *_nethttp.Response, error) /* * ReadAuthorizationModel Return a particular version of an authorization model * The ReadAuthorizationModel API returns an authorization model by its identifier. The response will return the authorization model for the particular version. ## Example To retrieve the authorization model with ID `01G5JAVJ41T49E9TT3SKVS7X1J` for the store, call the GET authorization-models by ID API with `01G5JAVJ41T49E9TT3SKVS7X1J` as the `id` path parameter. The API will return: ```json { "authorization_model":{ "id":"01G5JAVJ41T49E9TT3SKVS7X1J", "type_definitions":[ { "type":"user" }, { "type":"document", "relations":{ "reader":{ "union":{ "child":[ { "this":{} }, { "computedUserset":{ "object":"", "relation":"writer" } } ] } }, "writer":{ "this":{} } } } ] } } ``` In the above example, there are 2 types (`user` and `document`). The `document` type has 2 relations (`writer` and `reader`). * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param id * @return ApiReadAuthorizationModelRequest */ ReadAuthorizationModel(ctx _context.Context, id string) ApiReadAuthorizationModelRequest /* * ReadAuthorizationModelExecute executes the request * @return ReadAuthorizationModelResponse */ ReadAuthorizationModelExecute(r ApiReadAuthorizationModelRequest) (ReadAuthorizationModelResponse, *_nethttp.Response, error) /* * ReadAuthorizationModels Return all the authorization models for a particular store * The ReadAuthorizationModels API will return all the authorization models for a certain store. OpenFGA's response will contain an array of all authorization models, sorted in descending order of creation. ## Example Assume that a store's authorization model has been configured twice. To get all the authorization models that have been created in this store, call GET authorization-models. The API will return a response that looks like: ```json { "authorization_models": [ { "id": "01G50QVV17PECNVAHX1GG4Y5NC", "type_definitions": [...] }, { "id": "01G4ZW8F4A07AKQ8RHSVG9RW04", "type_definitions": [...] }, ], "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } ``` If there are no more authorization models available, the `continuation_token` field will be empty ```json { "authorization_models": [ { "id": "01G50QVV17PECNVAHX1GG4Y5NC", "type_definitions": [...] }, { "id": "01G4ZW8F4A07AKQ8RHSVG9RW04", "type_definitions": [...] }, ], "continuation_token": "" } ``` * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiReadAuthorizationModelsRequest */ ReadAuthorizationModels(ctx _context.Context) ApiReadAuthorizationModelsRequest /* * ReadAuthorizationModelsExecute executes the request * @return ReadAuthorizationModelsResponse */ ReadAuthorizationModelsExecute(r ApiReadAuthorizationModelsRequest) (ReadAuthorizationModelsResponse, *_nethttp.Response, error) /* * ReadChanges Return a list of all the tuple changes * The ReadChanges API will return a paginated list of tuple changes (additions and deletions) that occurred in a given store, sorted by ascending time. The response will include a continuation token that is used to get the next set of changes. If there are no changes after the provided continuation token, the same token will be returned in order for it to be used when new changes are recorded. If the store never had any tuples added or removed, this token will be empty. You can use the `type` parameter to only get the list of tuple changes that affect objects of that type. When reading a write tuple change, if it was conditioned, the condition will be returned. When reading a delete tuple change, the condition will NOT be returned regardless of whether it was originally conditioned or not. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiReadChangesRequest */ ReadChanges(ctx _context.Context) ApiReadChangesRequest /* * ReadChangesExecute executes the request * @return ReadChangesResponse */ ReadChangesExecute(r ApiReadChangesRequest) (ReadChangesResponse, *_nethttp.Response, error) /* * Write Add or delete tuples from the store * The Write API will update the tuples for a certain store. Tuples and type definitions allow OpenFGA to determine whether a relationship exists between an object and an user. In the body, `writes` adds new tuples and `deletes` removes existing tuples. When deleting a tuple, any `condition` specified with it is ignored. The API is not idempotent: if, later on, you try to add the same tuple key (even if the `condition` is different), or if you try to delete a non-existing tuple, it will throw an error. An `authorization_model_id` may be specified in the body. If it is, it will be used to assert that each written tuple (not deleted) is valid for the model specified. If it is not specified, the latest authorization model ID will be used. ## Example ### Adding relationships To add `user:anne` as a `writer` for `document:2021-budget`, call write API with the following ```json { "writes": { "tuple_keys": [ { "user": "user:anne", "relation": "writer", "object": "document:2021-budget" } ] }, "authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC" } ``` ### Removing relationships To remove `user:bob` as a `reader` for `document:2021-budget`, call write API with the following ```json { "deletes": { "tuple_keys": [ { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" } ] } } ``` * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiWriteRequest */ Write(ctx _context.Context) ApiWriteRequest /* * WriteExecute executes the request * @return map[string]interface{} */ WriteExecute(r ApiWriteRequest) (map[string]interface{}, *_nethttp.Response, error) /* * WriteAssertions Upsert assertions for an authorization model ID * The WriteAssertions API will upsert new assertions for an authorization model id, or overwrite the existing ones. An assertion is an object that contains a tuple key, and the expectation of whether a call to the Check API of that tuple key will return true or false. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param authorizationModelId * @return ApiWriteAssertionsRequest */ WriteAssertions(ctx _context.Context, authorizationModelId string) ApiWriteAssertionsRequest /* * WriteAssertionsExecute executes the request */ WriteAssertionsExecute(r ApiWriteAssertionsRequest) (*_nethttp.Response, error) /* * WriteAuthorizationModel Create a new authorization model * The WriteAuthorizationModel API will add a new authorization model to a store. Each item in the `type_definitions` array is a type definition as specified in the field `type_definition`. The response will return the authorization model's ID in the `id` field. ## Example To add an authorization model with `user` and `document` type definitions, call POST authorization-models API with the body: ```json { "type_definitions":[ { "type":"user" }, { "type":"document", "relations":{ "reader":{ "union":{ "child":[ { "this":{} }, { "computedUserset":{ "object":"", "relation":"writer" } } ] } }, "writer":{ "this":{} } } } ] } ``` OpenFGA's response will include the version id for this authorization model, which will look like ``` {"authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC"} ``` * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiWriteAuthorizationModelRequest */ WriteAuthorizationModel(ctx _context.Context) ApiWriteAuthorizationModelRequest /* * WriteAuthorizationModelExecute executes the request * @return WriteAuthorizationModelResponse */ WriteAuthorizationModelExecute(r ApiWriteAuthorizationModelRequest) (WriteAuthorizationModelResponse, *_nethttp.Response, error) } // OpenFgaApiService OpenFgaApi service type OpenFgaApiService service type ApiCheckRequest struct { ctx _context.Context ApiService OpenFgaApi body *CheckRequest } func (r ApiCheckRequest) Body(body CheckRequest) ApiCheckRequest { r.body = &body return r } func (r ApiCheckRequest) Execute() (CheckResponse, *_nethttp.Response, error) { return r.ApiService.CheckExecute(r) } /* - Check Check whether a user is authorized to access an object - The Check API queries to check if the user has a certain relationship with an object in a certain store. A `contextual_tuples` object may also be included in the body of the request. This object contains one field `tuple_keys`, which is an array of tuple keys. Each of these tuples may have an associated `condition`. You may also provide an `authorization_model_id` in the body. This will be used to assert that the input `tuple_key` is valid for the model specified. If not specified, the assertion will be made against the latest authorization model ID. It is strongly recommended to specify authorization model id for better performance. You may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly. The response will return whether the relationship exists in the field `allowed`. ## Example In order to check if user `user:anne` of type `user` has a `reader` relationship with object `document:2021-budget` given the following contextual tuple ```json { "user": "user:anne", "relation": "member", "object": "time_slot:office_hours" } ``` the Check API can be used with the following request body: ```json { "tuple_key": { "user": "user:anne", "relation": "reader", "object": "document:2021-budget" }, "contextual_tuples": { "tuple_keys": [ { "user": "user:anne", "relation": "member", "object": "time_slot:office_hours" } ] }, "authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC" } ``` OpenFGA's response will include `{ "allowed": true }` if there is a relationship and `{ "allowed": false }` if there isn't. - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiCheckRequest */ func (a *OpenFgaApiService) Check(ctx _context.Context) ApiCheckRequest { return ApiCheckRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return CheckResponse */ func (a *OpenFgaApiService) CheckExecute(r ApiCheckRequest) (CheckResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} localVarReturnValue CheckResponse ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/check" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.body == nil { return localVarReturnValue, nil, reportError("body is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{"application/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params localVarPostBody = r.body req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Check", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Check validation error for " + localVarHTTPMethod + " Check with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Check", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Check auth error for " + localVarHTTPMethod + " Check with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Check", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Check validation error for " + localVarHTTPMethod + " Check with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Check", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Check rate limit error for " + localVarHTTPMethod + " Check with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Check", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Check internal error for " + localVarHTTPMethod + " Check with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Check", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Check error for " + localVarHTTPMethod + " Check with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue CheckResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiCreateStoreRequest struct { ctx _context.Context ApiService OpenFgaApi body *CreateStoreRequest } func (r ApiCreateStoreRequest) Body(body CreateStoreRequest) ApiCreateStoreRequest { r.body = &body return r } func (r ApiCreateStoreRequest) Execute() (CreateStoreResponse, *_nethttp.Response, error) { return r.ApiService.CreateStoreExecute(r) } /* * CreateStore Create a store * Create a unique OpenFGA store which will be used to store authorization models and relationship tuples. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiCreateStoreRequest */ func (a *OpenFgaApiService) CreateStore(ctx _context.Context) ApiCreateStoreRequest { return ApiCreateStoreRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return CreateStoreResponse */ func (a *OpenFgaApiService) CreateStoreExecute(r ApiCreateStoreRequest) (CreateStoreResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} localVarReturnValue CreateStoreResponse ) localVarPath := "/stores" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.body == nil { return localVarReturnValue, nil, reportError("body is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{"application/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params localVarPostBody = r.body req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "CreateStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "CreateStore validation error for " + localVarHTTPMethod + " CreateStore with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "CreateStore", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "CreateStore auth error for " + localVarHTTPMethod + " CreateStore with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "CreateStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "CreateStore validation error for " + localVarHTTPMethod + " CreateStore with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "CreateStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "CreateStore rate limit error for " + localVarHTTPMethod + " CreateStore with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "CreateStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "CreateStore internal error for " + localVarHTTPMethod + " CreateStore with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "CreateStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "CreateStore error for " + localVarHTTPMethod + " CreateStore with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue CreateStoreResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiDeleteStoreRequest struct { ctx _context.Context ApiService OpenFgaApi } func (r ApiDeleteStoreRequest) Execute() (*_nethttp.Response, error) { return r.ApiService.DeleteStoreExecute(r) } /* * DeleteStore Delete a store * Delete an OpenFGA store. This does not delete the data associated with the store, like tuples or authorization models. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiDeleteStoreRequest */ func (a *OpenFgaApiService) DeleteStore(ctx _context.Context) ApiDeleteStoreRequest { return ApiDeleteStoreRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request */ func (a *OpenFgaApiService) DeleteStoreExecute(r ApiDeleteStoreRequest) (*_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodDelete localVarPostBody interface{} ) if a.client.cfg.StoreId == "" { return nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "DeleteStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "DeleteStore validation error for " + localVarHTTPMethod + " DeleteStore with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "DeleteStore", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "DeleteStore auth error for " + localVarHTTPMethod + " DeleteStore with body " + string(localVarBody) return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "DeleteStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "DeleteStore validation error for " + localVarHTTPMethod + " DeleteStore with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "DeleteStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "DeleteStore rate limit error for " + localVarHTTPMethod + " DeleteStore with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "DeleteStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "DeleteStore internal error for " + localVarHTTPMethod + " DeleteStore with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "DeleteStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "DeleteStore error for " + localVarHTTPMethod + " DeleteStore with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarHTTPResponse, newErr } return localVarHTTPResponse, nil } // should never have reached this return nil, reportError("Error not handled properly") } type ApiExpandRequest struct { ctx _context.Context ApiService OpenFgaApi body *ExpandRequest } func (r ApiExpandRequest) Body(body ExpandRequest) ApiExpandRequest { r.body = &body return r } func (r ApiExpandRequest) Execute() (ExpandResponse, *_nethttp.Response, error) { return r.ApiService.ExpandExecute(r) } /* - Expand Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship - The Expand API will return all users and usersets that have certain relationship with an object in a certain store. This is different from the `/stores/{store_id}/read` API in that both users and computed usersets are returned. Body parameters `tuple_key.object` and `tuple_key.relation` are all required. The response will return a tree whose leaves are the specific users and usersets. Union, intersection and difference operator are located in the intermediate nodes. ## Example To expand all users that have the `reader` relationship with object `document:2021-budget`, use the Expand API with the following request body ```json { "tuple_key": { "object": "document:2021-budget", "relation": "reader" }, "authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC" } ``` OpenFGA's response will be a userset tree of the users and usersets that have read access to the document. ```json { "tree":{ "root":{ "type":"document:2021-budget#reader", "union":{ "nodes":[ { "type":"document:2021-budget#reader", "leaf":{ "users":{ "users":[ "user:bob" ] } } }, { "type":"document:2021-budget#reader", "leaf":{ "computed":{ "userset":"document:2021-budget#writer" } } } ] } } } } ``` The caller can then call expand API for the `writer` relationship for the `document:2021-budget`. - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiExpandRequest */ func (a *OpenFgaApiService) Expand(ctx _context.Context) ApiExpandRequest { return ApiExpandRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return ExpandResponse */ func (a *OpenFgaApiService) ExpandExecute(r ApiExpandRequest) (ExpandResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} localVarReturnValue ExpandResponse ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/expand" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.body == nil { return localVarReturnValue, nil, reportError("body is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{"application/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params localVarPostBody = r.body req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Expand", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Expand validation error for " + localVarHTTPMethod + " Expand with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Expand", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Expand auth error for " + localVarHTTPMethod + " Expand with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Expand", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Expand validation error for " + localVarHTTPMethod + " Expand with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Expand", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Expand rate limit error for " + localVarHTTPMethod + " Expand with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Expand", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Expand internal error for " + localVarHTTPMethod + " Expand with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Expand", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Expand error for " + localVarHTTPMethod + " Expand with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue ExpandResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiGetStoreRequest struct { ctx _context.Context ApiService OpenFgaApi } func (r ApiGetStoreRequest) Execute() (GetStoreResponse, *_nethttp.Response, error) { return r.ApiService.GetStoreExecute(r) } /* * GetStore Get a store * Returns an OpenFGA store by its identifier * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return ApiGetStoreRequest */ func (a *OpenFgaApiService) GetStore(ctx _context.Context) ApiGetStoreRequest { return ApiGetStoreRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return GetStoreResponse */ func (a *OpenFgaApiService) GetStoreExecute(r ApiGetStoreRequest) (GetStoreResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarReturnValue GetStoreResponse ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "GetStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "GetStore validation error for " + localVarHTTPMethod + " GetStore with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "GetStore", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "GetStore auth error for " + localVarHTTPMethod + " GetStore with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "GetStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "GetStore validation error for " + localVarHTTPMethod + " GetStore with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "GetStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "GetStore rate limit error for " + localVarHTTPMethod + " GetStore with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "GetStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "GetStore internal error for " + localVarHTTPMethod + " GetStore with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "GetStore", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "GetStore error for " + localVarHTTPMethod + " GetStore with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue GetStoreResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiListObjectsRequest struct { ctx _context.Context ApiService OpenFgaApi body *ListObjectsRequest } func (r ApiListObjectsRequest) Body(body ListObjectsRequest) ApiListObjectsRequest { r.body = &body return r } func (r ApiListObjectsRequest) Execute() (ListObjectsResponse, *_nethttp.Response, error) { return r.ApiService.ListObjectsExecute(r) } /* - ListObjects List all objects of the given type that the user has a relation with - The ListObjects API returns a list of all the objects of the given type that the user has a relation with. To achieve this, both the store tuples and the authorization model are used. An `authorization_model_id` may be specified in the body. If it is not specified, the latest authorization model ID will be used. It is strongly recommended to specify authorization model id for better performance. You may also specify `contextual_tuples` that will be treated as regular tuples. Each of these tuples may have an associated `condition`. You may also provide a `context` object that will be used to evaluate the conditioned tuples in the system. It is strongly recommended to provide a value for all the input parameters of all the conditions, to ensure that all tuples be evaluated correctly. The response will contain the related objects in an array in the "objects" field of the response and they will be strings in the object format `:` (e.g. "document:roadmap"). The number of objects in the response array will be limited by the execution timeout specified in the flag OPENFGA_LIST_OBJECTS_DEADLINE and by the upper bound specified in the flag OPENFGA_LIST_OBJECTS_MAX_RESULTS, whichever is hit first. The objects given will not be sorted, and therefore two identical calls can give a given different set of objects. - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiListObjectsRequest */ func (a *OpenFgaApiService) ListObjects(ctx _context.Context) ApiListObjectsRequest { return ApiListObjectsRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return ListObjectsResponse */ func (a *OpenFgaApiService) ListObjectsExecute(r ApiListObjectsRequest) (ListObjectsResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} localVarReturnValue ListObjectsResponse ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/list-objects" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.body == nil { return localVarReturnValue, nil, reportError("body is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{"application/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params localVarPostBody = r.body req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListObjects", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ListObjects validation error for " + localVarHTTPMethod + " ListObjects with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListObjects", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ListObjects auth error for " + localVarHTTPMethod + " ListObjects with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListObjects", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ListObjects validation error for " + localVarHTTPMethod + " ListObjects with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListObjects", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ListObjects rate limit error for " + localVarHTTPMethod + " ListObjects with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListObjects", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ListObjects internal error for " + localVarHTTPMethod + " ListObjects with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListObjects", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ListObjects error for " + localVarHTTPMethod + " ListObjects with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue ListObjectsResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiListStoresRequest struct { ctx _context.Context ApiService OpenFgaApi pageSize *int32 continuationToken *string } func (r ApiListStoresRequest) PageSize(pageSize int32) ApiListStoresRequest { r.pageSize = &pageSize return r } func (r ApiListStoresRequest) ContinuationToken(continuationToken string) ApiListStoresRequest { r.continuationToken = &continuationToken return r } func (r ApiListStoresRequest) Execute() (ListStoresResponse, *_nethttp.Response, error) { return r.ApiService.ListStoresExecute(r) } /* - ListStores List all stores - Returns a paginated list of OpenFGA stores and a continuation token to get additional stores. The continuation token will be empty if there are no more stores. - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiListStoresRequest */ func (a *OpenFgaApiService) ListStores(ctx _context.Context) ApiListStoresRequest { return ApiListStoresRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return ListStoresResponse */ func (a *OpenFgaApiService) ListStoresExecute(r ApiListStoresRequest) (ListStoresResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarReturnValue ListStoresResponse ) localVarPath := "/stores" localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.pageSize != nil { localVarQueryParams.Add("page_size", parameterToString(*r.pageSize, "")) } if r.continuationToken != nil { localVarQueryParams.Add("continuation_token", parameterToString(*r.continuationToken, "")) } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListStores", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ListStores validation error for " + localVarHTTPMethod + " ListStores with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListStores", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ListStores auth error for " + localVarHTTPMethod + " ListStores with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListStores", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ListStores validation error for " + localVarHTTPMethod + " ListStores with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListStores", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ListStores rate limit error for " + localVarHTTPMethod + " ListStores with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListStores", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ListStores internal error for " + localVarHTTPMethod + " ListStores with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ListStores", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ListStores error for " + localVarHTTPMethod + " ListStores with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue ListStoresResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiReadRequest struct { ctx _context.Context ApiService OpenFgaApi body *ReadRequest } func (r ApiReadRequest) Body(body ReadRequest) ApiReadRequest { r.body = &body return r } func (r ApiReadRequest) Execute() (ReadResponse, *_nethttp.Response, error) { return r.ApiService.ReadExecute(r) } /* - Read Get tuples from the store that matches a query, without following userset rewrite rules - The Read API will return the tuples for a certain store that match a query filter specified in the body of the request. The API doesn't guarantee order by any field. It is different from the `/stores/{store_id}/expand` API in that it only returns relationship tuples that are stored in the system and satisfy the query. In the body: 1. `tuple_key` is optional. If not specified, it will return all tuples in the store. 2. `tuple_key.object` is mandatory if `tuple_key` is specified. It can be a full object (e.g., `type:object_id`) or type only (e.g., `type:`). 3. `tuple_key.user` is mandatory if tuple_key is specified in the case the `tuple_key.object` is a type only. ## Examples ### Query for all objects in a type definition To query for all objects that `user:bob` has `reader` relationship in the `document` type definition, call read API with body of ```json { "tuple_key": { "user": "user:bob", "relation": "reader", "object": "document:" } } ``` The API will return tuples and a continuation token, something like ```json { "tuples": [ { "key": { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" }, "timestamp": "2021-10-06T15:32:11.128Z" } ], "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } ``` This means that `user:bob` has a `reader` relationship with 1 document `document:2021-budget`. Note that this API, unlike the List Objects API, does not evaluate the tuples in the store. The continuation token will be empty if there are no more tuples to query. ### Query for all stored relationship tuples that have a particular relation and object To query for all users that have `reader` relationship with `document:2021-budget`, call read API with body of ```json { "tuple_key": { "object": "document:2021-budget", "relation": "reader" } } ``` The API will return something like ```json { "tuples": [ { "key": { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" }, "timestamp": "2021-10-06T15:32:11.128Z" } ], "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } ``` This means that `document:2021-budget` has 1 `reader` (`user:bob`). Note that, even if the model said that all `writers` are also `readers`, the API will not return writers such as `user:anne` because it only returns tuples and does not evaluate them. ### Query for all users with all relationships for a particular document To query for all users that have any relationship with `document:2021-budget`, call read API with body of ```json { "tuple_key": { "object": "document:2021-budget" } } ``` The API will return something like ```json { "tuples": [ { "key": { "user": "user:anne", "relation": "writer", "object": "document:2021-budget" }, "timestamp": "2021-10-05T13:42:12.356Z" }, { "key": { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" }, "timestamp": "2021-10-06T15:32:11.128Z" } ], "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } ``` This means that `document:2021-budget` has 1 `reader` (`user:bob`) and 1 `writer` (`user:anne`). - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiReadRequest */ func (a *OpenFgaApiService) Read(ctx _context.Context) ApiReadRequest { return ApiReadRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return ReadResponse */ func (a *OpenFgaApiService) ReadExecute(r ApiReadRequest) (ReadResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} localVarReturnValue ReadResponse ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/read" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.body == nil { return localVarReturnValue, nil, reportError("body is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{"application/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params localVarPostBody = r.body req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Read", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Read validation error for " + localVarHTTPMethod + " Read with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Read", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Read auth error for " + localVarHTTPMethod + " Read with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Read", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Read validation error for " + localVarHTTPMethod + " Read with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Read", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Read rate limit error for " + localVarHTTPMethod + " Read with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Read", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Read internal error for " + localVarHTTPMethod + " Read with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Read", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Read error for " + localVarHTTPMethod + " Read with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue ReadResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiReadAssertionsRequest struct { ctx _context.Context ApiService OpenFgaApi authorizationModelId string } func (r ApiReadAssertionsRequest) Execute() (ReadAssertionsResponse, *_nethttp.Response, error) { return r.ApiService.ReadAssertionsExecute(r) } /* * ReadAssertions Read assertions for an authorization model ID * The ReadAssertions API will return, for a given authorization model id, all the assertions stored for it. An assertion is an object that contains a tuple key, and the expectation of whether a call to the Check API of that tuple key will return true or false. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param authorizationModelId * @return ApiReadAssertionsRequest */ func (a *OpenFgaApiService) ReadAssertions(ctx _context.Context, authorizationModelId string) ApiReadAssertionsRequest { return ApiReadAssertionsRequest{ ApiService: a, ctx: ctx, authorizationModelId: authorizationModelId, } } /* * Execute executes the request * @return ReadAssertionsResponse */ func (a *OpenFgaApiService) ReadAssertionsExecute(r ApiReadAssertionsRequest) (ReadAssertionsResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarReturnValue ReadAssertionsResponse ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/assertions/{authorization_model_id}" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarPath = strings.Replace(localVarPath, "{"+"authorization_model_id"+"}", _neturl.PathEscape(parameterToString(r.authorizationModelId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAssertions", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadAssertions validation error for " + localVarHTTPMethod + " ReadAssertions with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAssertions", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadAssertions auth error for " + localVarHTTPMethod + " ReadAssertions with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAssertions", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadAssertions validation error for " + localVarHTTPMethod + " ReadAssertions with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAssertions", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadAssertions rate limit error for " + localVarHTTPMethod + " ReadAssertions with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAssertions", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadAssertions internal error for " + localVarHTTPMethod + " ReadAssertions with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAssertions", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadAssertions error for " + localVarHTTPMethod + " ReadAssertions with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue ReadAssertionsResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiReadAuthorizationModelRequest struct { ctx _context.Context ApiService OpenFgaApi id string } func (r ApiReadAuthorizationModelRequest) Execute() (ReadAuthorizationModelResponse, *_nethttp.Response, error) { return r.ApiService.ReadAuthorizationModelExecute(r) } /* - ReadAuthorizationModel Return a particular version of an authorization model - The ReadAuthorizationModel API returns an authorization model by its identifier. The response will return the authorization model for the particular version. ## Example To retrieve the authorization model with ID `01G5JAVJ41T49E9TT3SKVS7X1J` for the store, call the GET authorization-models by ID API with `01G5JAVJ41T49E9TT3SKVS7X1J` as the `id` path parameter. The API will return: ```json { "authorization_model":{ "id":"01G5JAVJ41T49E9TT3SKVS7X1J", "type_definitions":[ { "type":"user" }, { "type":"document", "relations":{ "reader":{ "union":{ "child":[ { "this":{} }, { "computedUserset":{ "object":"", "relation":"writer" } } ] } }, "writer":{ "this":{} } } } ] } } ``` In the above example, there are 2 types (`user` and `document`). The `document` type has 2 relations (`writer` and `reader`). - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param id - @return ApiReadAuthorizationModelRequest */ func (a *OpenFgaApiService) ReadAuthorizationModel(ctx _context.Context, id string) ApiReadAuthorizationModelRequest { return ApiReadAuthorizationModelRequest{ ApiService: a, ctx: ctx, id: id, } } /* * Execute executes the request * @return ReadAuthorizationModelResponse */ func (a *OpenFgaApiService) ReadAuthorizationModelExecute(r ApiReadAuthorizationModelRequest) (ReadAuthorizationModelResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarReturnValue ReadAuthorizationModelResponse ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/authorization-models/{id}" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", _neturl.PathEscape(parameterToString(r.id, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModel", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadAuthorizationModel validation error for " + localVarHTTPMethod + " ReadAuthorizationModel with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModel", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadAuthorizationModel auth error for " + localVarHTTPMethod + " ReadAuthorizationModel with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModel", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadAuthorizationModel validation error for " + localVarHTTPMethod + " ReadAuthorizationModel with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModel", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadAuthorizationModel rate limit error for " + localVarHTTPMethod + " ReadAuthorizationModel with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModel", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadAuthorizationModel internal error for " + localVarHTTPMethod + " ReadAuthorizationModel with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModel", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadAuthorizationModel error for " + localVarHTTPMethod + " ReadAuthorizationModel with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue ReadAuthorizationModelResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiReadAuthorizationModelsRequest struct { ctx _context.Context ApiService OpenFgaApi pageSize *int32 continuationToken *string } func (r ApiReadAuthorizationModelsRequest) PageSize(pageSize int32) ApiReadAuthorizationModelsRequest { r.pageSize = &pageSize return r } func (r ApiReadAuthorizationModelsRequest) ContinuationToken(continuationToken string) ApiReadAuthorizationModelsRequest { r.continuationToken = &continuationToken return r } func (r ApiReadAuthorizationModelsRequest) Execute() (ReadAuthorizationModelsResponse, *_nethttp.Response, error) { return r.ApiService.ReadAuthorizationModelsExecute(r) } /* - ReadAuthorizationModels Return all the authorization models for a particular store - The ReadAuthorizationModels API will return all the authorization models for a certain store. OpenFGA's response will contain an array of all authorization models, sorted in descending order of creation. ## Example Assume that a store's authorization model has been configured twice. To get all the authorization models that have been created in this store, call GET authorization-models. The API will return a response that looks like: ```json { "authorization_models": [ { "id": "01G50QVV17PECNVAHX1GG4Y5NC", "type_definitions": [...] }, { "id": "01G4ZW8F4A07AKQ8RHSVG9RW04", "type_definitions": [...] }, ], "continuation_token": "eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==" } ``` If there are no more authorization models available, the `continuation_token` field will be empty ```json { "authorization_models": [ { "id": "01G50QVV17PECNVAHX1GG4Y5NC", "type_definitions": [...] }, { "id": "01G4ZW8F4A07AKQ8RHSVG9RW04", "type_definitions": [...] }, ], "continuation_token": "" } ``` - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiReadAuthorizationModelsRequest */ func (a *OpenFgaApiService) ReadAuthorizationModels(ctx _context.Context) ApiReadAuthorizationModelsRequest { return ApiReadAuthorizationModelsRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return ReadAuthorizationModelsResponse */ func (a *OpenFgaApiService) ReadAuthorizationModelsExecute(r ApiReadAuthorizationModelsRequest) (ReadAuthorizationModelsResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarReturnValue ReadAuthorizationModelsResponse ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/authorization-models" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.pageSize != nil { localVarQueryParams.Add("page_size", parameterToString(*r.pageSize, "")) } if r.continuationToken != nil { localVarQueryParams.Add("continuation_token", parameterToString(*r.continuationToken, "")) } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModels", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadAuthorizationModels validation error for " + localVarHTTPMethod + " ReadAuthorizationModels with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModels", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadAuthorizationModels auth error for " + localVarHTTPMethod + " ReadAuthorizationModels with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModels", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadAuthorizationModels validation error for " + localVarHTTPMethod + " ReadAuthorizationModels with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModels", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadAuthorizationModels rate limit error for " + localVarHTTPMethod + " ReadAuthorizationModels with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModels", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadAuthorizationModels internal error for " + localVarHTTPMethod + " ReadAuthorizationModels with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadAuthorizationModels", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadAuthorizationModels error for " + localVarHTTPMethod + " ReadAuthorizationModels with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue ReadAuthorizationModelsResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiReadChangesRequest struct { ctx _context.Context ApiService OpenFgaApi type_ *string pageSize *int32 continuationToken *string } func (r ApiReadChangesRequest) Type_(type_ string) ApiReadChangesRequest { r.type_ = &type_ return r } func (r ApiReadChangesRequest) PageSize(pageSize int32) ApiReadChangesRequest { r.pageSize = &pageSize return r } func (r ApiReadChangesRequest) ContinuationToken(continuationToken string) ApiReadChangesRequest { r.continuationToken = &continuationToken return r } func (r ApiReadChangesRequest) Execute() (ReadChangesResponse, *_nethttp.Response, error) { return r.ApiService.ReadChangesExecute(r) } /* - ReadChanges Return a list of all the tuple changes - The ReadChanges API will return a paginated list of tuple changes (additions and deletions) that occurred in a given store, sorted by ascending time. The response will include a continuation token that is used to get the next set of changes. If there are no changes after the provided continuation token, the same token will be returned in order for it to be used when new changes are recorded. If the store never had any tuples added or removed, this token will be empty. You can use the `type` parameter to only get the list of tuple changes that affect objects of that type. When reading a write tuple change, if it was conditioned, the condition will be returned. When reading a delete tuple change, the condition will NOT be returned regardless of whether it was originally conditioned or not. - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiReadChangesRequest */ func (a *OpenFgaApiService) ReadChanges(ctx _context.Context) ApiReadChangesRequest { return ApiReadChangesRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return ReadChangesResponse */ func (a *OpenFgaApiService) ReadChangesExecute(r ApiReadChangesRequest) (ReadChangesResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} localVarReturnValue ReadChangesResponse ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/changes" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.type_ != nil { localVarQueryParams.Add("type", parameterToString(*r.type_, "")) } if r.pageSize != nil { localVarQueryParams.Add("page_size", parameterToString(*r.pageSize, "")) } if r.continuationToken != nil { localVarQueryParams.Add("continuation_token", parameterToString(*r.continuationToken, "")) } // to determine the Content-Type header localVarHTTPContentTypes := []string{} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadChanges", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadChanges validation error for " + localVarHTTPMethod + " ReadChanges with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadChanges", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadChanges auth error for " + localVarHTTPMethod + " ReadChanges with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadChanges", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "ReadChanges validation error for " + localVarHTTPMethod + " ReadChanges with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadChanges", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadChanges rate limit error for " + localVarHTTPMethod + " ReadChanges with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadChanges", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadChanges internal error for " + localVarHTTPMethod + " ReadChanges with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "ReadChanges", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "ReadChanges error for " + localVarHTTPMethod + " ReadChanges with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue ReadChangesResponse return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiWriteRequest struct { ctx _context.Context ApiService OpenFgaApi body *WriteRequest } func (r ApiWriteRequest) Body(body WriteRequest) ApiWriteRequest { r.body = &body return r } func (r ApiWriteRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) { return r.ApiService.WriteExecute(r) } /* - Write Add or delete tuples from the store - The Write API will update the tuples for a certain store. Tuples and type definitions allow OpenFGA to determine whether a relationship exists between an object and an user. In the body, `writes` adds new tuples and `deletes` removes existing tuples. When deleting a tuple, any `condition` specified with it is ignored. The API is not idempotent: if, later on, you try to add the same tuple key (even if the `condition` is different), or if you try to delete a non-existing tuple, it will throw an error. An `authorization_model_id` may be specified in the body. If it is, it will be used to assert that each written tuple (not deleted) is valid for the model specified. If it is not specified, the latest authorization model ID will be used. ## Example ### Adding relationships To add `user:anne` as a `writer` for `document:2021-budget`, call write API with the following ```json { "writes": { "tuple_keys": [ { "user": "user:anne", "relation": "writer", "object": "document:2021-budget" } ] }, "authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC" } ``` ### Removing relationships To remove `user:bob` as a `reader` for `document:2021-budget`, call write API with the following ```json { "deletes": { "tuple_keys": [ { "user": "user:bob", "relation": "reader", "object": "document:2021-budget" } ] } } ``` - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiWriteRequest */ func (a *OpenFgaApiService) Write(ctx _context.Context) ApiWriteRequest { return ApiWriteRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return map[string]interface{} */ func (a *OpenFgaApiService) WriteExecute(r ApiWriteRequest) (map[string]interface{}, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} localVarReturnValue map[string]interface{} ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/write" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.body == nil { return localVarReturnValue, nil, reportError("body is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{"application/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params localVarPostBody = r.body req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Write", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Write validation error for " + localVarHTTPMethod + " Write with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Write", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Write auth error for " + localVarHTTPMethod + " Write with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Write", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "Write validation error for " + localVarHTTPMethod + " Write with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Write", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Write rate limit error for " + localVarHTTPMethod + " Write with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Write", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Write internal error for " + localVarHTTPMethod + " Write with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "Write", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "Write error for " + localVarHTTPMethod + " Write with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue map[string]interface{} return localVarReturnValue, nil, reportError("Error not handled properly") } type ApiWriteAssertionsRequest struct { ctx _context.Context ApiService OpenFgaApi authorizationModelId string body *WriteAssertionsRequest } func (r ApiWriteAssertionsRequest) Body(body WriteAssertionsRequest) ApiWriteAssertionsRequest { r.body = &body return r } func (r ApiWriteAssertionsRequest) Execute() (*_nethttp.Response, error) { return r.ApiService.WriteAssertionsExecute(r) } /* * WriteAssertions Upsert assertions for an authorization model ID * The WriteAssertions API will upsert new assertions for an authorization model id, or overwrite the existing ones. An assertion is an object that contains a tuple key, and the expectation of whether a call to the Check API of that tuple key will return true or false. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param authorizationModelId * @return ApiWriteAssertionsRequest */ func (a *OpenFgaApiService) WriteAssertions(ctx _context.Context, authorizationModelId string) ApiWriteAssertionsRequest { return ApiWriteAssertionsRequest{ ApiService: a, ctx: ctx, authorizationModelId: authorizationModelId, } } /* * Execute executes the request */ func (a *OpenFgaApiService) WriteAssertionsExecute(r ApiWriteAssertionsRequest) (*_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} ) if a.client.cfg.StoreId == "" { return nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/assertions/{authorization_model_id}" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarPath = strings.Replace(localVarPath, "{"+"authorization_model_id"+"}", _neturl.PathEscape(parameterToString(r.authorizationModelId, "")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.body == nil { return nil, reportError("body is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{"application/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params localVarPostBody = r.body req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAssertions", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "WriteAssertions validation error for " + localVarHTTPMethod + " WriteAssertions with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAssertions", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "WriteAssertions auth error for " + localVarHTTPMethod + " WriteAssertions with body " + string(localVarBody) return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAssertions", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "WriteAssertions validation error for " + localVarHTTPMethod + " WriteAssertions with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAssertions", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "WriteAssertions rate limit error for " + localVarHTTPMethod + " WriteAssertions with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAssertions", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "WriteAssertions internal error for " + localVarHTTPMethod + " WriteAssertions with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAssertions", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "WriteAssertions error for " + localVarHTTPMethod + " WriteAssertions with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarHTTPResponse, newErr } return localVarHTTPResponse, nil } // should never have reached this return nil, reportError("Error not handled properly") } type ApiWriteAuthorizationModelRequest struct { ctx _context.Context ApiService OpenFgaApi body *WriteAuthorizationModelRequest } func (r ApiWriteAuthorizationModelRequest) Body(body WriteAuthorizationModelRequest) ApiWriteAuthorizationModelRequest { r.body = &body return r } func (r ApiWriteAuthorizationModelRequest) Execute() (WriteAuthorizationModelResponse, *_nethttp.Response, error) { return r.ApiService.WriteAuthorizationModelExecute(r) } /* - WriteAuthorizationModel Create a new authorization model - The WriteAuthorizationModel API will add a new authorization model to a store. Each item in the `type_definitions` array is a type definition as specified in the field `type_definition`. The response will return the authorization model's ID in the `id` field. ## Example To add an authorization model with `user` and `document` type definitions, call POST authorization-models API with the body: ```json { "type_definitions":[ { "type":"user" }, { "type":"document", "relations":{ "reader":{ "union":{ "child":[ { "this":{} }, { "computedUserset":{ "object":"", "relation":"writer" } } ] } }, "writer":{ "this":{} } } } ] } ``` OpenFGA's response will include the version id for this authorization model, which will look like ``` {"authorization_model_id": "01G50QVV17PECNVAHX1GG4Y5NC"} ``` - @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiWriteAuthorizationModelRequest */ func (a *OpenFgaApiService) WriteAuthorizationModel(ctx _context.Context) ApiWriteAuthorizationModelRequest { return ApiWriteAuthorizationModelRequest{ ApiService: a, ctx: ctx, } } /* * Execute executes the request * @return WriteAuthorizationModelResponse */ func (a *OpenFgaApiService) WriteAuthorizationModelExecute(r ApiWriteAuthorizationModelRequest) (WriteAuthorizationModelResponse, *_nethttp.Response, error) { var maxRetry int var minWaitInMs int if a.RetryParams != nil { maxRetry = a.RetryParams.MinWaitInMs minWaitInMs = a.RetryParams.MinWaitInMs } else { maxRetry = 0 minWaitInMs = 0 } for i := 0; i < maxRetry+1; i++ { var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} localVarReturnValue WriteAuthorizationModelResponse ) if a.client.cfg.StoreId == "" { return localVarReturnValue, nil, reportError("Configuration.StoreId is required and must be specified to call this method") } if a.client.cfg.StoreId != "" && !internalutils.IsWellFormedUlidString(a.client.cfg.StoreId) { return localVarReturnValue, nil, reportError("Configuration.StoreId is invalid") } localVarPath := "/stores/{store_id}/authorization-models" localVarPath = strings.Replace(localVarPath, "{"+"store_id"+"}", _neturl.PathEscape(a.client.cfg.StoreId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := _neturl.Values{} if r.body == nil { return localVarReturnValue, nil, reportError("body is required and must be specified") } // to determine the Content-Type header localVarHTTPContentTypes := []string{"application/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) if localVarHTTPContentType != "" { localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params localVarPostBody = r.body req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := a.client.callAPI(req) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { return localVarReturnValue, localVarHTTPResponse, err } if localVarHTTPResponse.StatusCode >= _nethttp.StatusMultipleChoices { if localVarHTTPResponse.StatusCode == _nethttp.StatusBadRequest || localVarHTTPResponse.StatusCode == _nethttp.StatusUnprocessableEntity { newErr := FgaApiValidationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAuthorizationModel", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "WriteAuthorizationModel validation error for " + localVarHTTPMethod + " WriteAuthorizationModel with body " + string(localVarBody) var v ValidationErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusUnauthorized || localVarHTTPResponse.StatusCode == _nethttp.StatusForbidden { newErr := FgaApiAuthenticationError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAuthorizationModel", responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "WriteAuthorizationModel auth error for " + localVarHTTPMethod + " WriteAuthorizationModel with body " + string(localVarBody) return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusNotFound { newErr := FgaApiNotFoundError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAuthorizationModel", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") newErr.error = "WriteAuthorizationModel validation error for " + localVarHTTPMethod + " WriteAuthorizationModel with body " + string(localVarBody) var v PathUnknownErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode == _nethttp.StatusTooManyRequests { if i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } // maximum number of retry reached newErr := FgaApiRateLimitExceededError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAuthorizationModel", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "WriteAuthorizationModel rate limit error for " + localVarHTTPMethod + " WriteAuthorizationModel with body " + string(localVarBody) // Due to CanonicalHeaderKey, header name is case-insensitive. newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") return localVarReturnValue, localVarHTTPResponse, newErr } if localVarHTTPResponse.StatusCode >= _nethttp.StatusInternalServerError { if localVarHTTPResponse.StatusCode != _nethttp.StatusNotImplemented && i < maxRetry { time.Sleep(time.Duration(internalutils.RandomTime(i, minWaitInMs)) * time.Millisecond) continue } newErr := FgaApiInternalError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAuthorizationModel", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "WriteAuthorizationModel internal error for " + localVarHTTPMethod + " WriteAuthorizationModel with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v InternalErrorMessageResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.GetCode() newErr.error += " with error code " + string(v.GetCode()) + " error message: " + v.GetMessage() return localVarReturnValue, localVarHTTPResponse, newErr } newErr := FgaApiError{ body: localVarBody, storeId: a.client.cfg.StoreId, endpointCategory: "WriteAuthorizationModel", requestBody: localVarPostBody, requestMethod: localVarHTTPMethod, responseStatusCode: localVarHTTPResponse.StatusCode, responseHeader: localVarHTTPResponse.Header, } newErr.error = "WriteAuthorizationModel error for " + localVarHTTPMethod + " WriteAuthorizationModel with body " + string(localVarBody) newErr.requestId = localVarHTTPResponse.Header.Get("Fga-Request-Id") var v ErrorResponse err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr.modelDecodeError = err return localVarReturnValue, localVarHTTPResponse, newErr } newErr.model = v newErr.responseCode = v.Code newErr.error += " with error code " + v.Code + " error message: " + v.Message return localVarReturnValue, localVarHTTPResponse, newErr } err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { newErr := GenericOpenAPIError{ body: localVarBody, error: err.Error(), } return localVarReturnValue, localVarHTTPResponse, newErr } return localVarReturnValue, localVarHTTPResponse, nil } // should never have reached this var localVarReturnValue WriteAuthorizationModelResponse return localVarReturnValue, nil, reportError("Error not handled properly") } golang-github-openfga-go-sdk-0.3.5/api_open_fga_test.go000066400000000000000000001261171456721040100230520ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "context" "encoding/json" "fmt" "net/http" "testing" "github.com/jarcoal/httpmock" "github.com/openfga/go-sdk/credentials" ) type TestDefinition struct { Name string JsonResponse string ResponseStatus int Method string RequestPath string } func TestOpenFgaApiConfiguration(t *testing.T) { t.Run("Providing no store id should not error", func(t *testing.T) { _, err := NewConfiguration(Configuration{ ApiHost: "api.fga.example", }) if err != nil { t.Fatalf("%v", err) } }) t.Run("Providing no store id when calling endpoints that require it should error", func(t *testing.T) { configuration, err := NewConfiguration(Configuration{ ApiHost: "api.fga.example", }) apiClient := NewAPIClient(configuration) if _, _, err = apiClient.OpenFgaApi.ReadAuthorizationModels(context.Background()).Execute(); err == nil { t.Fatalf("Expected an error when storeId is required but not provided") } }) t.Run("Providing no ApiHost should error", func(t *testing.T) { _, err := NewConfiguration(Configuration{}) if err == nil { t.Fatalf("Expected an error when storeId is required but not provided") } }) t.Run("ApiHost should be valid", func(t *testing.T) { _, err := NewConfiguration(Configuration{ ApiHost: "https://api.fga.example", }) if err == nil { t.Fatalf("Expected an error when ApiHost is invalid (scheme is part of the host)") } }) t.Run("Providing invalid storeid should result in error", func(t *testing.T) { _, err := NewConfiguration(Configuration{ ApiHost: "api.fga.example", StoreId: "invalid", }) if err == nil { t.Fatalf("Expect error when invalid storeid is provided") } }) t.Run("In ApiToken credential method, apiToken is required in the Credentials Config", func(t *testing.T) { _, err := NewConfiguration(Configuration{ ApiHost: "https://api.fga.example", Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodApiToken, }, }) if err == nil { t.Fatalf("Expected an error when apiToken is missing but the credential method is ApiToken") } }) t.Run("should issue a successful network call when using ApiToken credential method", func(t *testing.T) { configuration, err := NewConfiguration(Configuration{ ApiHost: "api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodApiToken, Config: &credentials.Config{ ApiToken: "some-token", }, }, }) if err != nil { t.Fatalf("%v", err) } apiClient := NewAPIClient(configuration) httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", fmt.Sprintf("%s/stores/%s/authorization-models", configuration.ApiUrl, configuration.StoreId), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(200, ReadAuthorizationModelsResponse{AuthorizationModels: []AuthorizationModel{ { Id: "01GXSA8YR785C4FYS3C0RTG7B1", TypeDefinitions: []TypeDefinition{}, }, { Id: "01GXSBM5PVYHCJNRNKXMB4QZTW", TypeDefinitions: []TypeDefinition{}, }, }}) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) if _, _, err = apiClient.OpenFgaApi.ReadAuthorizationModels(context.Background()).Execute(); err != nil { t.Fatalf("%v", err) } }) t.Run("In ClientCredentials method, providing no client id, secret or issuer should error", func(t *testing.T) { _, err := NewConfiguration(Configuration{ ApiHost: "https://api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodApiToken, Config: &credentials.Config{ ClientCredentialsClientSecret: "some-secret", }, }, }) if err == nil { t.Fatalf("Expected an error: client id is required") } _, err = NewConfiguration(Configuration{ ApiHost: "https://api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodApiToken, Config: &credentials.Config{ ClientCredentialsClientId: "some-id", ClientCredentialsApiTokenIssuer: "some-issuer", ClientCredentialsApiAudience: "some-audience", }, }, }) if err == nil { t.Fatalf("Expected an error: client secret is required") } _, err = NewConfiguration(Configuration{ ApiHost: "https://api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodApiToken, Config: &credentials.Config{ ClientCredentialsClientId: "some-id", ClientCredentialsClientSecret: "some-secret", ClientCredentialsApiAudience: "some-audience", }, }, }) if err == nil { t.Fatalf("Expected an error: api token issuer is required") } _, err = NewConfiguration(Configuration{ ApiHost: "api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodClientCredentials, Config: &credentials.Config{ ClientCredentialsClientId: "some-id", ClientCredentialsClientSecret: "some-secret", ClientCredentialsApiAudience: "some-audience", ClientCredentialsApiTokenIssuer: "some-issuer.fga.example", }, }, }) if err != nil { t.Fatalf("Unexpected error: %v", err) } }) t.Run("NewCredentials should validate properly", func(t *testing.T) { // Passing valid credentials to NewCredentials should not error creds, err := credentials.NewCredentials(credentials.Credentials{ Method: credentials.CredentialsMethodApiToken, Config: &credentials.Config{ ApiToken: "some-token", }, }) if err != nil { t.Fatalf("Unexpected error: %v", err) } if creds == nil { t.Fatalf("Expected creds to be non-nil") } if creds.Method != credentials.CredentialsMethodApiToken { t.Fatalf("Expected method to be %v, got %v", credentials.CredentialsMethodApiToken, creds.Method) } if creds.Config.ApiToken != "some-token" { t.Fatalf("Expected ApiToken to be %v, got %v", "some-token", creds.Config.ApiToken) } // Passing invalid credentials to NewCredentials should error _, err = credentials.NewCredentials(credentials.Credentials{ Method: credentials.CredentialsMethodApiToken, Config: &credentials.Config{ ClientCredentialsClientSecret: "some-secret", }, }) if err == nil { t.Fatalf("Expected validation error") } }) clientCredentialsFirstRequestTest := func(t *testing.T, config Configuration, expectedTokenEndpoint string) { configuration, err := NewConfiguration(config) if err != nil { t.Fatalf("%v", err) } apiClient := NewAPIClient(configuration) httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", fmt.Sprintf("%s/stores/%s/authorization-models", configuration.ApiUrl, configuration.StoreId), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(200, ReadAuthorizationModelsResponse{AuthorizationModels: []AuthorizationModel{ { Id: "01GXSA8YR785C4FYS3C0RTG7B1", TypeDefinitions: []TypeDefinition{}, }, { Id: "01GXSBM5PVYHCJNRNKXMB4QZTW", TypeDefinitions: []TypeDefinition{}, }, }}) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) httpmock.RegisterResponder("POST", expectedTokenEndpoint, func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(200, struct { AccessToken string `json:"access_token"` }{AccessToken: "abcde"}) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) if _, _, err = apiClient.OpenFgaApi.ReadAuthorizationModels(context.Background()).Execute(); err != nil { t.Fatalf("%v", err) } info := httpmock.GetCallCountInfo() numCalls := info[fmt.Sprintf("POST %s", expectedTokenEndpoint)] if numCalls != 1 { t.Fatalf("Expected call to get access token to be made exactly once, saw: %d", numCalls) } numCalls = info[fmt.Sprintf("GET %s/stores/%s/authorization-models", configuration.ApiUrl, configuration.StoreId)] if numCalls != 1 { t.Fatalf("Expected call to get authorization models to be made exactly once, saw: %d", numCalls) } } tokenIssuers := map[string]string{ "issuer.fga.example": "https://issuer.fga.example/oauth/token", "https://issuer.fga.example": "https://issuer.fga.example/oauth/token", "https://issuer.fga.example/": "https://issuer.fga.example/oauth/token", "https://issuer.fga.example:8080": "https://issuer.fga.example:8080/oauth/token", "https://issuer.fga.example:8080/": "https://issuer.fga.example:8080/oauth/token", "issuer.fga.example/some_endpoint": "https://issuer.fga.example/some_endpoint", "https://issuer.fga.example/some_endpoint": "https://issuer.fga.example/some_endpoint", "https://issuer.fga.example:8080/some_endpoint": "https://issuer.fga.example:8080/some_endpoint", } for tokenIssuer, expectedTokenURL := range tokenIssuers { t.Run("should issue a network call to get the token at the first request if client id is provided", func(t *testing.T) { t.Run("with Auth0 configuration", func(t *testing.T) { clientCredentialsFirstRequestTest(t, Configuration{ ApiUrl: "http://api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodClientCredentials, Config: &credentials.Config{ ClientCredentialsClientId: "some-id", ClientCredentialsClientSecret: "some-secret", ClientCredentialsApiAudience: "some-audience", ClientCredentialsApiTokenIssuer: tokenIssuer, }, }, }, expectedTokenURL) }) t.Run("with OAuth2 configuration", func(t *testing.T) { clientCredentialsFirstRequestTest(t, Configuration{ ApiUrl: "http://api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodClientCredentials, Config: &credentials.Config{ ClientCredentialsClientId: "some-id", ClientCredentialsClientSecret: "some-secret", ClientCredentialsScopes: "scope1 scope2", ClientCredentialsApiTokenIssuer: tokenIssuer, }, }, }, expectedTokenURL) }) }) } t.Run("should not issue a network call to get the token at the first request if the clientId is not provided", func(t *testing.T) { configuration, err := NewConfiguration(Configuration{ ApiHost: "api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodNone, Config: &credentials.Config{ClientCredentialsApiTokenIssuer: "tokenissuer.api.example"}, }, }) if err != nil { t.Fatalf("%v", err) } configuration.ApiHost = "api.fga.example" apiClient := NewAPIClient(configuration) httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("GET", fmt.Sprintf("%s/stores/%s/authorization-models", configuration.ApiUrl, configuration.StoreId), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(200, ReadAuthorizationModelsResponse{AuthorizationModels: []AuthorizationModel{ { Id: "01GXSA8YR785C4FYS3C0RTG7B1", TypeDefinitions: []TypeDefinition{}, }, { Id: "01GXSBM5PVYHCJNRNKXMB4QZTW", TypeDefinitions: []TypeDefinition{}, }, }}) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) if _, _, err = apiClient.OpenFgaApi.ReadAuthorizationModels(context.Background()).Execute(); err != nil { t.Fatalf("%v", err) } info := httpmock.GetCallCountInfo() numCalls := info[fmt.Sprintf("POST https://%s/oauth/token", configuration.Credentials.Config.ClientCredentialsApiTokenIssuer)] if numCalls != 0 { t.Fatalf("Unexpected call to get access token made. Expected 0, saw: %d", numCalls) } numCalls = info[fmt.Sprintf("GET %s/stores/%s/authorization-models", configuration.ApiUrl, configuration.StoreId)] if numCalls != 1 { t.Fatalf("Expected call to get authorization models to be made exactly once, saw: %d", numCalls) } }) t.Run("Updating StoreId after initialization should work", func(t *testing.T) { configuration, err := NewConfiguration(Configuration{ ApiHost: "api.fga.example", Credentials: &credentials.Credentials{ Method: credentials.CredentialsMethodClientCredentials, Config: &credentials.Config{ ClientCredentialsClientId: "some-id", ClientCredentialsClientSecret: "some-secret", ClientCredentialsApiAudience: "some-audience", ClientCredentialsApiTokenIssuer: "tokenissuer.fga.example", }, }, }) if err != nil { t.Fatalf("%v", err) } apiClient := NewAPIClient(configuration) if apiClient.GetStoreId() != "" { t.Fatalf("apiClient.GetStoreId() = \"\", want %v", apiClient.GetStoreId()) } storeId := "some-id" apiClient.SetStoreId(storeId) if apiClient.GetStoreId() != storeId { t.Fatalf("apiClient.GetStoreId() = %v, want %v", apiClient.GetStoreId(), storeId) } storeId = "some-other-id" apiClient.SetStoreId(storeId) if apiClient.GetStoreId() != storeId { t.Fatalf("apiClient.GetStoreId() = %v, want %v", apiClient.GetStoreId(), storeId) } }) t.Run("Issuing a call to a method that requires StoreId without providing it should error", func(t *testing.T) { configuration, err := NewConfiguration(Configuration{ ApiHost: "api.fga.example", }) if err != nil { t.Fatalf("%v", err) } apiClient := NewAPIClient(configuration) if apiClient.GetStoreId() != "" { t.Fatalf("apiClient.GetStoreId() = \"\", want %v", apiClient.GetStoreId()) } _, _, err = apiClient.OpenFgaApi.ReadAuthorizationModels(context.Background()).Execute() if err == nil { t.Fatalf("Expected an error, got none") } }) } func TestOpenFgaApi(t *testing.T) { configuration, err := NewConfiguration(Configuration{ ApiHost: "api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", }) if err != nil { t.Fatalf("%v", err) } apiClient := NewAPIClient(configuration) t.Run("ReadAuthorizationModels", func(t *testing.T) { test := TestDefinition{ Name: "ReadAuthorizationModels", JsonResponse: `{"authorization_models":[{"id":"01GXSA8YR785C4FYS3C0RTG7B1","schema_version":"1.1","type_definitions":[]}]}`, ResponseStatus: 200, Method: "GET", RequestPath: "authorization-models", } var expectedResponse ReadAuthorizationModelsResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) got, response, err := apiClient.OpenFgaApi.ReadAuthorizationModels(context.Background()).Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } if len(got.AuthorizationModels) != 1 { t.Fatalf("%v", err) } if got.AuthorizationModels[0].Id != expectedResponse.AuthorizationModels[0].Id { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, got.AuthorizationModels[0].Id, expectedResponse.AuthorizationModels[0].Id) } }) t.Run("WriteAuthorizationModel", func(t *testing.T) { test := TestDefinition{ Name: "WriteAuthorizationModel", JsonResponse: `{"authorization_model_id":"01GXSA8YR785C4FYS3C0RTG7B1"}`, ResponseStatus: 200, Method: "POST", RequestPath: "authorization-models", } requestBody := WriteAuthorizationModelRequest{ TypeDefinitions: []TypeDefinition{{ Type: "github-repo", Relations: &map[string]Userset{ "repo_writer": { This: &map[string]interface{}{}, }, "viewer": {Union: &Usersets{ Child: []Userset{ {This: &map[string]interface{}{}}, {ComputedUserset: &ObjectRelation{ Object: PtrString(""), Relation: PtrString("repo_writer"), }}, }, }}, }, }}, } var expectedResponse WriteAuthorizationModelResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) got, response, err := apiClient.OpenFgaApi.WriteAuthorizationModel(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } _, err = got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } }) t.Run("ReadAuthorizationModel", func(t *testing.T) { test := TestDefinition{ Name: "ReadAuthorizationModel", JsonResponse: `{"authorization_model":{"id":"01GXSA8YR785C4FYS3C0RTG7B1", "schema_version":"1.1", "type_definitions":[{"type":"github-repo", "relations":{"viewer":{"this":{}}}}]}}`, ResponseStatus: 200, Method: "GET", RequestPath: "authorization-models", } var expectedResponse ReadAuthorizationModelResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } modelId := expectedResponse.AuthorizationModel.Id httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath, modelId), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) got, response, err := apiClient.OpenFgaApi.ReadAuthorizationModel(context.Background(), modelId).Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if got.AuthorizationModel.Id != modelId { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } }) t.Run("Check", func(t *testing.T) { test := TestDefinition{ Name: "Check", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: 200, Method: "POST", RequestPath: "check", } requestBody := CheckRequest{ TupleKey: CheckRequestTupleKey{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }, AuthorizationModelId: PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } var expectedResponse CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) got, response, err := apiClient.OpenFgaApi.Check(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if *got.Allowed != *expectedResponse.Allowed { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } }) t.Run("Write (Write Tuple)", func(t *testing.T) { test := TestDefinition{ Name: "Write", JsonResponse: `{}`, ResponseStatus: 200, Method: "POST", RequestPath: "write", } requestBody := WriteRequest{ Writes: &WriteRequestWrites{ TupleKeys: []TupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }}, }, AuthorizationModelId: PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } var expectedResponse map[string]interface{} if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) _, response, err := apiClient.OpenFgaApi.Write(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } }) t.Run("Write (Delete Tuple)", func(t *testing.T) { test := TestDefinition{ Name: "Write", JsonResponse: `{}`, ResponseStatus: 200, Method: "POST", RequestPath: "write", } requestBody := WriteRequest{ Deletes: &WriteRequestDeletes{ TupleKeys: []TupleKeyWithoutCondition{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }}, }, AuthorizationModelId: PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } var expectedResponse map[string]interface{} if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) _, response, err := apiClient.OpenFgaApi.Write(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } }) t.Run("Expand", func(t *testing.T) { test := TestDefinition{ Name: "Expand", JsonResponse: `{"tree":{"root":{"name":"document:roadmap#viewer","union":{"nodes":[{"name": "document:roadmap#viewer","leaf":{"users":{"users":["user:81684243-9356-4421-8fbf-a4f8d36aa31b"]}}}]}}}}`, ResponseStatus: 200, Method: "POST", RequestPath: "expand", } requestBody := ExpandRequest{ TupleKey: ExpandRequestTupleKey{ Relation: "viewer", Object: "document:roadmap", }, AuthorizationModelId: PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } var expectedResponse ExpandResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) got, response, err := apiClient.OpenFgaApi.Expand(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } _, err = got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } }) t.Run("Read", func(t *testing.T) { test := TestDefinition{ Name: "Read", JsonResponse: `{"tuples":[{"key":{"user":"user:81684243-9356-4421-8fbf-a4f8d36aa31b","relation":"viewer","object":"document:roadmap"},"timestamp": "2000-01-01T00:00:00Z"}]}`, ResponseStatus: 200, Method: "POST", RequestPath: "read", } requestBody := ReadRequest{ TupleKey: &ReadRequestTupleKey{ User: PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"), Relation: PtrString("viewer"), Object: PtrString("document:roadmap"), }, } var expectedResponse ReadResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) got, response, err := apiClient.OpenFgaApi.Read(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if len(got.Tuples) != len(expectedResponse.Tuples) { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } }) t.Run("ReadChanges", func(t *testing.T) { test := TestDefinition{ Name: "ReadChanges", JsonResponse: `{"changes":[{"tuple_key":{"user":"user:81684243-9356-4421-8fbf-a4f8d36aa31b","relation":"viewer","object":"document:roadmap"},"operation":"TUPLE_OPERATION_WRITE","timestamp": "2000-01-01T00:00:00Z"}],"continuation_token":"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="}`, ResponseStatus: 200, Method: "GET", RequestPath: "changes", } var expectedResponse ReadChangesResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) got, response, err := apiClient.OpenFgaApi.ReadChanges(context.Background()). Type_("repo"). PageSize(25). ContinuationToken("eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="). Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if len(got.Changes) != len(expectedResponse.Changes) { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } }) t.Run("ListObjects", func(t *testing.T) { test := TestDefinition{ Name: "ListObjects", JsonResponse: `{"objects":["document:roadmap"]}`, ResponseStatus: 200, Method: "POST", RequestPath: "list-objects", } requestBody := ListObjectsRequest{ AuthorizationModelId: PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "can_read", Type: "document", ContextualTuples: &ContextualTupleKeys{ TupleKeys: []TupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "folder:product", }, { User: "folder:product", Relation: "parent", Object: "document:roadmap", }}, }, } var expectedResponse ListObjectsResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(500, ""), nil } return resp, nil }, ) got, response, err := apiClient.OpenFgaApi.ListObjects(context.Background()). Body(requestBody). Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if len(got.Objects) != len(expectedResponse.Objects) || (got.Objects)[0] != (expectedResponse.Objects)[0] { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } }) t.Run("Check with 400 error", func(t *testing.T) { test := TestDefinition{ Name: "Check", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: 400, Method: "POST", RequestPath: "check", } requestBody := CheckRequest{ TupleKey: CheckRequestTupleKey{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }, } var expectedResponse CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { errObj := ErrorResponse{ Code: "validation_error", Message: "Foo", } return httpmock.NewJsonResponse(400, errObj) }, ) _, _, err := apiClient.OpenFgaApi.Check(context.Background()).Body(requestBody).Execute() if err == nil { t.Fatalf("Expected error with 400 request but there is none") } validationError, ok := err.(FgaApiValidationError) if !ok { t.Fatalf("Expected validation Error but type is incorrect %v", err) } // Do some basic validation of the error itself if validationError.StoreId() != configuration.StoreId { t.Fatalf("Expected store id to be %s but actual %s", configuration.StoreId, validationError.StoreId()) } if validationError.EndpointCategory() != "Check" { t.Fatalf("Expected category to be Check but actual %s", validationError.EndpointCategory()) } if validationError.RequestMethod() != "POST" { t.Fatalf("Expected category to be POST but actual %s", validationError.RequestMethod()) } if validationError.ResponseStatusCode() != 400 { t.Fatalf("Expected status code to be 400 but actual %d", validationError.ResponseStatusCode()) } if validationError.ResponseCode() != VALIDATION_ERROR { t.Fatalf("Expected response code to be VALIDATION_ERROR but actual %s", validationError.ResponseCode()) } }) t.Run("Check with 401 error", func(t *testing.T) { test := TestDefinition{ Name: "Check", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: 401, Method: "POST", RequestPath: "check", } requestBody := CheckRequest{ TupleKey: CheckRequestTupleKey{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }, } var expectedResponse CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { errObj := ErrorResponse{ Code: "auth_failure", Message: "Foo", } return httpmock.NewJsonResponse(401, errObj) }, ) _, _, err := apiClient.OpenFgaApi.Check(context.Background()).Body(requestBody).Execute() if err == nil { t.Fatalf("Expected error with 401 request but there is none") } authenticationError, ok := err.(FgaApiAuthenticationError) if !ok { t.Fatalf("Expected authentication Error but type is incorrect %v", err) } // Do some basic validation of the error itself if authenticationError.StoreId() != configuration.StoreId { t.Fatalf("Expected store id to be %s but actual %s", configuration.StoreId, authenticationError.StoreId()) } if authenticationError.EndpointCategory() != "Check" { t.Fatalf("Expected category to be Check but actual %s", authenticationError.EndpointCategory()) } if authenticationError.ResponseStatusCode() != 401 { t.Fatalf("Expected status code to be 401 but actual %d", authenticationError.ResponseStatusCode()) } }) t.Run("Check with 404 error", func(t *testing.T) { test := TestDefinition{ Name: "Check", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: 404, Method: "POST", RequestPath: "check", } requestBody := CheckRequest{ TupleKey: CheckRequestTupleKey{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }, } var expectedResponse CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { errObj := ErrorResponse{ Code: "undefined_endpoint", Message: "Foo", } return httpmock.NewJsonResponse(404, errObj) }, ) _, _, err := apiClient.OpenFgaApi.Check(context.Background()).Body(requestBody).Execute() if err == nil { t.Fatalf("Expected error with 404 request but there is none") } notFoundError, ok := err.(FgaApiNotFoundError) if !ok { t.Fatalf("Expected not found Error but type is incorrect %v", err) } // Do some basic validation of the error itself if notFoundError.StoreId() != configuration.StoreId { t.Fatalf("Expected store id to be %s but actual %s", configuration.StoreId, notFoundError.StoreId()) } if notFoundError.EndpointCategory() != "Check" { t.Fatalf("Expected category to be Check but actual %s", notFoundError.EndpointCategory()) } if notFoundError.RequestMethod() != "POST" { t.Fatalf("Expected category to be POST but actual %s", notFoundError.RequestMethod()) } if notFoundError.ResponseStatusCode() != 404 { t.Fatalf("Expected status code to be 404 but actual %d", notFoundError.ResponseStatusCode()) } if notFoundError.ResponseCode() != UNDEFINED_ENDPOINT { t.Fatalf("Expected response code to be UNDEFINED_ENDPOINT but actual %s", notFoundError.ResponseCode()) } }) t.Run("Check with 429 error", func(t *testing.T) { test := TestDefinition{ Name: "Check", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: 429, Method: "POST", RequestPath: "check", } requestBody := CheckRequest{ TupleKey: CheckRequestTupleKey{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }, } var expectedResponse CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { errObj := ErrorResponse{ Code: "rate_limit_exceeded", Message: "Foo", } return httpmock.NewJsonResponse(429, errObj) }, ) updatedConfiguration, err := NewConfiguration(Configuration{ ApiHost: "api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", RetryParams: &RetryParams{ MaxRetry: 3, MinWaitInMs: 5, }, }) if err != nil { t.Fatalf("%v", err) } updatedApiClient := NewAPIClient(updatedConfiguration) _, _, err = updatedApiClient.OpenFgaApi.Check(context.Background()).Body(requestBody).Execute() if err == nil { t.Fatalf("Expected error with 429 request but there is none") } rateLimitError, ok := err.(FgaApiRateLimitExceededError) if !ok { t.Fatalf("Expected rate limit exceeded Error but type is incorrect %v", err) } // Do some basic validation of the error itself if rateLimitError.StoreId() != configuration.StoreId { t.Fatalf("Expected store id to be %s but actual %s", configuration.StoreId, rateLimitError.StoreId()) } if rateLimitError.EndpointCategory() != "Check" { t.Fatalf("Expected category to be Check but actual %s", rateLimitError.EndpointCategory()) } if rateLimitError.ResponseStatusCode() != 429 { t.Fatalf("Expected status code to be 429 but actual %d", rateLimitError.ResponseStatusCode()) } }) t.Run("Check with initial 429 but eventually resolved", func(t *testing.T) { test := TestDefinition{ Name: "Check", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: 200, Method: "POST", RequestPath: "check", } requestBody := CheckRequest{ TupleKey: CheckRequestTupleKey{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }, } var expectedResponse CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() firstMock := httpmock.NewStringResponder(429, "") secondMock, _ := httpmock.NewJsonResponder(200, expectedResponse) httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), firstMock.Then(firstMock).Then(firstMock).Then(secondMock), ) updatedConfiguration, err := NewConfiguration(Configuration{ ApiHost: "api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", RetryParams: &RetryParams{ MaxRetry: 2, MinWaitInMs: 5, }, }) if err != nil { t.Fatalf("%v", err) } updatedApiClient := NewAPIClient(updatedConfiguration) got, response, err := updatedApiClient.OpenFgaApi.Check(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } if response.StatusCode != test.ResponseStatus { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, response.StatusCode, test.ResponseStatus) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if *got.Allowed != *expectedResponse.Allowed { t.Fatalf("OpenFga%v().Execute() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } }) t.Run("Check with 500 error", func(t *testing.T) { test := TestDefinition{ Name: "Check", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: 500, Method: "POST", RequestPath: "check", } requestBody := CheckRequest{ TupleKey: CheckRequestTupleKey{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }, } var expectedResponse CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", configuration.ApiUrl, configuration.StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { errObj := ErrorResponse{ Code: "internal_error", Message: "Foo", } return httpmock.NewJsonResponse(500, errObj) }, ) _, _, err := apiClient.OpenFgaApi.Check(context.Background()).Body(requestBody).Execute() if err == nil { t.Fatalf("Expected error with 500 request but there is none") } internalError, ok := err.(FgaApiInternalError) if !ok { t.Fatalf("Expected internal Error but type is incorrect %v", err) } // Do some basic validation of the error itself if internalError.StoreId() != configuration.StoreId { t.Fatalf("Expected store id to be %s but actual %s", configuration.StoreId, internalError.StoreId()) } if internalError.EndpointCategory() != "Check" { t.Fatalf("Expected category to be Check but actual %s", internalError.EndpointCategory()) } if internalError.RequestMethod() != "POST" { t.Fatalf("Expected category to be POST but actual %s", internalError.RequestMethod()) } if internalError.ResponseStatusCode() != 500 { t.Fatalf("Expected status code to be 500 but actual %d", internalError.ResponseStatusCode()) } if internalError.ResponseCode() != INTERNAL_ERROR { t.Fatalf("Expected response code to be INTERNAL_ERROR but actual %s", internalError.ResponseCode()) } }) } golang-github-openfga-go-sdk-0.3.5/client/000077500000000000000000000000001456721040100203235ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/client/client.go000066400000000000000000002237551456721040100221460ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package client import ( _context "context" "encoding/json" "fmt" "math" _nethttp "net/http" fgaSdk "github.com/openfga/go-sdk" "github.com/openfga/go-sdk/credentials" internalutils "github.com/openfga/go-sdk/internal/utils" "golang.org/x/sync/errgroup" ) var ( _ _context.Context // Ensure the SdkClient fits OpenFgaClient interface _ SdkClient = (*OpenFgaClient)(nil) ) var DEFAULT_MAX_METHOD_PARALLEL_REQS = int32(10) type ClientConfiguration struct { fgaSdk.Configuration // ApiScheme - defines the scheme for the API: http or https // Deprecated: use ApiUrl instead of ApiScheme and ApiHost ApiScheme string `json:"api_scheme"` // ApiHost - defines the host for the API without the scheme e.g. (api.fga.example) // Deprecated: use ApiUrl instead of ApiScheme and ApiHost ApiHost string `json:"api_host"` ApiUrl string `json:"api_url"` StoreId string `json:"store_id"` AuthorizationModelId string `json:"authorization_model_id"` Credentials *credentials.Credentials `json:"credentials"` DefaultHeaders map[string]string `json:"default_headers"` UserAgent string `json:"user_agent"` Debug bool `json:"debug"` HTTPClient *_nethttp.Client RetryParams *fgaSdk.RetryParams } func newClientConfiguration(cfg *fgaSdk.Configuration) ClientConfiguration { return ClientConfiguration{ ApiScheme: cfg.ApiScheme, ApiHost: cfg.ApiHost, ApiUrl: cfg.ApiUrl, StoreId: cfg.StoreId, Credentials: cfg.Credentials, DefaultHeaders: cfg.DefaultHeaders, UserAgent: cfg.UserAgent, Debug: cfg.Debug, RetryParams: cfg.RetryParams, } } type OpenFgaClient struct { config ClientConfiguration SdkClient fgaSdk.APIClient } func NewSdkClient(cfg *ClientConfiguration) (*OpenFgaClient, error) { apiConfiguration, err := fgaSdk.NewConfiguration(fgaSdk.Configuration{ ApiScheme: cfg.ApiScheme, ApiHost: cfg.ApiHost, ApiUrl: cfg.ApiUrl, StoreId: cfg.StoreId, Credentials: cfg.Credentials, DefaultHeaders: cfg.DefaultHeaders, UserAgent: cfg.UserAgent, Debug: cfg.Debug, RetryParams: cfg.RetryParams, }) if err != nil { return nil, err } clientConfig := newClientConfiguration(apiConfiguration) clientConfig.AuthorizationModelId = cfg.AuthorizationModelId // store id is already validate as part of configuration validation if cfg.AuthorizationModelId != "" && !internalutils.IsWellFormedUlidString(cfg.AuthorizationModelId) { return nil, FgaInvalidError{param: "AuthorizationModelId", description: "ULID"} } apiClient := fgaSdk.NewAPIClient(apiConfiguration) return &OpenFgaClient{ config: clientConfig, APIClient: *apiClient, }, nil } type ClientRequestOptions struct { MaxRetry *int `json:"max_retry,omitempty"` MinWaitInMs *int `json:"min_wait_in_ms,omitempty"` } type AuthorizationModelIdOptions struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"` } type ClientRequestOptionsWithAuthZModelId struct { ClientRequestOptions AuthorizationModelIdOptions } type ClientTupleKey = fgaSdk.TupleKey type ClientTupleKeyWithoutCondition = fgaSdk.TupleKeyWithoutCondition type ClientCheckRequestTupleKey = fgaSdk.CheckRequestTupleKey type ClientReadRequestTupleKey = fgaSdk.ReadRequestTupleKey type ClientExpandRequestTupleKey = fgaSdk.ExpandRequestTupleKey type ClientContextualTupleKey = ClientTupleKey type ClientPaginationOptions struct { PageSize *int32 `json:"page_size,omitempty"` ContinuationToken *string `json:"continuation_token,omitempty"` } func getPageSizeFromRequest(options *ClientPaginationOptions) *int32 { if options == nil { return nil } return options.PageSize } func getContinuationTokenFromRequest(options *ClientPaginationOptions) *string { if options == nil { return nil } return options.ContinuationToken } type SdkClient interface { /* Stores */ /* * ListStores Get a paginated list of stores. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientListStoresRequestInterface */ ListStores(ctx _context.Context) SdkClientListStoresRequestInterface /* * ListStoresExecute executes the ListStores request * @return *ClientListStoresResponse */ ListStoresExecute(request SdkClientListStoresRequestInterface) (*ClientListStoresResponse, error) /* * CreateStore Create and initialize a store * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientCreateStoreRequestInterface */ CreateStore(ctx _context.Context) SdkClientCreateStoreRequestInterface /* * CreateStoreExecute executes the CreateStore request * @return *ClientCreateStoreResponse */ CreateStoreExecute(request SdkClientCreateStoreRequestInterface) (*ClientCreateStoreResponse, error) /* * GetStore Get information about the current store. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientGetStoreRequestInterface */ GetStore(ctx _context.Context) SdkClientGetStoreRequestInterface /* * GetStoreExecute executes the GetStore request * @return *ClientGetStoreResponse */ GetStoreExecute(request SdkClientGetStoreRequestInterface) (*ClientGetStoreResponse, error) /* * DeleteStore Delete a store. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientDeleteStoreRequestInterface */ DeleteStore(ctx _context.Context) SdkClientDeleteStoreRequestInterface /* * DeleteStoreExecute executes the DeleteStore request * @return *ClientDeleteStoreResponse */ DeleteStoreExecute(request SdkClientDeleteStoreRequestInterface) (*ClientDeleteStoreResponse, error) /* Authorization Models */ /* * ReadAuthorizationModels Read all authorization models in the store. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientReadAuthorizationModelsRequest */ ReadAuthorizationModels(ctx _context.Context) SdkClientReadAuthorizationModelsRequestInterface /* * ReadAuthorizationModelsExecute executes the ReadAuthorizationModels request * @return *ClientReadAuthorizationModelsResponse */ ReadAuthorizationModelsExecute(request SdkClientReadAuthorizationModelsRequestInterface) (*ClientReadAuthorizationModelsResponse, error) /* * WriteAuthorizationModel Create a new authorization model. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientWriteAuthorizationModelRequest */ WriteAuthorizationModel(ctx _context.Context) SdkClientWriteAuthorizationModelRequestInterface /* * WriteAuthorizationModelExecute executes the WriteAuthorizationModel request * @return *ClientWriteAuthorizationModelResponse */ WriteAuthorizationModelExecute(request SdkClientWriteAuthorizationModelRequestInterface) (*ClientWriteAuthorizationModelResponse, error) /* * ReadAuthorizationModel Read a particular authorization model. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientReadAuthorizationModelRequestInterface */ ReadAuthorizationModel(ctx _context.Context) SdkClientReadAuthorizationModelRequestInterface /* * ReadAuthorizationModelExecute executes the ReadAuthorizationModel request * @return *ClientReadAuthorizationModelResponse */ ReadAuthorizationModelExecute(request SdkClientReadAuthorizationModelRequestInterface) (*ClientReadAuthorizationModelResponse, error) /* * ReadLatestAuthorizationModel Reads the latest authorization model (note: this ignores the model id in configuration). * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientReadLatestAuthorizationModelRequestInterface */ ReadLatestAuthorizationModel(ctx _context.Context) SdkClientReadLatestAuthorizationModelRequestInterface /* * ReadLatestAuthorizationModelExecute executes the ReadLatestAuthorizationModel request * @return *ClientReadAuthorizationModelResponse */ ReadLatestAuthorizationModelExecute(request SdkClientReadLatestAuthorizationModelRequestInterface) (*ClientReadAuthorizationModelResponse, error) /* Relationship Tuples */ /* * ReadChanges Reads the list of historical relationship tuple writes and deletes. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientReadChangesRequestInterface */ ReadChanges(ctx _context.Context) SdkClientReadChangesRequestInterface /* * ReadChangesExecute executes the ReadChanges request * @return *ClientReadChangesResponse */ ReadChangesExecute(request SdkClientReadChangesRequestInterface) (*ClientReadChangesResponse, error) /* * Read Reads the relationship tuples stored in the database. It does not evaluate nor exclude invalid tuples according to the authorization model. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientReadRequestInterface */ Read(ctx _context.Context) SdkClientReadRequestInterface /* * ReadExecute executes the Read request * @return *ClientReadResponse */ ReadExecute(request SdkClientReadRequestInterface) (*ClientReadResponse, error) /* * Write Create and/or delete relationship tuples to update the system state. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientWriteRequestInterface */ Write(ctx _context.Context) SdkClientWriteRequestInterface /* * WriteExecute executes the Write request * @return *ClientWriteResponse */ WriteExecute(request SdkClientWriteRequestInterface) (*ClientWriteResponse, error) /* * WriteTuples Utility method around Write * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientWriteTuplesRequestInterface */ WriteTuples(ctx _context.Context) SdkClientWriteTuplesRequestInterface /* * WriteTuplesExecute executes the WriteTuples request * @return *ClientWriteResponse */ WriteTuplesExecute(request SdkClientWriteTuplesRequestInterface) (*ClientWriteResponse, error) /* * DeleteTuples Utility method around Write * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientDeleteTuplesRequestInterface */ DeleteTuples(ctx _context.Context) SdkClientDeleteTuplesRequestInterface /* * DeleteTuplesExecute executes the DeleteTuples request * @return *ClientWriteResponse */ DeleteTuplesExecute(request SdkClientDeleteTuplesRequestInterface) (*ClientWriteResponse, error) /* Relationship Queries */ /* * Check Check if a user has a particular relation with an object. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientCheckRequestInterface */ Check(ctx _context.Context) SdkClientCheckRequestInterface /* * CheckExecute executes the Check request * @return *ClientCheckResponse */ CheckExecute(request SdkClientCheckRequestInterface) (*ClientCheckResponse, error) /* * BatchCheck Run a set of [checks](#check). Batch Check will return `allowed: false` if it encounters an error, and will return the error in the body. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientBatchCheckRequestInterface */ BatchCheck(ctx _context.Context) SdkClientBatchCheckRequestInterface /* * BatchCheckExecute executes the BatchCheck request * @return *ClientBatchCheckResponse */ BatchCheckExecute(request SdkClientBatchCheckRequestInterface) (*ClientBatchCheckResponse, error) /* * Expand Expands the relationships in userset tree format. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientExpandRequestInterface */ Expand(ctx _context.Context) SdkClientExpandRequestInterface /* * ExpandExecute executes the Expand request * @return *ClientExpandResponse */ ExpandExecute(request SdkClientExpandRequestInterface) (*ClientExpandResponse, error) /* * ListObjects List the objects of a particular type a user has access to. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientListObjectsRequestInterface */ ListObjects(ctx _context.Context) SdkClientListObjectsRequestInterface /* * ListObjectsExecute executes the ListObjects request * @return *ClientListObjectsResponse */ ListObjectsExecute(request SdkClientListObjectsRequestInterface) (*ClientListObjectsResponse, error) /* * ListRelations List the relations a user has on an object. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientListRelationsRequestInterface */ ListRelations(ctx _context.Context) SdkClientListRelationsRequestInterface /* * ListRelationsExecute executes the ListRelations request * @return *ClientListRelationsResponse */ ListRelationsExecute(request SdkClientListRelationsRequestInterface) (*ClientListRelationsResponse, error) /* Assertions */ /* * ReadAssertions Read assertions for a particular authorization model. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientReadAssertionsRequestInterface */ ReadAssertions(ctx _context.Context) SdkClientReadAssertionsRequestInterface /* * ReadAssertionsExecute executes the ReadAssertions request * @return *ClientReadAssertionsResponse */ ReadAssertionsExecute(request SdkClientReadAssertionsRequestInterface) (*ClientReadAssertionsResponse, error) /* * WriteAssertions Update the assertions for a particular authorization model. * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @return SdkClientWriteAssertionsRequestInterface */ WriteAssertions(ctx _context.Context) SdkClientWriteAssertionsRequestInterface /* * WriteAssertionsExecute executes the WriteAssertions request * @return *ClientWriteAssertionsResponse */ WriteAssertionsExecute(request SdkClientWriteAssertionsRequestInterface) (*ClientWriteAssertionsResponse, error) } func (client *OpenFgaClient) SetAuthorizationModelId(authorizationModelId string) error { if authorizationModelId != "" && !internalutils.IsWellFormedUlidString(authorizationModelId) { return FgaInvalidError{param: "AuthorizationModelId", description: "ULID"} } client.config.AuthorizationModelId = authorizationModelId return nil } func (client *OpenFgaClient) GetAuthorizationModelId() (string, error) { modelId := client.config.AuthorizationModelId if modelId != "" && !internalutils.IsWellFormedUlidString(modelId) { return "", FgaInvalidError{param: "AuthorizationModelId", description: "ULID"} } return modelId, nil } func (client *OpenFgaClient) getAuthorizationModelId(authorizationModelId *string) (*string, error) { modelId := client.config.AuthorizationModelId if authorizationModelId != nil && *authorizationModelId != "" { modelId = *authorizationModelId } if modelId != "" && !internalutils.IsWellFormedUlidString(modelId) { return nil, FgaInvalidError{param: "AuthorizationModelId", description: "ULID"} } return &modelId, nil } // helper function to validate the connection (i.e., get token) func (client *OpenFgaClient) checkValidApiConnection(ctx _context.Context, authorizationModelId *string) error { if authorizationModelId != nil && *authorizationModelId != "" { _, _, err := client.OpenFgaApi.ReadAuthorizationModel(ctx, *authorizationModelId).Execute() return err } else { _, err := client.ReadAuthorizationModels(ctx).Options(ClientReadAuthorizationModelsOptions{ PageSize: fgaSdk.PtrInt32(1), }).Execute() return err } } /* Stores */ // / ListStores type SdkClientListStoresRequest struct { ctx _context.Context Client *OpenFgaClient options *ClientListStoresOptions } type SdkClientListStoresRequestInterface interface { Options(options ClientListStoresOptions) SdkClientListStoresRequestInterface Execute() (*ClientListStoresResponse, error) GetContext() _context.Context GetOptions() *ClientListStoresOptions } type ClientListStoresOptions struct { PageSize *int32 `json:"page_size,omitempty"` ContinuationToken *string `json:"continuation_token,omitempty"` } type ClientListStoresResponse = fgaSdk.ListStoresResponse func (request *SdkClientListStoresRequest) Options(options ClientListStoresOptions) SdkClientListStoresRequestInterface { request.options = &options return request } func (request *SdkClientListStoresRequest) Execute() (*ClientListStoresResponse, error) { return request.Client.ListStoresExecute(request) } func (request *SdkClientListStoresRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientListStoresRequest) GetOptions() *ClientListStoresOptions { return request.options } func (client *OpenFgaClient) ListStoresExecute(request SdkClientListStoresRequestInterface) (*ClientListStoresResponse, error) { req := client.OpenFgaApi.ListStores(request.GetContext()) pageSize := getPageSizeFromRequest((*ClientPaginationOptions)(request.GetOptions())) if pageSize != nil { req = req.PageSize(*pageSize) } continuationToken := getContinuationTokenFromRequest((*ClientPaginationOptions)(request.GetOptions())) if continuationToken != nil { req = req.ContinuationToken(*continuationToken) } data, _, err := req.Execute() if err != nil { return nil, err } return &data, nil } func (client *OpenFgaClient) ListStores(ctx _context.Context) SdkClientListStoresRequestInterface { return &SdkClientListStoresRequest{ ctx: ctx, Client: client, } } // / CreateStore type SdkClientCreateStoreRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientCreateStoreRequest options *ClientCreateStoreOptions } type SdkClientCreateStoreRequestInterface interface { Options(options ClientCreateStoreOptions) SdkClientCreateStoreRequestInterface Body(body ClientCreateStoreRequest) SdkClientCreateStoreRequestInterface Execute() (*ClientCreateStoreResponse, error) GetContext() _context.Context GetOptions() *ClientCreateStoreOptions GetBody() *ClientCreateStoreRequest } type ClientCreateStoreRequest struct { Name string `json:"name"` } type ClientCreateStoreOptions struct { } type ClientCreateStoreResponse = fgaSdk.CreateStoreResponse func (request *SdkClientCreateStoreRequest) Options(options ClientCreateStoreOptions) SdkClientCreateStoreRequestInterface { request.options = &options return request } func (request *SdkClientCreateStoreRequest) Body(body ClientCreateStoreRequest) SdkClientCreateStoreRequestInterface { request.body = &body return request } func (request *SdkClientCreateStoreRequest) Execute() (*ClientCreateStoreResponse, error) { return request.Client.CreateStoreExecute(request) } func (request *SdkClientCreateStoreRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientCreateStoreRequest) GetOptions() *ClientCreateStoreOptions { return request.options } func (request *SdkClientCreateStoreRequest) GetBody() *ClientCreateStoreRequest { return request.body } func (client *OpenFgaClient) CreateStoreExecute(request SdkClientCreateStoreRequestInterface) (*ClientCreateStoreResponse, error) { data, _, err := client.OpenFgaApi.CreateStore(request.GetContext()).Body(fgaSdk.CreateStoreRequest{ Name: request.GetBody().Name, }).Execute() if err != nil { return nil, err } return &data, nil } func (client *OpenFgaClient) CreateStore(ctx _context.Context) SdkClientCreateStoreRequestInterface { return &SdkClientCreateStoreRequest{ Client: client, ctx: ctx, } } // / GetStore type SdkClientGetStoreRequest struct { ctx _context.Context Client *OpenFgaClient options *ClientGetStoreOptions } type SdkClientGetStoreRequestInterface interface { Options(options ClientGetStoreOptions) SdkClientGetStoreRequestInterface Execute() (*ClientGetStoreResponse, error) GetContext() _context.Context GetOptions() *ClientGetStoreOptions } type ClientGetStoreOptions struct { } type ClientGetStoreResponse = fgaSdk.GetStoreResponse func (request *SdkClientGetStoreRequest) Options(options ClientGetStoreOptions) SdkClientGetStoreRequestInterface { request.options = &options return request } func (request *SdkClientGetStoreRequest) Execute() (*ClientGetStoreResponse, error) { return request.Client.GetStoreExecute(request) } func (request *SdkClientGetStoreRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientGetStoreRequest) GetOptions() *ClientGetStoreOptions { return request.options } func (client *OpenFgaClient) GetStoreExecute(request SdkClientGetStoreRequestInterface) (*ClientGetStoreResponse, error) { data, _, err := client.OpenFgaApi.GetStore(request.GetContext()).Execute() if err != nil { return nil, err } return &data, nil } func (client *OpenFgaClient) GetStore(ctx _context.Context) SdkClientGetStoreRequestInterface { return &SdkClientGetStoreRequest{ Client: client, ctx: ctx, } } // / DeleteStore type SdkClientDeleteStoreRequest struct { ctx _context.Context Client *OpenFgaClient options *ClientDeleteStoreOptions } type SdkClientDeleteStoreRequestInterface interface { Options(options ClientDeleteStoreOptions) SdkClientDeleteStoreRequestInterface Execute() (*ClientDeleteStoreResponse, error) GetContext() _context.Context GetOptions() *ClientDeleteStoreOptions } type ClientDeleteStoreOptions struct { } type ClientDeleteStoreResponse struct{} func (request *SdkClientDeleteStoreRequest) Options(options ClientDeleteStoreOptions) SdkClientDeleteStoreRequestInterface { request.options = &options return request } func (request *SdkClientDeleteStoreRequest) Execute() (*ClientDeleteStoreResponse, error) { return request.Client.DeleteStoreExecute(request) } func (request *SdkClientDeleteStoreRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientDeleteStoreRequest) GetOptions() *ClientDeleteStoreOptions { return request.options } func (client *OpenFgaClient) DeleteStoreExecute(request SdkClientDeleteStoreRequestInterface) (*ClientDeleteStoreResponse, error) { _, err := client.OpenFgaApi.DeleteStore(request.GetContext()).Execute() if err != nil { return nil, err } return &ClientDeleteStoreResponse{}, nil } func (client *OpenFgaClient) DeleteStore(ctx _context.Context) SdkClientDeleteStoreRequestInterface { return &SdkClientDeleteStoreRequest{ Client: client, ctx: ctx, } } /* Authorization Models */ // / ReadAuthorizationModels type SdkClientReadAuthorizationModelsRequest struct { ctx _context.Context Client *OpenFgaClient options *ClientReadAuthorizationModelsOptions } type SdkClientReadAuthorizationModelsRequestInterface interface { Options(options ClientReadAuthorizationModelsOptions) SdkClientReadAuthorizationModelsRequestInterface Execute() (*ClientReadAuthorizationModelsResponse, error) GetContext() _context.Context GetOptions() *ClientReadAuthorizationModelsOptions } type ClientReadAuthorizationModelsOptions struct { PageSize *int32 `json:"page_size,omitempty"` ContinuationToken *string `json:"continuation_token,omitempty"` } type ClientReadAuthorizationModelsResponse = fgaSdk.ReadAuthorizationModelsResponse func (request *SdkClientReadAuthorizationModelsRequest) Options(options ClientReadAuthorizationModelsOptions) SdkClientReadAuthorizationModelsRequestInterface { request.options = &options return request } func (request *SdkClientReadAuthorizationModelsRequest) Execute() (*ClientReadAuthorizationModelsResponse, error) { return request.Client.ReadAuthorizationModelsExecute(request) } func (request *SdkClientReadAuthorizationModelsRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientReadAuthorizationModelsRequest) GetOptions() *ClientReadAuthorizationModelsOptions { return request.options } func (client *OpenFgaClient) ReadAuthorizationModelsExecute(request SdkClientReadAuthorizationModelsRequestInterface) (*ClientReadAuthorizationModelsResponse, error) { req := client.OpenFgaApi.ReadAuthorizationModels(request.GetContext()) pageSize := getPageSizeFromRequest((*ClientPaginationOptions)(request.GetOptions())) if pageSize != nil { req = req.PageSize(*pageSize) } continuationToken := getContinuationTokenFromRequest((*ClientPaginationOptions)(request.GetOptions())) if continuationToken != nil { req = req.ContinuationToken(*continuationToken) } data, _, err := req.Execute() if err != nil { return nil, err } return &data, nil } func (client *OpenFgaClient) ReadAuthorizationModels(ctx _context.Context) SdkClientReadAuthorizationModelsRequestInterface { return &SdkClientReadAuthorizationModelsRequest{ Client: client, ctx: ctx, } } // / WriteAuthorizationModel type SdkClientWriteAuthorizationModelRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientWriteAuthorizationModelRequest options *ClientWriteAuthorizationModelOptions } type SdkClientWriteAuthorizationModelRequestInterface interface { Options(options ClientWriteAuthorizationModelOptions) SdkClientWriteAuthorizationModelRequestInterface Body(body ClientWriteAuthorizationModelRequest) SdkClientWriteAuthorizationModelRequestInterface Execute() (*ClientWriteAuthorizationModelResponse, error) GetBody() *ClientWriteAuthorizationModelRequest GetOptions() *ClientWriteAuthorizationModelOptions GetContext() _context.Context } type ClientWriteAuthorizationModelRequest = fgaSdk.WriteAuthorizationModelRequest type ClientWriteAuthorizationModelOptions struct { } type ClientWriteAuthorizationModelResponse = fgaSdk.WriteAuthorizationModelResponse func (request *SdkClientWriteAuthorizationModelRequest) Options(options ClientWriteAuthorizationModelOptions) SdkClientWriteAuthorizationModelRequestInterface { request.options = &options return request } func (request *SdkClientWriteAuthorizationModelRequest) Body(body ClientWriteAuthorizationModelRequest) SdkClientWriteAuthorizationModelRequestInterface { request.body = &body return request } func (request *SdkClientWriteAuthorizationModelRequest) Execute() (*ClientWriteAuthorizationModelResponse, error) { return request.Client.WriteAuthorizationModelExecute(request) } func (request *SdkClientWriteAuthorizationModelRequest) GetBody() *ClientWriteAuthorizationModelRequest { return request.body } func (request *SdkClientWriteAuthorizationModelRequest) GetOptions() *ClientWriteAuthorizationModelOptions { return request.options } func (request *SdkClientWriteAuthorizationModelRequest) GetContext() _context.Context { return request.ctx } func (client *OpenFgaClient) WriteAuthorizationModelExecute(request SdkClientWriteAuthorizationModelRequestInterface) (*ClientWriteAuthorizationModelResponse, error) { data, _, err := client.OpenFgaApi.WriteAuthorizationModel(request.GetContext()).Body(*request.GetBody()).Execute() if err != nil { return nil, err } return &data, nil } func (client *OpenFgaClient) WriteAuthorizationModel(ctx _context.Context) SdkClientWriteAuthorizationModelRequestInterface { return &SdkClientWriteAuthorizationModelRequest{ Client: client, ctx: ctx, } } // / ReadAuthorizationModel type SdkClientReadAuthorizationModelRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientReadAuthorizationModelRequest options *ClientReadAuthorizationModelOptions } type SdkClientReadAuthorizationModelRequestInterface interface { Options(options ClientReadAuthorizationModelOptions) SdkClientReadAuthorizationModelRequestInterface Body(body ClientReadAuthorizationModelRequest) SdkClientReadAuthorizationModelRequestInterface Execute() (*ClientReadAuthorizationModelResponse, error) GetAuthorizationModelIdOverride() *string GetContext() _context.Context GetBody() *ClientReadAuthorizationModelRequest GetOptions() *ClientReadAuthorizationModelOptions } type ClientReadAuthorizationModelRequest struct { } type ClientReadAuthorizationModelOptions struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"` } type ClientReadAuthorizationModelResponse = fgaSdk.ReadAuthorizationModelResponse func (request *SdkClientReadAuthorizationModelRequest) Options(options ClientReadAuthorizationModelOptions) SdkClientReadAuthorizationModelRequestInterface { request.options = &options return request } func (request *SdkClientReadAuthorizationModelRequest) GetAuthorizationModelIdOverride() *string { if request.options == nil { return nil } return request.options.AuthorizationModelId } func (request *SdkClientReadAuthorizationModelRequest) Body(body ClientReadAuthorizationModelRequest) SdkClientReadAuthorizationModelRequestInterface { request.body = &body return request } func (request *SdkClientReadAuthorizationModelRequest) Execute() (*ClientReadAuthorizationModelResponse, error) { return request.Client.ReadAuthorizationModelExecute(request) } func (request *SdkClientReadAuthorizationModelRequest) GetBody() *ClientReadAuthorizationModelRequest { return request.body } func (request *SdkClientReadAuthorizationModelRequest) GetOptions() *ClientReadAuthorizationModelOptions { return request.options } func (request *SdkClientReadAuthorizationModelRequest) GetContext() _context.Context { return request.ctx } func (client *OpenFgaClient) ReadAuthorizationModelExecute(request SdkClientReadAuthorizationModelRequestInterface) (*ClientReadAuthorizationModelResponse, error) { authorizationModelId, err := client.getAuthorizationModelId(request.GetAuthorizationModelIdOverride()) if err != nil { return nil, err } if authorizationModelId == nil || *authorizationModelId == "" { return nil, FgaRequiredParamError{param: "AuthorizationModelId"} } data, _, err := client.OpenFgaApi.ReadAuthorizationModel(request.GetContext(), *authorizationModelId).Execute() if err != nil { return nil, err } return &data, nil } func (client *OpenFgaClient) ReadAuthorizationModel(ctx _context.Context) SdkClientReadAuthorizationModelRequestInterface { return &SdkClientReadAuthorizationModelRequest{ Client: client, ctx: ctx, } } // / ReadLatestAuthorizationModel type SdkClientReadLatestAuthorizationModelRequest struct { ctx _context.Context Client OpenFgaClient options *ClientReadLatestAuthorizationModelOptions } type SdkClientReadLatestAuthorizationModelRequestInterface interface { Options(options ClientReadLatestAuthorizationModelOptions) SdkClientReadLatestAuthorizationModelRequestInterface Execute() (*ClientReadAuthorizationModelResponse, error) GetContext() _context.Context GetOptions() *ClientReadLatestAuthorizationModelOptions } type ClientReadLatestAuthorizationModelOptions struct { } func (client *OpenFgaClient) ReadLatestAuthorizationModel(ctx _context.Context) SdkClientReadLatestAuthorizationModelRequestInterface { return &SdkClientReadLatestAuthorizationModelRequest{ Client: *client, ctx: ctx, } } func (request *SdkClientReadLatestAuthorizationModelRequest) Options(options ClientReadLatestAuthorizationModelOptions) SdkClientReadLatestAuthorizationModelRequestInterface { request.options = &options return request } func (request *SdkClientReadLatestAuthorizationModelRequest) Execute() (*ClientReadAuthorizationModelResponse, error) { return request.Client.ReadLatestAuthorizationModelExecute(request) } func (request *SdkClientReadLatestAuthorizationModelRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientReadLatestAuthorizationModelRequest) GetOptions() *ClientReadLatestAuthorizationModelOptions { return request.options } func (client *OpenFgaClient) ReadLatestAuthorizationModelExecute(request SdkClientReadLatestAuthorizationModelRequestInterface) (*ClientReadAuthorizationModelResponse, error) { response, err := client.ReadAuthorizationModels(request.GetContext()).Options(ClientReadAuthorizationModelsOptions{ PageSize: fgaSdk.PtrInt32(1), }).Execute() if err != nil { return nil, err } var authorizationModel *fgaSdk.AuthorizationModel if len(response.AuthorizationModels) > 0 { authorizationModels := response.AuthorizationModels authorizationModel = &(authorizationModels)[0] } return &fgaSdk.ReadAuthorizationModelResponse{ AuthorizationModel: authorizationModel, }, nil } /* Relationship Tuples */ // / ReadChanges type SdkClientReadChangesRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientReadChangesRequest options *ClientReadChangesOptions } type SdkClientReadChangesRequestInterface interface { Options(options ClientReadChangesOptions) SdkClientReadChangesRequestInterface Body(body ClientReadChangesRequest) SdkClientReadChangesRequestInterface Execute() (*ClientReadChangesResponse, error) GetContext() _context.Context GetBody() *ClientReadChangesRequest GetOptions() *ClientReadChangesOptions } type ClientReadChangesRequest struct { Type string `json:"type,omitempty"` } type ClientReadChangesOptions struct { PageSize *int32 `json:"page_size,omitempty"` ContinuationToken *string `json:"continuation_token,omitempty"` } type ClientReadChangesResponse = fgaSdk.ReadChangesResponse func (client *OpenFgaClient) ReadChanges(ctx _context.Context) SdkClientReadChangesRequestInterface { return &SdkClientReadChangesRequest{ Client: client, ctx: ctx, } } func (request *SdkClientReadChangesRequest) Options(options ClientReadChangesOptions) SdkClientReadChangesRequestInterface { request.options = &options return request } func (request *SdkClientReadChangesRequest) Body(body ClientReadChangesRequest) SdkClientReadChangesRequestInterface { request.body = &body return request } func (request *SdkClientReadChangesRequest) Execute() (*ClientReadChangesResponse, error) { return request.Client.ReadChangesExecute(request) } func (request *SdkClientReadChangesRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientReadChangesRequest) GetBody() *ClientReadChangesRequest { return request.body } func (request *SdkClientReadChangesRequest) GetOptions() *ClientReadChangesOptions { return request.options } func (client *OpenFgaClient) ReadChangesExecute(request SdkClientReadChangesRequestInterface) (*ClientReadChangesResponse, error) { req := client.OpenFgaApi.ReadChanges(request.GetContext()) pageSize := getPageSizeFromRequest((*ClientPaginationOptions)(request.GetOptions())) if pageSize != nil { req = req.PageSize(*pageSize) } continuationToken := getContinuationTokenFromRequest((*ClientPaginationOptions)(request.GetOptions())) if continuationToken != nil { req = req.ContinuationToken(*continuationToken) } requestBody := request.GetBody() if requestBody != nil { req = req.Type_(requestBody.Type) } data, _, err := req.Execute() if err != nil { return nil, err } return &data, nil } // / Read type SdkClientReadRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientReadRequest options *ClientReadOptions } type SdkClientReadRequestInterface interface { Options(options ClientReadOptions) SdkClientReadRequestInterface Body(body ClientReadRequest) SdkClientReadRequestInterface Execute() (*ClientReadResponse, error) GetContext() _context.Context GetBody() *ClientReadRequest GetOptions() *ClientReadOptions } type ClientReadRequest struct { User *string `json:"user,omitempty"` Relation *string `json:"relation,omitempty"` Object *string `json:"object,omitempty"` } type ClientReadOptions struct { PageSize *int32 `json:"page_size,omitempty"` ContinuationToken *string `json:"continuation_token,omitempty"` } type ClientReadResponse = fgaSdk.ReadResponse func (client *OpenFgaClient) Read(ctx _context.Context) SdkClientReadRequestInterface { return &SdkClientReadRequest{ Client: client, ctx: ctx, } } func (request *SdkClientReadRequest) Options(options ClientReadOptions) SdkClientReadRequestInterface { request.options = &options return request } func (request *SdkClientReadRequest) Body(body ClientReadRequest) SdkClientReadRequestInterface { request.body = &body return request } func (request *SdkClientReadRequest) Execute() (*ClientReadResponse, error) { return request.Client.ReadExecute(request) } func (request *SdkClientReadRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientReadRequest) GetBody() *ClientReadRequest { return request.body } func (request *SdkClientReadRequest) GetOptions() *ClientReadOptions { return request.options } func (client *OpenFgaClient) ReadExecute(request SdkClientReadRequestInterface) (*ClientReadResponse, error) { body := fgaSdk.ReadRequest{ PageSize: getPageSizeFromRequest((*ClientPaginationOptions)(request.GetOptions())), ContinuationToken: getContinuationTokenFromRequest((*ClientPaginationOptions)(request.GetOptions())), } if request.GetBody() != nil && (request.GetBody().User != nil || request.GetBody().Relation != nil || request.GetBody().Object != nil) { body.TupleKey = &fgaSdk.ReadRequestTupleKey{ User: request.GetBody().User, Relation: request.GetBody().Relation, Object: request.GetBody().Object, } } data, _, err := client.OpenFgaApi.Read(request.GetContext()).Body(body).Execute() if err != nil { return nil, err } return &data, nil } // / Write type SdkClientWriteRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientWriteRequest options *ClientWriteOptions } type SdkClientWriteRequestInterface interface { Options(options ClientWriteOptions) SdkClientWriteRequestInterface Body(body ClientWriteRequest) SdkClientWriteRequestInterface Execute() (*ClientWriteResponse, error) GetAuthorizationModelIdOverride() *string GetContext() _context.Context GetOptions() *ClientWriteOptions GetBody() *ClientWriteRequest } type ClientWriteRequest struct { Writes []ClientTupleKey Deletes []ClientTupleKeyWithoutCondition } type TransactionOptions struct { // If set to true will disable running in transaction mode (transaction mode means everything is sent in a single transaction to the server) Disable bool `json:"disable,omitempty"` // When transaction mode is disabled, the requests are chunked and sent separately and each chunk is a transaction (default = 1) MaxPerChunk int32 `json:"max_per_chunk,omitempty"` // Number of requests to issue in parallel MaxParallelRequests int32 `json:"max_parallel_requests,omitempty"` } type ClientWriteOptions struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"` Transaction *TransactionOptions `json:"transaction_options,omitempty"` } type ClientWriteStatus string // List of ClientWriteStatus const ( SUCCESS ClientWriteStatus = "CLIENT_WRITE_STATUS_SUCCESS" FAILURE ClientWriteStatus = "CLIENT_WRITE_STATUS_FAILURE" ) type ClientWriteRequestWriteResponse struct { TupleKey ClientTupleKey `json:"tuple_key,omitempty"` Status ClientWriteStatus `json:"status,omitempty"` HttpResponse *_nethttp.Response `json:"http_response,omitempty"` Error error `json:"error,omitempty"` } func (o ClientWriteRequestWriteResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tuple_key"] = o.TupleKey toSerialize["status"] = o.Status if o.HttpResponse != nil { toSerialize["http_response"] = o.HttpResponse } if o.Error != nil { toSerialize["error"] = o.Error } return json.Marshal(toSerialize) } type ClientWriteRequestDeleteResponse struct { TupleKey ClientTupleKeyWithoutCondition `json:"tuple_key,omitempty"` Status ClientWriteStatus `json:"status,omitempty"` HttpResponse *_nethttp.Response `json:"http_response,omitempty"` Error error `json:"error,omitempty"` } func (o ClientWriteRequestDeleteResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tuple_key"] = o.TupleKey toSerialize["status"] = o.Status if o.HttpResponse != nil { toSerialize["http_response"] = o.HttpResponse } if o.Error != nil { toSerialize["error"] = o.Error } return json.Marshal(toSerialize) } type ClientWriteResponse struct { Writes []ClientWriteRequestWriteResponse `json:"writes,omitempty"` Deletes []ClientWriteRequestDeleteResponse `json:"deletes,omitempty"` } func (o ClientWriteResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Writes != nil { toSerialize["writes"] = o.Writes } if o.Deletes != nil { toSerialize["deletes"] = o.Deletes } return json.Marshal(toSerialize) } func (client *OpenFgaClient) Write(ctx _context.Context) SdkClientWriteRequestInterface { return &SdkClientWriteRequest{ Client: client, ctx: ctx, } } func (request *SdkClientWriteRequest) Options(options ClientWriteOptions) SdkClientWriteRequestInterface { request.options = &options return request } func (request *SdkClientWriteRequest) GetAuthorizationModelIdOverride() *string { if request.options == nil { return nil } return request.options.AuthorizationModelId } func (request *SdkClientWriteRequest) Body(body ClientWriteRequest) SdkClientWriteRequestInterface { request.body = &body return request } func (request *SdkClientWriteRequest) Execute() (*ClientWriteResponse, error) { return request.Client.WriteExecute(request) } func (request *SdkClientWriteRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientWriteRequest) GetOptions() *ClientWriteOptions { return request.options } func (request *SdkClientWriteRequest) GetBody() *ClientWriteRequest { return request.body } func (client *OpenFgaClient) WriteExecute(request SdkClientWriteRequestInterface) (*ClientWriteResponse, error) { var maxPerChunk = int32(1) // 1 has to be the default otherwise the chunks will be sent in transactions if request.GetOptions() != nil && request.GetOptions().Transaction != nil { maxPerChunk = request.GetOptions().Transaction.MaxPerChunk } var maxParallelReqs = DEFAULT_MAX_METHOD_PARALLEL_REQS if request.GetOptions() != nil && request.GetOptions().Transaction != nil { maxParallelReqs = request.GetOptions().Transaction.MaxParallelRequests } response := ClientWriteResponse{ Writes: []ClientWriteRequestWriteResponse{}, Deletes: []ClientWriteRequestDeleteResponse{}, } authorizationModelId, err := client.getAuthorizationModelId(request.GetAuthorizationModelIdOverride()) if err != nil { return nil, err } // Unless explicitly disabled, transaction mode is enabled // In transaction mode, the client will send the request to the server as is if request.GetOptions() == nil || request.GetOptions().Transaction == nil || !request.GetOptions().Transaction.Disable { writeRequest := fgaSdk.WriteRequest{ AuthorizationModelId: authorizationModelId, } if request.GetBody().Writes != nil && len(request.GetBody().Writes) > 0 { writes := fgaSdk.WriteRequestWrites{} for index := 0; index < len(request.GetBody().Writes); index++ { writes.TupleKeys = append(writes.TupleKeys, (request.GetBody().Writes)[index]) } writeRequest.Writes = &writes } if request.GetBody().Deletes != nil && len(request.GetBody().Deletes) > 0 { deletes := fgaSdk.WriteRequestDeletes{} for index := 0; index < len(request.GetBody().Deletes); index++ { deletes.TupleKeys = append(deletes.TupleKeys, (request.GetBody().Deletes)[index]) } writeRequest.Deletes = &deletes } _, httpResponse, err := client.OpenFgaApi.Write(request.GetContext()).Body(writeRequest).Execute() clientWriteStatus := SUCCESS if err != nil { clientWriteStatus = FAILURE } if request.GetBody() != nil && request.GetBody().Writes != nil { writeRequestTupleKeys := request.GetBody().Writes for index := 0; index < len(writeRequestTupleKeys); index++ { response.Writes = append(response.Writes, ClientWriteRequestWriteResponse{ TupleKey: writeRequestTupleKeys[index], HttpResponse: httpResponse, Status: clientWriteStatus, Error: err, }) } } if request.GetBody() != nil && request.GetBody().Deletes != nil { deleteRequestTupleKeys := request.GetBody().Deletes for index := 0; index < len(deleteRequestTupleKeys); index++ { response.Deletes = append(response.Deletes, ClientWriteRequestDeleteResponse{ TupleKey: deleteRequestTupleKeys[index], HttpResponse: httpResponse, Status: clientWriteStatus, Error: err, }) } } return &response, err } // If the transaction mode is disabled: // - the client will attempt to chunk the writes and deletes into multiple requests // - each request is a transaction // - the max items in each request are based on maxPerChunk (default=1) var writeChunkSize = int(maxPerChunk) var writeChunks [][]ClientTupleKey if request.GetBody() != nil { for i := 0; i < len(request.GetBody().Writes); i += writeChunkSize { end := int(math.Min(float64(i+writeChunkSize), float64(len(request.GetBody().Writes)))) writeChunks = append(writeChunks, (request.GetBody().Writes)[i:end]) } } writeGroup, ctx := errgroup.WithContext(request.GetContext()) err = client.checkValidApiConnection(ctx, authorizationModelId) if err != nil { return nil, err } writeGroup.SetLimit(int(maxParallelReqs)) writeResponses := make([]ClientWriteResponse, len(writeChunks)) for index, writeBody := range writeChunks { index, writeBody := index, writeBody writeGroup.Go(func() error { singleResponse, _ := client.WriteExecute(&SdkClientWriteRequest{ ctx: ctx, Client: client, body: &ClientWriteRequest{ Writes: writeBody, }, options: &ClientWriteOptions{ AuthorizationModelId: authorizationModelId, }, }) writeResponses[index] = *singleResponse return nil }) } _ = writeGroup.Wait() var deleteChunkSize = int(maxPerChunk) var deleteChunks [][]ClientTupleKeyWithoutCondition if request.GetBody() != nil { for i := 0; i < len(request.GetBody().Deletes); i += deleteChunkSize { end := int(math.Min(float64(i+writeChunkSize), float64(len(request.GetBody().Deletes)))) deleteChunks = append(deleteChunks, (request.GetBody().Deletes)[i:end]) } } deleteGroup, ctx := errgroup.WithContext(request.GetContext()) deleteGroup.SetLimit(int(maxParallelReqs)) deleteResponses := make([]ClientWriteResponse, len(deleteChunks)) for index, deleteBody := range deleteChunks { index, deleteBody := index, deleteBody deleteGroup.Go(func() error { singleResponse, _ := client.WriteExecute(&SdkClientWriteRequest{ ctx: ctx, Client: client, body: &ClientWriteRequest{ Deletes: deleteBody, }, options: &ClientWriteOptions{ AuthorizationModelId: authorizationModelId, }, }) deleteResponses[index] = *singleResponse return nil }) } _ = deleteGroup.Wait() for _, writeResponse := range writeResponses { for _, writeSingleResponse := range writeResponse.Writes { response.Writes = append(response.Writes, writeSingleResponse) } } for _, deleteResponse := range deleteResponses { for _, deleteSingleResponse := range deleteResponse.Deletes { response.Deletes = append(response.Deletes, deleteSingleResponse) } } return &response, nil } // / WriteTuples type SdkClientWriteTuplesRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientWriteTuplesBody options *ClientWriteOptions } type SdkClientWriteTuplesRequestInterface interface { Options(options ClientWriteOptions) SdkClientWriteTuplesRequestInterface Body(body ClientWriteTuplesBody) SdkClientWriteTuplesRequestInterface Execute() (*ClientWriteResponse, error) GetContext() _context.Context GetBody() *ClientWriteTuplesBody GetOptions() *ClientWriteOptions } type ClientWriteTuplesBody = []ClientTupleKey func (client *OpenFgaClient) WriteTuples(ctx _context.Context) SdkClientWriteTuplesRequestInterface { return &SdkClientWriteTuplesRequest{ Client: client, ctx: ctx, } } func (request *SdkClientWriteTuplesRequest) Options(options ClientWriteOptions) SdkClientWriteTuplesRequestInterface { request.options = &options return request } func (request *SdkClientWriteTuplesRequest) Body(body ClientWriteTuplesBody) SdkClientWriteTuplesRequestInterface { request.body = &body return request } func (request *SdkClientWriteTuplesRequest) Execute() (*ClientWriteResponse, error) { return request.Client.WriteTuplesExecute(request) } func (request *SdkClientWriteTuplesRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientWriteTuplesRequest) GetBody() *ClientWriteTuplesBody { return request.body } func (request *SdkClientWriteTuplesRequest) GetOptions() *ClientWriteOptions { return request.options } func (client *OpenFgaClient) WriteTuplesExecute(request SdkClientWriteTuplesRequestInterface) (*ClientWriteResponse, error) { baseReq := client.Write(request.GetContext()).Body(ClientWriteRequest{ Writes: *request.GetBody(), }) if request.GetOptions() != nil { baseReq = baseReq.Options(*request.GetOptions()) } return baseReq.Execute() } // / DeleteTuples type SdkClientDeleteTuplesRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientDeleteTuplesBody options *ClientWriteOptions } type SdkClientDeleteTuplesRequestInterface interface { Options(options ClientWriteOptions) SdkClientDeleteTuplesRequestInterface Body(body ClientDeleteTuplesBody) SdkClientDeleteTuplesRequestInterface Execute() (*ClientWriteResponse, error) GetContext() _context.Context GetBody() *ClientDeleteTuplesBody GetOptions() *ClientWriteOptions } type ClientDeleteTuplesBody = []ClientTupleKeyWithoutCondition func (client *OpenFgaClient) DeleteTuples(ctx _context.Context) SdkClientDeleteTuplesRequestInterface { return &SdkClientDeleteTuplesRequest{ Client: client, ctx: ctx, } } func (request *SdkClientDeleteTuplesRequest) Options(options ClientWriteOptions) SdkClientDeleteTuplesRequestInterface { request.options = &options return request } func (request *SdkClientDeleteTuplesRequest) Body(body ClientDeleteTuplesBody) SdkClientDeleteTuplesRequestInterface { request.body = &body return request } func (request *SdkClientDeleteTuplesRequest) Execute() (*ClientWriteResponse, error) { return request.Client.DeleteTuplesExecute(request) } func (request *SdkClientDeleteTuplesRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientDeleteTuplesRequest) GetBody() *ClientDeleteTuplesBody { return request.body } func (request *SdkClientDeleteTuplesRequest) GetOptions() *ClientWriteOptions { return request.options } func (client *OpenFgaClient) DeleteTuplesExecute(request SdkClientDeleteTuplesRequestInterface) (*ClientWriteResponse, error) { baseReq := client.Write(request.GetContext()).Body(ClientWriteRequest{ Deletes: *request.GetBody(), }) if request.GetOptions() != nil { baseReq = baseReq.Options(*request.GetOptions()) } return baseReq.Execute() } /* Relationship Queries */ /// Check type SdkClientCheckRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientCheckRequest options *ClientCheckOptions } type SdkClientCheckRequestInterface interface { Options(options ClientCheckOptions) SdkClientCheckRequestInterface Body(body ClientCheckRequest) SdkClientCheckRequestInterface Execute() (*ClientCheckResponse, error) GetAuthorizationModelIdOverride() *string GetContext() _context.Context GetBody() *ClientCheckRequest GetOptions() *ClientCheckOptions } type ClientCheckRequest struct { User string `json:"user,omitempty"` Relation string `json:"relation,omitempty"` Object string `json:"object,omitempty"` Context *map[string]interface{} `json:"context,omitempty"` ContextualTuples []ClientContextualTupleKey `json:"contextual_tuples,omitempty"` } type ClientCheckOptions struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"` } type ClientCheckResponse struct { fgaSdk.CheckResponse HttpResponse *_nethttp.Response } func (client *OpenFgaClient) Check(ctx _context.Context) SdkClientCheckRequestInterface { return &SdkClientCheckRequest{ Client: client, ctx: ctx, } } func (request *SdkClientCheckRequest) Options(options ClientCheckOptions) SdkClientCheckRequestInterface { request.options = &options return request } func (request *SdkClientCheckRequest) GetAuthorizationModelIdOverride() *string { if request.options == nil { return nil } return request.options.AuthorizationModelId } func (request *SdkClientCheckRequest) Body(body ClientCheckRequest) SdkClientCheckRequestInterface { request.body = &body return request } func (request *SdkClientCheckRequest) Execute() (*ClientCheckResponse, error) { return request.Client.CheckExecute(request) } func (request *SdkClientCheckRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientCheckRequest) GetBody() *ClientCheckRequest { return request.body } func (request *SdkClientCheckRequest) GetOptions() *ClientCheckOptions { return request.options } func (client *OpenFgaClient) CheckExecute(request SdkClientCheckRequestInterface) (*ClientCheckResponse, error) { var contextualTuples []ClientContextualTupleKey if request.GetBody().ContextualTuples != nil { for index := 0; index < len(request.GetBody().ContextualTuples); index++ { contextualTuples = append(contextualTuples, (request.GetBody().ContextualTuples)[index]) } } authorizationModelId, err := client.getAuthorizationModelId(request.GetAuthorizationModelIdOverride()) if err != nil { return nil, err } requestBody := fgaSdk.CheckRequest{ TupleKey: fgaSdk.CheckRequestTupleKey{ User: request.GetBody().User, Relation: request.GetBody().Relation, Object: request.GetBody().Object, }, Context: request.GetBody().Context, ContextualTuples: fgaSdk.NewContextualTupleKeys(contextualTuples), AuthorizationModelId: authorizationModelId, } data, httpResponse, err := client.OpenFgaApi.Check(request.GetContext()).Body(requestBody).Execute() return &ClientCheckResponse{CheckResponse: data, HttpResponse: httpResponse}, err } /// BatchCheck type SdkClientBatchCheckRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientBatchCheckBody options *ClientBatchCheckOptions } type SdkClientBatchCheckRequestInterface interface { Options(options ClientBatchCheckOptions) SdkClientBatchCheckRequestInterface Body(body ClientBatchCheckBody) SdkClientBatchCheckRequestInterface Execute() (*ClientBatchCheckResponse, error) GetAuthorizationModelIdOverride() *string GetContext() _context.Context GetBody() *ClientBatchCheckBody GetOptions() *ClientBatchCheckOptions } type ClientBatchCheckBody = []ClientCheckRequest type ClientBatchCheckOptions struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"` MaxParallelRequests *int32 `json:"max_parallel_requests,omitempty"` } type ClientBatchCheckSingleResponse struct { ClientCheckResponse Request ClientCheckRequest Error error } type ClientBatchCheckResponse = []ClientBatchCheckSingleResponse func (client *OpenFgaClient) BatchCheck(ctx _context.Context) SdkClientBatchCheckRequestInterface { return &SdkClientBatchCheckRequest{ Client: client, ctx: ctx, } } func (request *SdkClientBatchCheckRequest) Options(options ClientBatchCheckOptions) SdkClientBatchCheckRequestInterface { request.options = &options return request } func (request *SdkClientBatchCheckRequest) GetAuthorizationModelIdOverride() *string { if request.options == nil { return nil } return request.options.AuthorizationModelId } func (request *SdkClientBatchCheckRequest) Body(body ClientBatchCheckBody) SdkClientBatchCheckRequestInterface { request.body = &body return request } func (request *SdkClientBatchCheckRequest) Execute() (*ClientBatchCheckResponse, error) { return request.Client.BatchCheckExecute(request) } func (request *SdkClientBatchCheckRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientBatchCheckRequest) GetBody() *ClientBatchCheckBody { return request.body } func (request *SdkClientBatchCheckRequest) GetOptions() *ClientBatchCheckOptions { return request.options } func (client *OpenFgaClient) BatchCheckExecute(request SdkClientBatchCheckRequestInterface) (*ClientBatchCheckResponse, error) { group, ctx := errgroup.WithContext(request.GetContext()) var maxParallelReqs int if request.GetOptions() == nil || request.GetOptions().MaxParallelRequests == nil { maxParallelReqs = int(DEFAULT_MAX_METHOD_PARALLEL_REQS) } else { maxParallelReqs = int(*request.GetOptions().MaxParallelRequests) } group.SetLimit(maxParallelReqs) var numOfChecks = len(*request.GetBody()) response := make(ClientBatchCheckResponse, numOfChecks) authorizationModelId, err := client.getAuthorizationModelId(request.GetAuthorizationModelIdOverride()) if err != nil { return nil, err } group.Go(func() error { // if the connection is probelmatic, we will return error to the overall // response rather than individual response return client.checkValidApiConnection(ctx, authorizationModelId) }) for index, checkBody := range *request.GetBody() { index, checkBody := index, checkBody group.Go(func() error { singleResponse, err := client.CheckExecute(&SdkClientCheckRequest{ ctx: ctx, Client: client, body: &checkBody, options: &ClientCheckOptions{ AuthorizationModelId: authorizationModelId, }, }) response[index] = ClientBatchCheckSingleResponse{ Request: checkBody, ClientCheckResponse: *singleResponse, Error: err, } return nil }) } if err := group.Wait(); err != nil { return nil, err } return &response, nil } // / Expand type SdkClientExpandRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientExpandRequest options *ClientExpandOptions } type SdkClientExpandRequestInterface interface { Options(options ClientExpandOptions) SdkClientExpandRequestInterface Body(body ClientExpandRequest) SdkClientExpandRequestInterface Execute() (*ClientExpandResponse, error) GetAuthorizationModelIdOverride() *string GetContext() _context.Context GetBody() *ClientExpandRequest GetOptions() *ClientExpandOptions } type ClientExpandRequest struct { Relation string `json:"relation,omitempty"` Object string `json:"object,omitempty"` } type ClientExpandOptions struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"` } type ClientExpandResponse = fgaSdk.ExpandResponse func (client *OpenFgaClient) Expand(ctx _context.Context) SdkClientExpandRequestInterface { return &SdkClientExpandRequest{ Client: client, ctx: ctx, } } func (request *SdkClientExpandRequest) Options(options ClientExpandOptions) SdkClientExpandRequestInterface { request.options = &options return request } func (request *SdkClientExpandRequest) GetAuthorizationModelIdOverride() *string { if request.options == nil { return nil } return request.options.AuthorizationModelId } func (request *SdkClientExpandRequest) Body(body ClientExpandRequest) SdkClientExpandRequestInterface { request.body = &body return request } func (request *SdkClientExpandRequest) Execute() (*ClientExpandResponse, error) { return request.Client.ExpandExecute(request) } func (request *SdkClientExpandRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientExpandRequest) GetBody() *ClientExpandRequest { return request.body } func (request *SdkClientExpandRequest) GetOptions() *ClientExpandOptions { return request.options } func (client *OpenFgaClient) ExpandExecute(request SdkClientExpandRequestInterface) (*ClientExpandResponse, error) { authorizationModelId, err := client.getAuthorizationModelId(request.GetAuthorizationModelIdOverride()) if err != nil { return nil, err } data, _, err := client.OpenFgaApi.Expand(request.GetContext()).Body(fgaSdk.ExpandRequest{ TupleKey: fgaSdk.ExpandRequestTupleKey{ Relation: request.GetBody().Relation, Object: request.GetBody().Object, }, AuthorizationModelId: authorizationModelId, }).Execute() if err != nil { return nil, err } return &data, nil } // / ListObjects type SdkClientListObjectsRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientListObjectsRequest options *ClientListObjectsOptions } type SdkClientListObjectsRequestInterface interface { Options(options ClientListObjectsOptions) SdkClientListObjectsRequestInterface Body(body ClientListObjectsRequest) SdkClientListObjectsRequestInterface Execute() (*ClientListObjectsResponse, error) GetAuthorizationModelIdOverride() *string GetContext() _context.Context GetBody() *ClientListObjectsRequest GetOptions() *ClientListObjectsOptions } type ClientListObjectsRequest struct { User string `json:"user,omitempty"` Relation string `json:"relation,omitempty"` Type string `json:"type,omitempty"` Context *map[string]interface{} `json:"context,omitempty"` ContextualTuples []ClientContextualTupleKey `json:"contextual_tuples,omitempty"` } type ClientListObjectsOptions struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"` } type ClientListObjectsResponse = fgaSdk.ListObjectsResponse func (client *OpenFgaClient) ListObjects(ctx _context.Context) SdkClientListObjectsRequestInterface { return &SdkClientListObjectsRequest{ Client: client, ctx: ctx, } } func (request *SdkClientListObjectsRequest) Options(options ClientListObjectsOptions) SdkClientListObjectsRequestInterface { request.options = &options return request } func (request *SdkClientListObjectsRequest) GetAuthorizationModelIdOverride() *string { if request.options == nil { return nil } return request.options.AuthorizationModelId } func (request *SdkClientListObjectsRequest) Body(body ClientListObjectsRequest) SdkClientListObjectsRequestInterface { request.body = &body return request } func (request *SdkClientListObjectsRequest) Execute() (*ClientListObjectsResponse, error) { return request.Client.ListObjectsExecute(request) } func (request *SdkClientListObjectsRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientListObjectsRequest) GetBody() *ClientListObjectsRequest { return request.body } func (request *SdkClientListObjectsRequest) GetOptions() *ClientListObjectsOptions { return request.options } func (client *OpenFgaClient) ListObjectsExecute(request SdkClientListObjectsRequestInterface) (*ClientListObjectsResponse, error) { var contextualTuples []ClientContextualTupleKey if request.GetBody().ContextualTuples != nil { for index := 0; index < len(request.GetBody().ContextualTuples); index++ { contextualTuples = append(contextualTuples, (request.GetBody().ContextualTuples)[index]) } } authorizationModelId, err := client.getAuthorizationModelId(request.GetAuthorizationModelIdOverride()) if err != nil { return nil, err } data, _, err := client.OpenFgaApi.ListObjects(request.GetContext()).Body(fgaSdk.ListObjectsRequest{ User: request.GetBody().User, Relation: request.GetBody().Relation, Type: request.GetBody().Type, ContextualTuples: fgaSdk.NewContextualTupleKeys(contextualTuples), Context: request.GetBody().Context, AuthorizationModelId: authorizationModelId, }).Execute() if err != nil { return nil, err } return &data, nil } /// ListRelations type SdkClientListRelationsRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientListRelationsRequest options *ClientListRelationsOptions } type SdkClientListRelationsRequestInterface interface { Options(options ClientListRelationsOptions) SdkClientListRelationsRequestInterface Body(body ClientListRelationsRequest) SdkClientListRelationsRequestInterface Execute() (*ClientListRelationsResponse, error) GetAuthorizationModelIdOverride() *string GetContext() _context.Context GetBody() *ClientListRelationsRequest GetOptions() *ClientListRelationsOptions } type ClientListRelationsRequest struct { User string `json:"user,omitempty"` Object string `json:"object,omitempty"` Relations []string `json:"relations,omitempty"` Context *map[string]interface{} `json:"context,omitempty"` ContextualTuples []ClientContextualTupleKey `json:"contextual_tuples,omitempty"` } type ClientListRelationsOptions struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"` } type ClientListRelationsResponse struct { Relations []string `json:"response,omitempty"` } func (o ClientListRelationsResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["relations"] = o.Relations return json.Marshal(toSerialize) } func (client *OpenFgaClient) ListRelations(ctx _context.Context) SdkClientListRelationsRequestInterface { return &SdkClientListRelationsRequest{ Client: client, ctx: ctx, } } func (request *SdkClientListRelationsRequest) Options(options ClientListRelationsOptions) SdkClientListRelationsRequestInterface { request.options = &options return request } func (request *SdkClientListRelationsRequest) GetAuthorizationModelIdOverride() *string { if request.options == nil { return nil } return request.options.AuthorizationModelId } func (request *SdkClientListRelationsRequest) Body(body ClientListRelationsRequest) SdkClientListRelationsRequestInterface { request.body = &body return request } func (request *SdkClientListRelationsRequest) Execute() (*ClientListRelationsResponse, error) { return request.Client.ListRelationsExecute(request) } func (request *SdkClientListRelationsRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientListRelationsRequest) GetBody() *ClientListRelationsRequest { return request.body } func (request *SdkClientListRelationsRequest) GetOptions() *ClientListRelationsOptions { return request.options } func (client *OpenFgaClient) ListRelationsExecute(request SdkClientListRelationsRequestInterface) (*ClientListRelationsResponse, error) { if len(request.GetBody().Relations) <= 0 { return nil, fmt.Errorf("ListRelations - expected len(Relations) > 0") } batchRequestBody := ClientBatchCheckBody{} for index := 0; index < len(request.GetBody().Relations); index++ { batchRequestBody = append(batchRequestBody, ClientCheckRequest{ User: request.GetBody().User, Relation: request.GetBody().Relations[index], Object: request.GetBody().Object, Context: request.GetBody().Context, ContextualTuples: request.GetBody().ContextualTuples, }) } authorizationModelId, err := client.getAuthorizationModelId(request.GetAuthorizationModelIdOverride()) if err != nil { return nil, err } batchResponse, err := client.BatchCheckExecute(&SdkClientBatchCheckRequest{ ctx: request.GetContext(), Client: client, body: &batchRequestBody, options: &ClientBatchCheckOptions{ AuthorizationModelId: authorizationModelId, }, }) if err != nil { return nil, err } var relations []string for index := 0; index < len(*batchResponse); index++ { if (*batchResponse)[index].GetAllowed() { relations = append(relations, (*batchResponse)[index].Request.Relation) } } return &ClientListRelationsResponse{Relations: relations}, nil } // / ReadAssertions type SdkClientReadAssertionsRequest struct { ctx _context.Context Client *OpenFgaClient options *ClientReadAssertionsOptions } type SdkClientReadAssertionsRequestInterface interface { Options(options ClientReadAssertionsOptions) SdkClientReadAssertionsRequestInterface Execute() (*ClientReadAssertionsResponse, error) GetAuthorizationModelIdOverride() *string GetContext() _context.Context GetOptions() *ClientReadAssertionsOptions } type ClientReadAssertionsOptions struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"` } type ClientReadAssertionsResponse = fgaSdk.ReadAssertionsResponse func (client *OpenFgaClient) ReadAssertions(ctx _context.Context) SdkClientReadAssertionsRequestInterface { return &SdkClientReadAssertionsRequest{ Client: client, ctx: ctx, } } func (request *SdkClientReadAssertionsRequest) Options(options ClientReadAssertionsOptions) SdkClientReadAssertionsRequestInterface { request.options = &options return request } func (request *SdkClientReadAssertionsRequest) GetAuthorizationModelIdOverride() *string { if request.options == nil { return nil } return request.options.AuthorizationModelId } func (request *SdkClientReadAssertionsRequest) Execute() (*ClientReadAssertionsResponse, error) { return request.Client.ReadAssertionsExecute(request) } func (request *SdkClientReadAssertionsRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientReadAssertionsRequest) GetOptions() *ClientReadAssertionsOptions { return request.options } func (client *OpenFgaClient) ReadAssertionsExecute(request SdkClientReadAssertionsRequestInterface) (*ClientReadAssertionsResponse, error) { authorizationModelId, err := client.getAuthorizationModelId(request.GetAuthorizationModelIdOverride()) if err != nil { return nil, err } if authorizationModelId == nil || *authorizationModelId == "" { return nil, FgaRequiredParamError{param: "AuthorizationModelId"} } data, _, err := client.OpenFgaApi.ReadAssertions(request.GetContext(), *authorizationModelId).Execute() if err != nil { return nil, err } return &data, nil } // / WriteAssertions type SdkClientWriteAssertionsRequest struct { ctx _context.Context Client *OpenFgaClient body *ClientWriteAssertionsRequest options *ClientWriteAssertionsOptions } type SdkClientWriteAssertionsRequestInterface interface { Options(options ClientWriteAssertionsOptions) SdkClientWriteAssertionsRequestInterface Body(body ClientWriteAssertionsRequest) SdkClientWriteAssertionsRequestInterface Execute() (*ClientWriteAssertionsResponse, error) GetAuthorizationModelIdOverride() *string GetContext() _context.Context GetBody() *ClientWriteAssertionsRequest GetOptions() *ClientWriteAssertionsOptions } type ClientAssertion struct { User string `json:"user,omitempty"` Relation string `json:"relation,omitempty"` Object string `json:"object,omitempty"` Expectation bool `json:"expectation,omitempty"` } type ClientWriteAssertionsRequest = []ClientAssertion func (clientAssertion ClientAssertion) ToAssertion() fgaSdk.Assertion { return fgaSdk.Assertion{ TupleKey: fgaSdk.AssertionTupleKey{ User: clientAssertion.User, Relation: clientAssertion.Relation, Object: clientAssertion.Object, }, Expectation: clientAssertion.Expectation, } } type ClientWriteAssertionsOptions struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"` } type ClientWriteAssertionsResponse struct { } func (client *OpenFgaClient) WriteAssertions(ctx _context.Context) SdkClientWriteAssertionsRequestInterface { return &SdkClientWriteAssertionsRequest{ Client: client, ctx: ctx, } } func (request *SdkClientWriteAssertionsRequest) Options(options ClientWriteAssertionsOptions) SdkClientWriteAssertionsRequestInterface { request.options = &options return request } func (request *SdkClientWriteAssertionsRequest) GetAuthorizationModelIdOverride() *string { if request.options == nil { return nil } return request.options.AuthorizationModelId } func (request *SdkClientWriteAssertionsRequest) Body(body ClientWriteAssertionsRequest) SdkClientWriteAssertionsRequestInterface { request.body = &body return request } func (request *SdkClientWriteAssertionsRequest) Execute() (*ClientWriteAssertionsResponse, error) { return request.Client.WriteAssertionsExecute(request) } func (request *SdkClientWriteAssertionsRequest) GetContext() _context.Context { return request.ctx } func (request *SdkClientWriteAssertionsRequest) GetBody() *ClientWriteAssertionsRequest { return request.body } func (request *SdkClientWriteAssertionsRequest) GetOptions() *ClientWriteAssertionsOptions { return request.options } func (client *OpenFgaClient) WriteAssertionsExecute(request SdkClientWriteAssertionsRequestInterface) (*ClientWriteAssertionsResponse, error) { writeAssertionsRequest := fgaSdk.WriteAssertionsRequest{} authorizationModelId, err := client.getAuthorizationModelId(request.GetAuthorizationModelIdOverride()) if err != nil { return nil, err } if authorizationModelId == nil || *authorizationModelId == "" { return nil, FgaRequiredParamError{param: "AuthorizationModelId"} } for index := 0; index < len(*request.GetBody()); index++ { clientAssertion := (*request.GetBody())[index] writeAssertionsRequest.Assertions = append(writeAssertionsRequest.Assertions, clientAssertion.ToAssertion()) } _, err = client.OpenFgaApi.WriteAssertions(request.GetContext(), *authorizationModelId).Body(writeAssertionsRequest).Execute() if err != nil { return nil, err } return &ClientWriteAssertionsResponse{}, nil } golang-github-openfga-go-sdk-0.3.5/client/client_test.go000066400000000000000000002020271456721040100231720ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package client_test import ( "context" "encoding/json" "fmt" "net/http" "testing" "github.com/jarcoal/httpmock" "github.com/openfga/go-sdk" . "github.com/openfga/go-sdk/client" ) type TestDefinition struct { Name string JsonResponse string ResponseStatus int Method string RequestPath string } func TestOpenFgaClient(t *testing.T) { fgaClient, err := NewSdkClient(&ClientConfiguration{ ApiUrl: "https://api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", }) if err != nil { t.Fatalf("%v", err) } t.Run("Allow client to have no store ID specified", func(t *testing.T) { _, err := NewSdkClient(&ClientConfiguration{ ApiHost: "api.fga.example", }) if err != nil { t.Fatalf("Expect no error when store id is not specified but got %v", err) } }) t.Run("Allow client to have ApiUrl specified", func(t *testing.T) { _, err := NewSdkClient(&ClientConfiguration{ ApiUrl: "https://api.fga.example", }) if err != nil { t.Fatalf("Expect no error when api url is specified but got %v", err) } }) t.Run("Ensure that ApiUrl is well formed", func(t *testing.T) { urls := []string{ "api.fga.example", "https//api.fga.example", "https://api.fga.example:notavalidport", "https://https://api.fga.example", "notavalidscheme://api.fga.example", } for _, uri := range urls { _, err := NewSdkClient(&ClientConfiguration{ ApiUrl: uri, }) if err == nil { t.Fatalf("Expected an error for invalid uri (%s) but got nil", uri) } expectedErrorString := fmt.Sprintf("Configuration.ApiUrl (%s) does not form a valid uri", uri) if err.Error() != expectedErrorString { t.Fatalf("Expected error (%s) but got (%s)", expectedErrorString, err.Error()) } } }) t.Run("Allow client to have empty store ID specified", func(t *testing.T) { _, err := NewSdkClient(&ClientConfiguration{ ApiHost: "api.fga.example", StoreId: "", }) if err != nil { t.Fatalf("Expect no error when store id is empty but has %v", err) } }) t.Run("Validate store ID when specified", func(t *testing.T) { _, err := NewSdkClient(&ClientConfiguration{ ApiHost: "api.fga.example", StoreId: "error", }) if err == nil { t.Fatalf("Expect invalid store ID to result in error but there is none") } }) t.Run("Validate auth model ID when specified", func(t *testing.T) { _, err := NewSdkClient(&ClientConfiguration{ ApiHost: "api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", AuthorizationModelId: "BadAuthID", }) if err == nil { t.Fatalf("Expect invalid auth mode ID to result in error but there is none") } }) t.Run("Allow auth model ID to be empty when specified", func(t *testing.T) { _, err := NewSdkClient(&ClientConfiguration{ ApiHost: "api.fga.example", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", AuthorizationModelId: "", }) if err != nil { t.Fatalf("Expect no error when auth model id is empty but has %v", err) } }) t.Run("Allow specifying an ApiUrl with a port and a base path", func(t *testing.T) { _, err := NewSdkClient(&ClientConfiguration{ ApiUrl: "https://api.fga.example:8080/fga", StoreId: "01GXSB9YR785C4FYS3C0RTG7B2", }) if err != nil { t.Fatalf("Expect no error when auth model id is empty but has %v", err) } test := TestDefinition{ Name: "ListStores", JsonResponse: `{"stores":[]}`, ResponseStatus: http.StatusOK, Method: http.MethodGet, } var expectedResponse openfga.ListStoresResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores", fgaClient.GetConfig().ApiUrl), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) got, err := fgaClient.ListStores(context.Background()).Execute() if err != nil { t.Fatalf("%v", err) } if len(got.Stores) != 0 { t.Fatalf("expected stores of length 0, got %v", len(got.Stores)) } }) /* Stores */ t.Run("ListStores", func(t *testing.T) { test := TestDefinition{ Name: "ListStores", JsonResponse: `{"stores":[{"id":"01GXSA8YR785C4FYS3C0RTG7B1","name":"Test Store","created_at":"2023-01-01T23:23:23.000000000Z","updated_at":"2023-01-01T23:23:23.000000000Z"}]}`, ResponseStatus: http.StatusOK, Method: http.MethodGet, } var expectedResponse openfga.ListStoresResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores", fgaClient.GetConfig().ApiUrl), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) options := ClientListStoresOptions{ PageSize: openfga.PtrInt32(10), ContinuationToken: openfga.PtrString("..."), } got, err := fgaClient.ListStores(context.Background()).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } if len(got.Stores) != 1 { t.Fatalf("%v", err) } if got.Stores[0].Id != expectedResponse.Stores[0].Id { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, got.Stores[0].Id, expectedResponse.Stores[0].Id) } // ListStores without options should work _, err = fgaClient.ListStores(context.Background()).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("CreateStore", func(t *testing.T) { test := TestDefinition{ Name: "CreateStore", JsonResponse: `{"id":"01GXSA8YR785C4FYS3C0RTG7B1","name":"Test Store","created_at":"2023-01-01T23:23:23.000000000Z","updated_at":"2023-01-01T23:23:23.000000000Z"}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, } requestBody := ClientCreateStoreRequest{ Name: "Test Store", } var expectedResponse openfga.CreateStoreResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores", fgaClient.GetConfig().ApiUrl), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) got, err := fgaClient.CreateStore(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } _, err = got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if got.Name != expectedResponse.Name { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, got.Name, expectedResponse.Name) } // CreateStore without options should work _, err = fgaClient.CreateStore(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("GetStore", func(t *testing.T) { test := TestDefinition{ Name: "GetStore", JsonResponse: `{"id":"01GXSA8YR785C4FYS3C0RTG7B1","name":"Test Store","created_at":"2023-01-01T23:23:23.000000000Z","updated_at":"2023-01-01T23:23:23.000000000Z"}`, ResponseStatus: http.StatusOK, Method: http.MethodGet, } var expectedResponse openfga.GetStoreResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) got, err := fgaClient.GetStore(context.Background()).Execute() if err != nil { t.Fatalf("%v", err) } if got.Id != expectedResponse.Id { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, got.Id, expectedResponse.Id) } // GetStore without options should work _, err = fgaClient.GetStore(context.Background()).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("GetStoreAfterSettingStoreId", func(t *testing.T) { test := TestDefinition{ Name: "GetStoreAfterSettingStoreId", JsonResponse: `{"id":"01GXSA8YR785C4FYS3C0RTG7B1","name":"Test Store","created_at":"2023-01-01T23:23:23.000000000Z","updated_at":"2023-01-01T23:23:23.000000000Z"}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, } requestBody := ClientCreateStoreRequest{ Name: "Test Store", } var expectedResponse openfga.CreateStoreResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores", fgaClient.GetConfig().ApiUrl), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) got1, err1 := fgaClient.CreateStore(context.Background()).Body(requestBody).Execute() if err1 != nil { t.Fatalf("%v", err1) } _, err = got1.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if got1.Name != expectedResponse.Name { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, got1.Name, expectedResponse.Name) } storeId := got1.Id fgaClient.SetStoreId(storeId) httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(http.MethodGet, fmt.Sprintf("%s/stores/%s", fgaClient.GetConfig().ApiUrl, storeId), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) got2, err2 := fgaClient.GetStore(context.Background()).Execute() if err2 != nil { t.Fatalf("%v", err2) } if got2.Id != storeId { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, got2.Id, storeId) } }) t.Run("DeleteStore", func(t *testing.T) { test := TestDefinition{ Name: "DeleteStore", JsonResponse: ``, ResponseStatus: http.StatusNoContent, Method: http.MethodDelete, } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, "{}") if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) _, err := fgaClient.DeleteStore(context.Background()).Execute() if err != nil { t.Fatalf("%v", err) } // DeleteStore without options should work _, err = fgaClient.DeleteStore(context.Background()).Execute() if err != nil { t.Fatalf("%v", err) } }) /* Authorization Models */ t.Run("ReadAuthorizationModels", func(t *testing.T) { test := TestDefinition{ Name: "ReadAuthorizationModels", JsonResponse: `{"authorization_models":[{"id":"01GXSA8YR785C4FYS3C0RTG7B1","schema_version":"1.1","type_definitions":[]}]}`, ResponseStatus: http.StatusOK, Method: http.MethodGet, RequestPath: "authorization-models", } var expectedResponse openfga.ReadAuthorizationModelsResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) options := ClientReadAuthorizationModelsOptions{ PageSize: openfga.PtrInt32(10), ContinuationToken: openfga.PtrString("..."), } got, err := fgaClient.ReadAuthorizationModels(context.Background()).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } if len(got.AuthorizationModels) != 1 { t.Fatalf("%v", err) } if got.AuthorizationModels[0].Id != expectedResponse.AuthorizationModels[0].Id { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, got.AuthorizationModels[0].Id, expectedResponse.AuthorizationModels[0].Id) } // ReadAuthorizationModels without options should work _, err = fgaClient.ReadAuthorizationModels(context.Background()).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("WriteAuthorizationModel", func(t *testing.T) { test := TestDefinition{ Name: "WriteAuthorizationModel", JsonResponse: `{"authorization_model_id":"01GXSA8YR785C4FYS3C0RTG7B1"}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "authorization-models", } requestBody := ClientWriteAuthorizationModelRequest{ SchemaVersion: "1.1", TypeDefinitions: []openfga.TypeDefinition{ {Type: "user", Relations: &map[string]openfga.Userset{}}, { Type: "document", Relations: &map[string]openfga.Userset{ "writer": { This: &map[string]interface{}{}, }, "viewer": {Union: &openfga.Usersets{ Child: []openfga.Userset{ {This: &map[string]interface{}{}}, {ComputedUserset: &openfga.ObjectRelation{ Object: openfga.PtrString(""), Relation: openfga.PtrString("writer"), }}, }, }}, }, Metadata: &openfga.Metadata{ Relations: &map[string]openfga.RelationMetadata{ "writer": { DirectlyRelatedUserTypes: &[]openfga.RelationReference{ {Type: "user"}, }, }, "viewer": { DirectlyRelatedUserTypes: &[]openfga.RelationReference{ {Type: "user"}, }, }, }, }, }}, } var expectedResponse openfga.WriteAuthorizationModelResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) options := ClientWriteAuthorizationModelOptions{} got, err := fgaClient.WriteAuthorizationModel(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } _, err = got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if got.GetAuthorizationModelId() != expectedResponse.GetAuthorizationModelId() { t.Fatalf("OpenFgaClient.%v() / AuthorizationModelId = %v, want %v", test.Name, got.GetAuthorizationModelId(), expectedResponse.GetAuthorizationModelId()) } // WriteAuthorizationModel without options should work _, err = fgaClient.WriteAuthorizationModel(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("WriteAuthorizationModelWithCondition", func(t *testing.T) { test := TestDefinition{ Name: "WriteAuthorizationModelWithCondition", JsonResponse: `{"authorization_model_id":"01GXSA8YR785C4FYS3C0RTG7B1"}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "authorization-models", } requestBody := ClientWriteAuthorizationModelRequest{ SchemaVersion: "1.1", TypeDefinitions: []openfga.TypeDefinition{ { Type: "user", Relations: &map[string]openfga.Userset{}, }, { Type: "document", Relations: &map[string]openfga.Userset{ "writer": {This: &map[string]interface{}{}}, "viewer": {Union: &openfga.Usersets{ Child: []openfga.Userset{ {This: &map[string]interface{}{}}, {ComputedUserset: &openfga.ObjectRelation{ Object: openfga.PtrString(""), Relation: openfga.PtrString("writer"), }}, }, }}, }, Metadata: &openfga.Metadata{ Relations: &map[string]openfga.RelationMetadata{ "writer": { DirectlyRelatedUserTypes: &[]openfga.RelationReference{ {Type: "user"}, {Type: "user", Condition: openfga.PtrString("ViewCountLessThan200")}, }, }, "viewer": { DirectlyRelatedUserTypes: &[]openfga.RelationReference{ {Type: "user"}, }, }, }, }, }, }, Conditions: &map[string]openfga.Condition{ "ViewCountLessThan200": { Name: "ViewCountLessThan200", Expression: "ViewCount < 200", Parameters: &map[string]openfga.ConditionParamTypeRef{ "ViewCount": { TypeName: openfga.INT, }, "Type": { TypeName: openfga.STRING, }, "Name": { TypeName: openfga.STRING, }, }, }, }, } var expectedResponse openfga.WriteAuthorizationModelResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterMatcherResponder( test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), httpmock.BodyContainsString(`"ViewCountLessThan200"`), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) options := ClientWriteAuthorizationModelOptions{} got, err := fgaClient.WriteAuthorizationModel(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } _, err = got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if got.GetAuthorizationModelId() != expectedResponse.GetAuthorizationModelId() { t.Fatalf("OpenFgaClient.%v() / AuthorizationModelId = %v, want %v", test.Name, got.GetAuthorizationModelId(), expectedResponse.GetAuthorizationModelId()) } // WriteAuthorizationModel without options should work _, err = fgaClient.WriteAuthorizationModel(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("WriteAuthorizationModelWithCondition2", func(t *testing.T) { test := TestDefinition{ Name: "WriteAuthorizationModelWithCondition2", JsonResponse: `{"authorization_model_id":"01GXSA8YR785C4FYS3C0RTG7B1"}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "authorization-models", } schemaVersion := "1.1" typeDefs := []openfga.TypeDefinition{ { Type: "user", Relations: &map[string]openfga.Userset{}, }, { Type: "document", Relations: &map[string]openfga.Userset{ "writer": {This: &map[string]interface{}{}}, "viewer": {Union: &openfga.Usersets{ Child: []openfga.Userset{ {This: &map[string]interface{}{}}, {ComputedUserset: &openfga.ObjectRelation{ Object: openfga.PtrString(""), Relation: openfga.PtrString("writer"), }}, }, }}, }, Metadata: &openfga.Metadata{ Relations: &map[string]openfga.RelationMetadata{ "writer": { DirectlyRelatedUserTypes: &[]openfga.RelationReference{ {Type: "user"}, {Type: "user", Condition: openfga.PtrString("ViewCountLessThan200")}, }, }, "viewer": { DirectlyRelatedUserTypes: &[]openfga.RelationReference{ {Type: "user"}, }, }, }, }, }, } conditions := map[string]openfga.Condition{ "ViewCountLessThan200": { Name: "ViewCountLessThan200", Expression: "ViewCount < 200", Parameters: &map[string]openfga.ConditionParamTypeRef{ "ViewCount": { TypeName: openfga.INT, }, "Type": { TypeName: openfga.STRING, }, "Name": { TypeName: openfga.STRING, }, }, }, } requestBody := ClientWriteAuthorizationModelRequest{ SchemaVersion: schemaVersion, TypeDefinitions: typeDefs, Conditions: &conditions, } var expectedResponse openfga.WriteAuthorizationModelResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterMatcherResponder( test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), httpmock.BodyContainsString(`"ViewCountLessThan200"`), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) options := ClientWriteAuthorizationModelOptions{} got, err := fgaClient.WriteAuthorizationModel(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } _, err = got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if got.GetAuthorizationModelId() != expectedResponse.GetAuthorizationModelId() { t.Fatalf("OpenFgaClient.%v() / AuthorizationModelId = %v, want %v", test.Name, got.GetAuthorizationModelId(), expectedResponse.GetAuthorizationModelId()) } // WriteAuthorizationModel without options should work _, err = fgaClient.WriteAuthorizationModel(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("ReadAuthorizationModel", func(t *testing.T) { test := TestDefinition{ Name: "ReadAuthorizationModel", JsonResponse: `{"authorization_model":{"id":"01GXSA8YR785C4FYS3C0RTG7B1","schema_version":"1.1","type_definitions":[{"type":"github-repo", "relations":{"viewer":{"this":{}}}}]}}`, ResponseStatus: http.StatusOK, Method: http.MethodGet, RequestPath: "authorization-models", } var expectedResponse openfga.ReadAuthorizationModelResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } modelId := expectedResponse.AuthorizationModel.Id httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath, modelId), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) options := ClientReadAuthorizationModelOptions{ AuthorizationModelId: openfga.PtrString(modelId), } got, err := fgaClient.ReadAuthorizationModel(context.Background()).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if got.AuthorizationModel.Id != modelId { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } // ReadAuthorizationModel without options should not work _, err = fgaClient.ReadAuthorizationModel(context.Background()).Execute() expectedError := "Required parameter AuthorizationModelId was not provided" if err == nil || err.Error() != expectedError { t.Fatalf("Expected error:%v, got: %v", expectedError, err) } // ReadAuthorizationModel with options of empty string should not work badOptions := ClientReadAuthorizationModelOptions{ AuthorizationModelId: openfga.PtrString(""), } _, err = fgaClient.ReadAuthorizationModel(context.Background()).Options(badOptions).Execute() if err == nil || err.Error() != expectedError { t.Fatalf("Expected error:%v, got: %v", expectedError, err) } }) t.Run("ReadLatestAuthorizationModel", func(t *testing.T) { test := TestDefinition{ Name: "ReadAuthorizationModels", JsonResponse: `{"authorization_models":[{"id":"01GXSA8YR785C4FYS3C0RTG7B1","schema_version":"1.1","type_definitions":[{"type":"github-repo", "relations":{"viewer":{"this":{}}}}]}]}`, ResponseStatus: http.StatusOK, Method: http.MethodGet, RequestPath: "authorization-models", } var expectedResponse openfga.ReadAuthorizationModelsResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } modelId := expectedResponse.AuthorizationModels[0].Id httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) options := ClientReadLatestAuthorizationModelOptions{} got, err := fgaClient.ReadLatestAuthorizationModel(context.Background()).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if got.AuthorizationModel.GetId() != modelId { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } // ReadLatestAuthorizationModel without options should work _, err = fgaClient.ReadLatestAuthorizationModel(context.Background()).Execute() if err != nil { t.Fatalf("%v", err) } }) /* Relationship Tuples */ t.Run("ReadChanges", func(t *testing.T) { test := TestDefinition{ Name: "ReadChanges", JsonResponse: `{"changes":[{"tuple_key":{"user":"user:81684243-9356-4421-8fbf-a4f8d36aa31b","relation":"viewer","object":"document:roadmap"},"operation":"TUPLE_OPERATION_WRITE","timestamp": "2000-01-01T00:00:00Z"}],"continuation_token":"eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="}`, ResponseStatus: http.StatusOK, Method: http.MethodGet, RequestPath: "changes", } var expectedResponse openfga.ReadChangesResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) body := ClientReadChangesRequest{ Type: "document", } options := ClientReadChangesOptions{ContinuationToken: openfga.PtrString("eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="), PageSize: openfga.PtrInt32(25)} got, err := fgaClient.ReadChanges(context.Background()).Body(body).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if len(got.Changes) != len(expectedResponse.Changes) { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } // ReadChanges without options should work _, err = fgaClient.ReadChanges(context.Background()).Body(body).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("Read", func(t *testing.T) { test := TestDefinition{ Name: "Read", JsonResponse: `{"tuples":[{"key":{"user":"user:81684243-9356-4421-8fbf-a4f8d36aa31b","relation":"viewer","object":"document:roadmap"},"timestamp": "2000-01-01T00:00:00Z"}]}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "read", } requestBody := ClientReadRequest{ User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"), Relation: openfga.PtrString("viewer"), Object: openfga.PtrString("document:roadmap"), } var expectedResponse openfga.ReadResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) options := ClientReadOptions{ PageSize: openfga.PtrInt32(10), ContinuationToken: openfga.PtrString("eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="), } got, err := fgaClient.Read(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if len(got.Tuples) != len(expectedResponse.Tuples) { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } // Read without options should work _, err = fgaClient.Read(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("Write", func(t *testing.T) { test := TestDefinition{ Name: "Write", JsonResponse: `{}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "write", } requestBody := ClientWriteRequest{ Writes: []ClientTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }}, Deletes: []ClientTupleKeyWithoutCondition{}, } options := ClientWriteOptions{ AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } var expectedResponse map[string]interface{} if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) data, err := fgaClient.Write(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } if len(data.Writes) != 1 { t.Fatalf("OpenFgaClient.%v() - expected %v Writes, got %v", test.Name, 1, len(data.Writes)) } if len(data.Deletes) != 0 { t.Fatalf("OpenFgaClient.%v() - expected %v Deletes, got %v", test.Name, 0, len(data.Deletes)) } for index := 0; index < len(data.Writes); index++ { response := data.Writes[index] if response.Error != nil { t.Fatalf("OpenFgaClient.%v()|%d/ %v", test.Name, index, response.Error) } if response.HttpResponse.StatusCode != test.ResponseStatus { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, response.HttpResponse.StatusCode, test.ResponseStatus) } _, err := response.MarshalJSON() if err != nil { t.Fatalf("%v", err) } } for index := 0; index < len(data.Deletes); index++ { response := data.Deletes[index] if response.Error != nil { t.Fatalf("OpenFgaClient.%v()|%d/ %v", test.Name, index, response.Error) } if response.HttpResponse.StatusCode != test.ResponseStatus { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, response.HttpResponse.StatusCode, test.ResponseStatus) } _, err := response.MarshalJSON() if err != nil { t.Fatalf("%v", err) } } // Write without options should work _, err = fgaClient.Write(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("Write with invalid auth model id", func(t *testing.T) { test := TestDefinition{ Name: "Write", JsonResponse: `{}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "write", } requestBody := ClientWriteRequest{ Writes: []ClientTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }}, } options := ClientWriteOptions{ AuthorizationModelId: openfga.PtrString("INVALID"), } var expectedResponse map[string]interface{} if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } _, err := fgaClient.Write(context.Background()).Body(requestBody).Options(options).Execute() if err == nil { t.Fatalf("Expect error due to invalid auth model ID but there is none") } }) t.Run("WriteNonTransaction", func(t *testing.T) { test := TestDefinition{ Name: "Write", JsonResponse: `{}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "write", } requestBody := ClientWriteRequest{ Writes: []ClientTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:budget", }}, Deletes: []ClientTupleKeyWithoutCondition{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:planning", }}, } const authModelId = "01GAHCE4YVKPQEKZQHT2R89MQV" options := ClientWriteOptions{ AuthorizationModelId: openfga.PtrString(authModelId), Transaction: &TransactionOptions{ Disable: true, MaxParallelRequests: 5, MaxPerChunk: 1, }, } var expectedResponse map[string]interface{} if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) httpmock.RegisterResponder("GET", fmt.Sprintf("%s/stores/%s/authorization-models/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, authModelId), func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(http.StatusOK, ""), nil }, ) data, err := fgaClient.Write(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } if len(data.Writes) != 2 { t.Fatalf("OpenFgaClient.%v() - expected %v Writes, got %v", test.Name, 2, len(data.Writes)) } if len(data.Deletes) != 1 { t.Fatalf("OpenFgaClient.%v() - expected %v Deletes, got %v", test.Name, 1, len(data.Deletes)) } for index := 0; index < len(data.Writes); index++ { response := data.Writes[index] if response.Error != nil { t.Fatalf("OpenFgaClient.%v()|%d/ %v", test.Name, index, response.Error) } if response.HttpResponse.StatusCode != test.ResponseStatus { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, response.HttpResponse.StatusCode, test.ResponseStatus) } _, err := response.MarshalJSON() if err != nil { t.Fatalf("%v", err) } } for index := 0; index < len(data.Deletes); index++ { response := data.Deletes[index] if response.Error != nil { t.Fatalf("OpenFgaClient.%v()|%d/ %v", test.Name, index, response.Error) } if response.HttpResponse.StatusCode != test.ResponseStatus { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, response.HttpResponse.StatusCode, test.ResponseStatus) } _, err := response.MarshalJSON() if err != nil { t.Fatalf("%v", err) } } }) t.Run("WriteTuples", func(t *testing.T) { test := TestDefinition{ Name: "Write", JsonResponse: `{}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "write", } requestBody := []ClientTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }} options := ClientWriteOptions{ AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } var expectedResponse map[string]interface{} if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) data, err := fgaClient.WriteTuples(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } if len(data.Writes) != 1 { t.Fatalf("OpenFgaClient.%v() - expected %v Writes, got %v", test.Name, 1, len(data.Writes)) } if len(data.Deletes) != 0 { t.Fatalf("OpenFgaClient.%v() - expected %v Deletes, got %v", test.Name, 0, len(data.Deletes)) } for index := 0; index < len(data.Writes); index++ { response := data.Writes[index] if response.Error != nil { t.Fatalf("OpenFgaClient.%v()|%d/ %v", test.Name, index, response.Error) } if response.HttpResponse.StatusCode != test.ResponseStatus { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, response.HttpResponse.StatusCode, test.ResponseStatus) } _, err := response.MarshalJSON() if err != nil { t.Fatalf("%v", err) } } for index := 0; index < len(data.Deletes); index++ { response := data.Deletes[index] if response.Error != nil { t.Fatalf("OpenFgaClient.%v()|%d/ %v", test.Name, index, response.Error) } if response.HttpResponse.StatusCode != test.ResponseStatus { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, response.HttpResponse.StatusCode, test.ResponseStatus) } _, err := response.MarshalJSON() if err != nil { t.Fatalf("%v", err) } } // WriteTuples without options should work _, err = fgaClient.WriteTuples(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } }) t.Run("DeleteTuples", func(t *testing.T) { test := TestDefinition{ Name: "Write", JsonResponse: `{}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "write", } requestBody := []ClientTupleKeyWithoutCondition{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", }} options := ClientWriteOptions{ AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } var expectedResponse map[string]interface{} if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) data, err := fgaClient.DeleteTuples(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } if len(data.Writes) != 0 { t.Fatalf("OpenFgaClient.%v() - expected no Writes, got %v", test.Name, len(data.Writes)) } if len(data.Deletes) != 1 { t.Fatalf("OpenFgaClient.%v() - expected no Deletes, got %v", test.Name, len(data.Deletes)) } for index := 0; index < len(data.Writes); index++ { response := data.Writes[index] if response.Error != nil { t.Fatalf("OpenFgaClient.%v()|%d/ %v", test.Name, index, response.Error) } if response.HttpResponse.StatusCode != test.ResponseStatus { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, response.HttpResponse.StatusCode, test.ResponseStatus) } _, err := response.MarshalJSON() if err != nil { t.Fatalf("%v", err) } } for index := 0; index < len(data.Deletes); index++ { response := data.Deletes[index] if response.Error != nil { t.Fatalf("OpenFgaClient.%v()|%d/ %v", test.Name, index, response.Error) } if response.HttpResponse.StatusCode != test.ResponseStatus { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, response.HttpResponse.StatusCode, test.ResponseStatus) } _, err := response.MarshalJSON() if err != nil { t.Fatalf("%v", err) } } // DeleteTuples without options should work _, err = fgaClient.DeleteTuples(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } }) /* Relationship Queries */ t.Run("Check", func(t *testing.T) { test := TestDefinition{ Name: "Check", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "check", } requestBody := ClientCheckRequest{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", ContextualTuples: []ClientContextualTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", }}, } options := ClientCheckOptions{ AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } var expectedResponse openfga.CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) got, err := fgaClient.Check(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if got.GetAllowed() != *expectedResponse.Allowed { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } // Check without options should work _, err = fgaClient.Check(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } // check with invalid auth model id should result in error badOptions := ClientCheckOptions{ AuthorizationModelId: openfga.PtrString("INVALID"), } _, err = fgaClient.Check(context.Background()).Body(requestBody).Options(badOptions).Execute() if err == nil { t.Fatalf("Expect error with bad auth model id but there is none") } }) t.Run("BatchCheck", func(t *testing.T) { test := TestDefinition{ Name: "Check", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "check", } requestBody := ClientBatchCheckBody{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", ContextualTuples: []ClientContextualTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", }}, }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "admin", Object: "document:roadmap", ContextualTuples: []ClientContextualTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", }}, }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "creator", Object: "document:roadmap", }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "deleter", Object: "document:roadmap", }} const authModelId = "01GAHCE4YVKPQEKZQHT2R89MQV" options := ClientBatchCheckOptions{ AuthorizationModelId: openfga.PtrString(authModelId), MaxParallelRequests: openfga.PtrInt32(5), } var expectedResponse openfga.CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) httpmock.RegisterResponder("GET", fmt.Sprintf("%s/stores/%s/authorization-models", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId), func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(http.StatusOK, ""), nil }, ) httpmock.RegisterResponder("GET", fmt.Sprintf("%s/stores/%s/authorization-models/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, authModelId), func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(http.StatusOK, ""), nil }, ) got, err := fgaClient.BatchCheck(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } if httpmock.GetTotalCallCount() != 5 { t.Fatalf("OpenFgaClient.%v() - wanted %v calls to /check + 1 call to validate auth model, got %v", test.Name, 4, httpmock.GetTotalCallCount()) } if len(*got) != len(requestBody) { t.Fatalf("OpenFgaClient.%v() - Response Length = %v, want %v", test.Name, len(*got), len(requestBody)) } for index := 0; index < len(*got); index++ { response := (*got)[index] if response.Error != nil { t.Fatalf("OpenFgaClient.%v()|%d/ %v", test.Name, index, response.Error) } if response.HttpResponse.StatusCode != test.ResponseStatus { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, response.HttpResponse.StatusCode, test.ResponseStatus) } responseJson, err := response.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if *response.Allowed != *expectedResponse.Allowed { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } } // BatchCheck without options should work _, err = fgaClient.BatchCheck(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } // BatchCheck with invalid auth model ID should fail badOptions := ClientBatchCheckOptions{ AuthorizationModelId: openfga.PtrString("INVALID"), MaxParallelRequests: openfga.PtrInt32(5), } _, err = fgaClient.BatchCheck(context.Background()).Body(requestBody).Options(badOptions).Execute() if err == nil { t.Fatalf("Expect error with invalid auth model id but there is none") } }) t.Run("BatchCheckConnectionProblem", func(t *testing.T) { test := TestDefinition{ Name: "Check", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "check", } requestBody := ClientBatchCheckBody{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "viewer", Object: "document:roadmap", ContextualTuples: []ClientContextualTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", }}, }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "admin", Object: "document:roadmap", ContextualTuples: []ClientContextualTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", }}, }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "creator", Object: "document:roadmap", }, { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "deleter", Object: "document:roadmap", }} const authModelId = "01GAHCE4YVKPQEKZQHT2R89MQV" options := ClientBatchCheckOptions{ AuthorizationModelId: openfga.PtrString(authModelId), MaxParallelRequests: openfga.PtrInt32(5), } var expectedResponse openfga.CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) httpmock.RegisterResponder("GET", fmt.Sprintf("%s/stores/%s/authorization-models", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId), func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(http.StatusUnauthorized, ""), nil }, ) httpmock.RegisterResponder("GET", fmt.Sprintf("%s/stores/%s/authorization-models/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, authModelId), func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(http.StatusUnauthorized, ""), nil }, ) _, err := fgaClient.BatchCheck(context.Background()).Body(requestBody).Options(options).Execute() if err == nil { t.Fatalf("Expect error but there is none") } }) t.Run("Expand", func(t *testing.T) { test := TestDefinition{ Name: "Expand", JsonResponse: `{"tree":{"root":{"name":"document:roadmap#viewer","union":{"nodes":[{"name": "document:roadmap#viewer","leaf":{"users":{"users":["user:81684243-9356-4421-8fbf-a4f8d36aa31b"]}}}]}}}}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "expand", } requestBody := ClientExpandRequest{ Relation: "viewer", Object: "document:roadmap", } options := ClientExpandOptions{ AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } var expectedResponse openfga.ExpandResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) got, err := fgaClient.Expand(context.Background()).Body(requestBody).Options(options).Execute() if err != nil { t.Fatalf("%v", err) } _, err = got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } // Expand without options should work _, err = fgaClient.Expand(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } // Invalid auth model ID should result in error badOptions := ClientExpandOptions{ AuthorizationModelId: openfga.PtrString("INVALID"), } _, err = fgaClient.Expand(context.Background()).Body(requestBody).Options(badOptions).Execute() if err == nil { t.Fatalf("Expect error for invalid auth model id but there is none") } }) t.Run("ListObjects", func(t *testing.T) { test := TestDefinition{ Name: "ListObjects", JsonResponse: `{"objects":["document:roadmap"]}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "list-objects", } requestBody := ClientListObjectsRequest{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "can_read", Type: "document", ContextualTuples: []ClientContextualTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "folder:product", }, { User: "folder:product", Relation: "parent", Object: "document:roadmap", }}, } options := ClientListObjectsOptions{ AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } var expectedResponse openfga.ListObjectsResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) got, err := fgaClient.ListObjects(context.Background()). Body(requestBody). Options(options). Execute() if err != nil { t.Fatalf("%v", err) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if len(got.Objects) != len(expectedResponse.Objects) || (got.Objects)[0] != (expectedResponse.Objects)[0] { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } // ListObjects without options should work _, err = fgaClient.ListObjects(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } // Invalid auth model id should result in error badOptions := ClientListObjectsOptions{ AuthorizationModelId: openfga.PtrString("INVALID"), } _, err = fgaClient.ListObjects(context.Background()). Body(requestBody). Options(badOptions). Execute() if err == nil { t.Fatalf("Expect error with invalid auth model id but there is none") } }) t.Run("ListRelations", func(t *testing.T) { test := TestDefinition{ Name: "ListRelations", JsonResponse: `{"allowed":true, "resolution":""}`, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "check", } requestBody := ClientListRelationsRequest{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Object: "document:roadmap", Relations: []string{"can_view", "can_edit", "can_delete", "can_rename"}, ContextualTuples: []ClientContextualTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", }}, } const authModelId = "01GAHCE4YVKPQEKZQHT2R89MQV" options := ClientListRelationsOptions{ AuthorizationModelId: openfga.PtrString(authModelId), } var expectedResponse openfga.CheckResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterMatcherResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), httpmock.BodyContainsString(`"relation":"can_delete"`), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, openfga.CheckResponse{Allowed: openfga.PtrBool(false)}) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) httpmock.RegisterResponder("GET", fmt.Sprintf("%s/stores/%s/authorization-models", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId), func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(http.StatusOK, ""), nil }, ) httpmock.RegisterResponder("GET", fmt.Sprintf("%s/stores/%s/authorization-models/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, authModelId), func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(http.StatusOK, ""), nil }, ) got, err := fgaClient.ListRelations(context.Background()). Body(requestBody). Options(options). Execute() if err != nil { t.Fatalf("%v", err) } if httpmock.GetTotalCallCount() != 5 { t.Fatalf("OpenFgaClient.%v() - wanted %v calls to /check + 1 call to validate auth model, got %v", test.Name, 4, httpmock.GetTotalCallCount()) } _, err = got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if len(got.Relations) != 3 { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, len(got.Relations), 3) } // ListRelations without options should work _, err = fgaClient.ListRelations(context.Background()).Body(requestBody).Execute() if err != nil { t.Fatalf("%v", err) } // Invalid auth model ID should result in error badOptions := ClientListRelationsOptions{ AuthorizationModelId: openfga.PtrString("INVALID"), } _, err = fgaClient.ListRelations(context.Background()). Body(requestBody). Options(badOptions). Execute() if err == nil { t.Fatalf("Expect error with invalid auth model id but there is none") } }) t.Run("ListRelationsNoRelationsProvided", func(t *testing.T) { test := TestDefinition{ Name: "ListRelations", JsonResponse: ``, ResponseStatus: http.StatusOK, Method: http.MethodPost, RequestPath: "check", } requestBody := ClientListRelationsRequest{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Object: "document:roadmap", Relations: []string{}, ContextualTuples: []ClientContextualTupleKey{{ User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "editor", Object: "document:roadmap", }}, } options := ClientListRelationsOptions{ AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"), } httpmock.Activate() defer httpmock.DeactivateAndReset() _, err := fgaClient.ListRelations(context.Background()). Body(requestBody). Options(options). Execute() if err == nil { t.Fatalf("OpenFgaClient.%v() - expected an error but received none", test.Name) } }) /* Assertions */ t.Run("ReadAssertions", func(t *testing.T) { modelId := "01GAHCE4YVKPQEKZQHT2R89MQV" test := TestDefinition{ Name: "ReadAssertions", JsonResponse: fmt.Sprintf(`{"assertions":[{"tuple_key":{"user":"user:anna","relation":"can_view","object":"document:roadmap"},"expectation":true}],"authorization_model_id":"%s"}`, modelId), ResponseStatus: http.StatusOK, Method: http.MethodGet, RequestPath: "assertions", } options := ClientReadAssertionsOptions{ AuthorizationModelId: openfga.PtrString(modelId), } var expectedResponse openfga.ReadAssertionsResponse if err := json.Unmarshal([]byte(test.JsonResponse), &expectedResponse); err != nil { t.Fatalf("%v", err) } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath, modelId), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse) if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) got, err := fgaClient.ReadAssertions(context.Background()). Options(options). Execute() if err != nil { t.Fatalf("%v", err) } responseJson, err := got.MarshalJSON() if err != nil { t.Fatalf("%v", err) } if len(*got.Assertions) != len(*expectedResponse.Assertions) || (*got.Assertions)[0].Expectation != (*expectedResponse.Assertions)[0].Expectation { t.Fatalf("OpenFgaClient.%v() = %v, want %v", test.Name, string(responseJson), test.JsonResponse) } // ReadAssertions without options should work _, err = fgaClient.ReadAssertions(context.Background()).Execute() expectedError := "Required parameter AuthorizationModelId was not provided" if err == nil || err.Error() != expectedError { t.Fatalf("Expected error:%v, got: %v", expectedError, err) } // Invalid auth model id should result in error badOptions := ClientReadAssertionsOptions{ AuthorizationModelId: openfga.PtrString("INVALID"), } _, err = fgaClient.ReadAssertions(context.Background()). Options(badOptions). Execute() if err == nil { t.Fatalf("Invalid auth model ID should result in error") } }) t.Run("WriteAssertions", func(t *testing.T) { modelId := "01GAHCE4YVKPQEKZQHT2R89MQV" test := TestDefinition{ Name: "WriteAssertions", JsonResponse: "", ResponseStatus: http.StatusNoContent, Method: http.MethodPut, RequestPath: "assertions", } requestBody := ClientWriteAssertionsRequest{ { User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b", Relation: "can_view", Object: "document:roadmap", Expectation: true, }, } options := ClientWriteAssertionsOptions{ AuthorizationModelId: openfga.PtrString(modelId), } httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores/%s/%s/%s", fgaClient.GetConfig().ApiUrl, fgaClient.GetConfig().StoreId, test.RequestPath, modelId), func(req *http.Request) (*http.Response, error) { resp, err := httpmock.NewJsonResponse(test.ResponseStatus, "") if err != nil { return httpmock.NewStringResponse(http.StatusInternalServerError, ""), nil } return resp, nil }, ) _, err := fgaClient.WriteAssertions(context.Background()). Body(requestBody). Options(options). Execute() if err != nil { t.Fatalf("%v", err) } // WriteAssertions without options should work _, err = fgaClient.WriteAssertions(context.Background()).Body(requestBody).Execute() expectedError := "Required parameter AuthorizationModelId was not provided" if err == nil || err.Error() != expectedError { t.Fatalf("Expected error:%v, got: %v", expectedError, err) } badOptions := ClientWriteAssertionsOptions{ AuthorizationModelId: openfga.PtrString("INVALID"), } _, err = fgaClient.WriteAssertions(context.Background()). Body(requestBody). Options(badOptions). Execute() if err == nil { t.Fatalf("Invalid auth model id should result in error but there is none") } }) } golang-github-openfga-go-sdk-0.3.5/client/errors.go000066400000000000000000000025211456721040100221660ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package client // FgaRequiredParamError Provides access to the body, error and model on returned errors. type FgaRequiredParamError struct { error string param string } // Error returns non-empty string if there was an error. func (e FgaRequiredParamError) Error() string { if e.error == "" { return "Required parameter " + e.Param() + " was not provided" } return e.error } // Param returns the name of the missing parameter func (e FgaRequiredParamError) Param() string { return e.param } // FgaInvalidError Provides access to the body, error and model on returned errors. type FgaInvalidError struct { error string param string description string } // Error returns non-empty string if there was an error. func (e FgaInvalidError) Error() string { if e.error == "" { return "Parameter " + e.Param() + " is not a valid " + e.description } return e.error } // Param returns the name of the invalid parameter func (e FgaInvalidError) Param() string { return e.param } golang-github-openfga-go-sdk-0.3.5/configuration.go000066400000000000000000000073371456721040100222550ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "net/http" "github.com/openfga/go-sdk/credentials" "github.com/openfga/go-sdk/internal/utils" ) const ( SdkVersion = "0.3.5" defaultUserAgent = "openfga-sdk go/0.3.5" ) // RetryParams configures configuration for retry in case of HTTP too many request type RetryParams struct { MaxRetry int `json:"maxRetry,omitempty"` MinWaitInMs int `json:"minWaitInMs,omitempty"` } // Configuration stores the configuration of the API client type Configuration struct { // ApiScheme - defines the scheme for the API: http or https // Deprecated: use ApiUrl instead of ApiScheme and ApiHost ApiScheme string `json:"api_scheme,omitempty"` // ApiHost - defines the host for the API without the scheme e.g. (api.fga.example) // Deprecated: use ApiUrl instead of ApiScheme and ApiHost ApiHost string `json:"api_host,omitempty"` ApiUrl string `json:"api_url,omitempty"` StoreId string `json:"store_id,omitempty"` Credentials *credentials.Credentials `json:"credentials,omitempty"` DefaultHeaders map[string]string `json:"default_headers,omitempty"` UserAgent string `json:"user_agent,omitempty"` Debug bool `json:"debug,omitempty"` HTTPClient *http.Client RetryParams *RetryParams } // DefaultRetryParams returns the default retry parameters func DefaultRetryParams() *RetryParams { return &RetryParams{ MaxRetry: 15, MinWaitInMs: 100, } } func GetSdkUserAgent() string { return defaultUserAgent } // NewConfiguration returns a new Configuration object func NewConfiguration(config Configuration) (*Configuration, error) { apiUrl := config.ApiUrl apiScheme := config.ApiScheme if apiScheme == "" { apiScheme = "https" } if apiUrl == "" { // If api url is not provided, fall back to deprecated config fields apiUrl = apiScheme + "://" + config.ApiHost } cfg := &Configuration{ ApiUrl: apiUrl, StoreId: config.StoreId, Credentials: config.Credentials, DefaultHeaders: config.DefaultHeaders, UserAgent: config.UserAgent, Debug: config.Debug, RetryParams: config.RetryParams, } if cfg.UserAgent == "" { cfg.UserAgent = GetSdkUserAgent() } if cfg.DefaultHeaders == nil { cfg.DefaultHeaders = make(map[string]string) } err := cfg.ValidateConfig() if err != nil { return nil, err } return cfg, nil } // AddDefaultHeader adds a new HTTP header to the default header in the request func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeaders[key] = value } // ValidateConfig ensures that the given configuration is valid func (c *Configuration) ValidateConfig() error { if c.ApiUrl == "" { return reportError("Configuration.ApiUrl is required") } if !IsWellFormedUri(c.ApiUrl) { return reportError("Configuration.ApiUrl (%s) does not form a valid uri", c.ApiUrl) } if c.Credentials != nil { if err := c.Credentials.ValidateCredentialsConfig(); err != nil { return reportError("Credentials are invalid: %v", err) } } if c.RetryParams != nil && c.RetryParams.MaxRetry > 15 { return reportError("Configuration.RetryParams.MaxRetry exceeds maximum allowed limit of 15") } if c.StoreId != "" && !internalutils.IsWellFormedUlidString(c.StoreId) { return reportError("Configuration.StoreId is not a valid ulid") } return nil } golang-github-openfga-go-sdk-0.3.5/credentials/000077500000000000000000000000001456721040100213425ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/credentials/credentials.go000066400000000000000000000106431456721040100241720ustar00rootroot00000000000000package credentials import ( "context" "fmt" "net/http" "net/url" "strings" "github.com/openfga/go-sdk/oauth2/clientcredentials" ) const ApiTokenHeaderKey = "Authorization" const ApiTokenHeaderValuePrefix = "Bearer" // Available credential methods type CredentialsMethod string const ( // No credentials (default) CredentialsMethodNone CredentialsMethod = "none" // API Token credentials (will be sent in "Authorization: Bearer $TOKEN" header) CredentialsMethodApiToken CredentialsMethod = "api_token" // Client Credentials flow will be performed, resulting token will be sent in "Authorization: Bearer $TOKEN" header CredentialsMethodClientCredentials CredentialsMethod = "client_credentials" ) type Config struct { ApiToken string `json:"apiToken,omitempty"` ClientCredentialsApiTokenIssuer string `json:"apiTokenIssuer,omitempty"` ClientCredentialsApiAudience string `json:"apiAudience,omitempty"` ClientCredentialsClientId string `json:"clientId,omitempty"` ClientCredentialsClientSecret string `json:"clientSecret,omitempty"` ClientCredentialsScopes string `json:"scopes,omitempty"` } type Credentials struct { Method CredentialsMethod `json:"method,omitempty"` Config *Config `json:"config,omitempty"` } func NewCredentials(config Credentials) (*Credentials, error) { creds := &Credentials{ Method: config.Method, Config: config.Config, } if creds.Method == "" { creds.Method = CredentialsMethodNone } err := creds.ValidateCredentialsConfig() if err != nil { return nil, err } return creds, nil } func (c *Credentials) ValidateCredentialsConfig() error { conf := c.Config if c.Method == CredentialsMethodApiToken && (conf == nil || conf.ApiToken == "") { return fmt.Errorf("CredentialsConfig.ApiToken is required when CredentialsMethod is CredentialsMethodApiToken (%s)", c.Method) } else if c.Method == CredentialsMethodClientCredentials { if conf == nil || conf.ClientCredentialsClientId == "" || conf.ClientCredentialsClientSecret == "" || conf.ClientCredentialsApiTokenIssuer == "" { return fmt.Errorf("all of CredentialsConfig.ClientId, CredentialsConfig.ClientSecret and CredentialsConfig.ApiTokenIssuer are required when CredentialsMethod is CredentialsMethodClientCredentials (%s)", c.Method) } tokenURL, err := buildApiTokenURL(conf.ClientCredentialsApiTokenIssuer) if err != nil { return err } conf.ClientCredentialsApiTokenIssuer = tokenURL } return nil } type HeaderParams struct { Key string Value string } func (c *Credentials) GetApiTokenHeader() *HeaderParams { if c.Method != CredentialsMethodApiToken { return nil } return &HeaderParams{ Key: ApiTokenHeaderKey, Value: ApiTokenHeaderValuePrefix + " " + c.Config.ApiToken, } } // GetHttpClientAndHeaderOverrides // The main export the client uses to get a configuration with the necessary // httpClient and header overrides based on the chosen credential method func (c *Credentials) GetHttpClientAndHeaderOverrides() (*http.Client, []*HeaderParams) { var headers []*HeaderParams var client = http.DefaultClient switch c.Method { case CredentialsMethodClientCredentials: ccConfig := clientcredentials.Config{ ClientID: c.Config.ClientCredentialsClientId, ClientSecret: c.Config.ClientCredentialsClientSecret, TokenURL: c.Config.ClientCredentialsApiTokenIssuer, } if c.Config.ClientCredentialsApiAudience != "" { ccConfig.EndpointParams = map[string][]string{ "audience": {c.Config.ClientCredentialsApiAudience}, } } if c.Config.ClientCredentialsScopes != "" { scopes := strings.Split(strings.TrimSpace(c.Config.ClientCredentialsScopes), " ") ccConfig.Scopes = append(ccConfig.Scopes, scopes...) } client = ccConfig.Client(context.Background()) case CredentialsMethodApiToken: var header = c.GetApiTokenHeader() if header != nil { headers = append(headers, header) } case CredentialsMethodNone: default: } return client, headers } var defaultTokenEndpointPath = "oauth/token" func buildApiTokenURL(issuer string) (string, error) { u, err := url.Parse(issuer) if err != nil { return "", err } if u.Scheme == "" { u, _ = url.Parse(fmt.Sprintf("https://%s", issuer)) } else if u.Scheme != "http" && u.Scheme != "https" { return "", fmt.Errorf("invalid issuer scheme '%s' (must be http or https)", u.Scheme) } if u.Path == "" || u.Path == "/" { u.Path = defaultTokenEndpointPath } return u.String(), nil } golang-github-openfga-go-sdk-0.3.5/docs/000077500000000000000000000000001456721040100177755ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/docs/AbortedMessageResponse.md000066400000000000000000000044411456721040100247260ustar00rootroot00000000000000# AbortedMessageResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Code** | Pointer to **string** | | [optional] **Message** | Pointer to **string** | | [optional] ## Methods ### NewAbortedMessageResponse `func NewAbortedMessageResponse() *AbortedMessageResponse` NewAbortedMessageResponse instantiates a new AbortedMessageResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewAbortedMessageResponseWithDefaults `func NewAbortedMessageResponseWithDefaults() *AbortedMessageResponse` NewAbortedMessageResponseWithDefaults instantiates a new AbortedMessageResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetCode `func (o *AbortedMessageResponse) GetCode() string` GetCode returns the Code field if non-nil, zero value otherwise. ### GetCodeOk `func (o *AbortedMessageResponse) GetCodeOk() (*string, bool)` GetCodeOk returns a tuple with the Code field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetCode `func (o *AbortedMessageResponse) SetCode(v string)` SetCode sets Code field to given value. ### HasCode `func (o *AbortedMessageResponse) HasCode() bool` HasCode returns a boolean if a field has been set. ### GetMessage `func (o *AbortedMessageResponse) GetMessage() string` GetMessage returns the Message field if non-nil, zero value otherwise. ### GetMessageOk `func (o *AbortedMessageResponse) GetMessageOk() (*string, bool)` GetMessageOk returns a tuple with the Message field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetMessage `func (o *AbortedMessageResponse) SetMessage(v string)` SetMessage sets Message field to given value. ### HasMessage `func (o *AbortedMessageResponse) HasMessage() bool` HasMessage returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Any.md000066400000000000000000000025501456721040100210500ustar00rootroot00000000000000# Any ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Type** | Pointer to **string** | | [optional] ## Methods ### NewAny `func NewAny() *Any` NewAny instantiates a new Any object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewAnyWithDefaults `func NewAnyWithDefaults() *Any` NewAnyWithDefaults instantiates a new Any object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetType `func (o *Any) GetType() string` GetType returns the Type field if non-nil, zero value otherwise. ### GetTypeOk `func (o *Any) GetTypeOk() (*string, bool)` GetTypeOk returns a tuple with the Type field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetType `func (o *Any) SetType(v string)` SetType sets Type field to given value. ### HasType `func (o *Any) HasType() bool` HasType returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Assertion.md000066400000000000000000000037731456721040100223000ustar00rootroot00000000000000# Assertion ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TupleKey** | [**AssertionTupleKey**](AssertionTupleKey.md) | | **Expectation** | **bool** | | ## Methods ### NewAssertion `func NewAssertion(tupleKey AssertionTupleKey, expectation bool, ) *Assertion` NewAssertion instantiates a new Assertion object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewAssertionWithDefaults `func NewAssertionWithDefaults() *Assertion` NewAssertionWithDefaults instantiates a new Assertion object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTupleKey `func (o *Assertion) GetTupleKey() AssertionTupleKey` GetTupleKey returns the TupleKey field if non-nil, zero value otherwise. ### GetTupleKeyOk `func (o *Assertion) GetTupleKeyOk() (*AssertionTupleKey, bool)` GetTupleKeyOk returns a tuple with the TupleKey field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleKey `func (o *Assertion) SetTupleKey(v AssertionTupleKey)` SetTupleKey sets TupleKey field to given value. ### GetExpectation `func (o *Assertion) GetExpectation() bool` GetExpectation returns the Expectation field if non-nil, zero value otherwise. ### GetExpectationOk `func (o *Assertion) GetExpectationOk() (*bool, bool)` GetExpectationOk returns a tuple with the Expectation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetExpectation `func (o *Assertion) SetExpectation(v bool)` SetExpectation sets Expectation field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/AssertionTupleKey.md000066400000000000000000000047311456721040100237560ustar00rootroot00000000000000# AssertionTupleKey ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Object** | **string** | | **Relation** | **string** | | **User** | **string** | | ## Methods ### NewAssertionTupleKey `func NewAssertionTupleKey(object string, relation string, user string, ) *AssertionTupleKey` NewAssertionTupleKey instantiates a new AssertionTupleKey object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewAssertionTupleKeyWithDefaults `func NewAssertionTupleKeyWithDefaults() *AssertionTupleKey` NewAssertionTupleKeyWithDefaults instantiates a new AssertionTupleKey object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetObject `func (o *AssertionTupleKey) GetObject() string` GetObject returns the Object field if non-nil, zero value otherwise. ### GetObjectOk `func (o *AssertionTupleKey) GetObjectOk() (*string, bool)` GetObjectOk returns a tuple with the Object field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetObject `func (o *AssertionTupleKey) SetObject(v string)` SetObject sets Object field to given value. ### GetRelation `func (o *AssertionTupleKey) GetRelation() string` GetRelation returns the Relation field if non-nil, zero value otherwise. ### GetRelationOk `func (o *AssertionTupleKey) GetRelationOk() (*string, bool)` GetRelationOk returns a tuple with the Relation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelation `func (o *AssertionTupleKey) SetRelation(v string)` SetRelation sets Relation field to given value. ### GetUser `func (o *AssertionTupleKey) GetUser() string` GetUser returns the User field if non-nil, zero value otherwise. ### GetUserOk `func (o *AssertionTupleKey) GetUserOk() (*string, bool)` GetUserOk returns a tuple with the User field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUser `func (o *AssertionTupleKey) SetUser(v string)` SetUser sets User field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/AuthorizationModel.md000066400000000000000000000067401456721040100241470ustar00rootroot00000000000000# AuthorizationModel ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Id** | **string** | | **SchemaVersion** | **string** | | **TypeDefinitions** | [**[]TypeDefinition**](TypeDefinition.md) | | **Conditions** | Pointer to [**map[string]Condition**](Condition.md) | | [optional] ## Methods ### NewAuthorizationModel `func NewAuthorizationModel(id string, schemaVersion string, typeDefinitions []TypeDefinition, ) *AuthorizationModel` NewAuthorizationModel instantiates a new AuthorizationModel object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewAuthorizationModelWithDefaults `func NewAuthorizationModelWithDefaults() *AuthorizationModel` NewAuthorizationModelWithDefaults instantiates a new AuthorizationModel object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetId `func (o *AuthorizationModel) GetId() string` GetId returns the Id field if non-nil, zero value otherwise. ### GetIdOk `func (o *AuthorizationModel) GetIdOk() (*string, bool)` GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetId `func (o *AuthorizationModel) SetId(v string)` SetId sets Id field to given value. ### GetSchemaVersion `func (o *AuthorizationModel) GetSchemaVersion() string` GetSchemaVersion returns the SchemaVersion field if non-nil, zero value otherwise. ### GetSchemaVersionOk `func (o *AuthorizationModel) GetSchemaVersionOk() (*string, bool)` GetSchemaVersionOk returns a tuple with the SchemaVersion field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetSchemaVersion `func (o *AuthorizationModel) SetSchemaVersion(v string)` SetSchemaVersion sets SchemaVersion field to given value. ### GetTypeDefinitions `func (o *AuthorizationModel) GetTypeDefinitions() []TypeDefinition` GetTypeDefinitions returns the TypeDefinitions field if non-nil, zero value otherwise. ### GetTypeDefinitionsOk `func (o *AuthorizationModel) GetTypeDefinitionsOk() (*[]TypeDefinition, bool)` GetTypeDefinitionsOk returns a tuple with the TypeDefinitions field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTypeDefinitions `func (o *AuthorizationModel) SetTypeDefinitions(v []TypeDefinition)` SetTypeDefinitions sets TypeDefinitions field to given value. ### GetConditions `func (o *AuthorizationModel) GetConditions() map[string]Condition` GetConditions returns the Conditions field if non-nil, zero value otherwise. ### GetConditionsOk `func (o *AuthorizationModel) GetConditionsOk() (*map[string]Condition, bool)` GetConditionsOk returns a tuple with the Conditions field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetConditions `func (o *AuthorizationModel) SetConditions(v map[string]Condition)` SetConditions sets Conditions field to given value. ### HasConditions `func (o *AuthorizationModel) HasConditions() bool` HasConditions returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/CheckRequest.md000066400000000000000000000111471456721040100227110ustar00rootroot00000000000000# CheckRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TupleKey** | [**CheckRequestTupleKey**](CheckRequestTupleKey.md) | | **ContextualTuples** | Pointer to [**ContextualTupleKeys**](ContextualTupleKeys.md) | | [optional] **AuthorizationModelId** | Pointer to **string** | | [optional] **Trace** | Pointer to **bool** | Defaults to false. Making it true has performance implications. | [optional] [readonly] **Context** | Pointer to **map[string]interface{}** | Additional request context that will be used to evaluate any ABAC conditions encountered in the query evaluation. | [optional] ## Methods ### NewCheckRequest `func NewCheckRequest(tupleKey CheckRequestTupleKey, ) *CheckRequest` NewCheckRequest instantiates a new CheckRequest object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewCheckRequestWithDefaults `func NewCheckRequestWithDefaults() *CheckRequest` NewCheckRequestWithDefaults instantiates a new CheckRequest object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTupleKey `func (o *CheckRequest) GetTupleKey() CheckRequestTupleKey` GetTupleKey returns the TupleKey field if non-nil, zero value otherwise. ### GetTupleKeyOk `func (o *CheckRequest) GetTupleKeyOk() (*CheckRequestTupleKey, bool)` GetTupleKeyOk returns a tuple with the TupleKey field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleKey `func (o *CheckRequest) SetTupleKey(v CheckRequestTupleKey)` SetTupleKey sets TupleKey field to given value. ### GetContextualTuples `func (o *CheckRequest) GetContextualTuples() ContextualTupleKeys` GetContextualTuples returns the ContextualTuples field if non-nil, zero value otherwise. ### GetContextualTuplesOk `func (o *CheckRequest) GetContextualTuplesOk() (*ContextualTupleKeys, bool)` GetContextualTuplesOk returns a tuple with the ContextualTuples field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetContextualTuples `func (o *CheckRequest) SetContextualTuples(v ContextualTupleKeys)` SetContextualTuples sets ContextualTuples field to given value. ### HasContextualTuples `func (o *CheckRequest) HasContextualTuples() bool` HasContextualTuples returns a boolean if a field has been set. ### GetAuthorizationModelId `func (o *CheckRequest) GetAuthorizationModelId() string` GetAuthorizationModelId returns the AuthorizationModelId field if non-nil, zero value otherwise. ### GetAuthorizationModelIdOk `func (o *CheckRequest) GetAuthorizationModelIdOk() (*string, bool)` GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAuthorizationModelId `func (o *CheckRequest) SetAuthorizationModelId(v string)` SetAuthorizationModelId sets AuthorizationModelId field to given value. ### HasAuthorizationModelId `func (o *CheckRequest) HasAuthorizationModelId() bool` HasAuthorizationModelId returns a boolean if a field has been set. ### GetTrace `func (o *CheckRequest) GetTrace() bool` GetTrace returns the Trace field if non-nil, zero value otherwise. ### GetTraceOk `func (o *CheckRequest) GetTraceOk() (*bool, bool)` GetTraceOk returns a tuple with the Trace field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTrace `func (o *CheckRequest) SetTrace(v bool)` SetTrace sets Trace field to given value. ### HasTrace `func (o *CheckRequest) HasTrace() bool` HasTrace returns a boolean if a field has been set. ### GetContext `func (o *CheckRequest) GetContext() map[string]interface{}` GetContext returns the Context field if non-nil, zero value otherwise. ### GetContextOk `func (o *CheckRequest) GetContextOk() (*map[string]interface{}, bool)` GetContextOk returns a tuple with the Context field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetContext `func (o *CheckRequest) SetContext(v map[string]interface{})` SetContext sets Context field to given value. ### HasContext `func (o *CheckRequest) HasContext() bool` HasContext returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/CheckRequestTupleKey.md000066400000000000000000000050251456721040100243720ustar00rootroot00000000000000# CheckRequestTupleKey ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **User** | **string** | | **Relation** | **string** | | **Object** | **string** | | ## Methods ### NewCheckRequestTupleKey `func NewCheckRequestTupleKey(user string, relation string, object string, ) *CheckRequestTupleKey` NewCheckRequestTupleKey instantiates a new CheckRequestTupleKey object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewCheckRequestTupleKeyWithDefaults `func NewCheckRequestTupleKeyWithDefaults() *CheckRequestTupleKey` NewCheckRequestTupleKeyWithDefaults instantiates a new CheckRequestTupleKey object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetUser `func (o *CheckRequestTupleKey) GetUser() string` GetUser returns the User field if non-nil, zero value otherwise. ### GetUserOk `func (o *CheckRequestTupleKey) GetUserOk() (*string, bool)` GetUserOk returns a tuple with the User field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUser `func (o *CheckRequestTupleKey) SetUser(v string)` SetUser sets User field to given value. ### GetRelation `func (o *CheckRequestTupleKey) GetRelation() string` GetRelation returns the Relation field if non-nil, zero value otherwise. ### GetRelationOk `func (o *CheckRequestTupleKey) GetRelationOk() (*string, bool)` GetRelationOk returns a tuple with the Relation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelation `func (o *CheckRequestTupleKey) SetRelation(v string)` SetRelation sets Relation field to given value. ### GetObject `func (o *CheckRequestTupleKey) GetObject() string` GetObject returns the Object field if non-nil, zero value otherwise. ### GetObjectOk `func (o *CheckRequestTupleKey) GetObjectOk() (*string, bool)` GetObjectOk returns a tuple with the Object field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetObject `func (o *CheckRequestTupleKey) SetObject(v string)` SetObject sets Object field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/CheckResponse.md000066400000000000000000000043441456721040100230600ustar00rootroot00000000000000# CheckResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Allowed** | Pointer to **bool** | | [optional] **Resolution** | Pointer to **string** | For internal use only. | [optional] ## Methods ### NewCheckResponse `func NewCheckResponse() *CheckResponse` NewCheckResponse instantiates a new CheckResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewCheckResponseWithDefaults `func NewCheckResponseWithDefaults() *CheckResponse` NewCheckResponseWithDefaults instantiates a new CheckResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetAllowed `func (o *CheckResponse) GetAllowed() bool` GetAllowed returns the Allowed field if non-nil, zero value otherwise. ### GetAllowedOk `func (o *CheckResponse) GetAllowedOk() (*bool, bool)` GetAllowedOk returns a tuple with the Allowed field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAllowed `func (o *CheckResponse) SetAllowed(v bool)` SetAllowed sets Allowed field to given value. ### HasAllowed `func (o *CheckResponse) HasAllowed() bool` HasAllowed returns a boolean if a field has been set. ### GetResolution `func (o *CheckResponse) GetResolution() string` GetResolution returns the Resolution field if non-nil, zero value otherwise. ### GetResolutionOk `func (o *CheckResponse) GetResolutionOk() (*string, bool)` GetResolutionOk returns a tuple with the Resolution field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetResolution `func (o *CheckResponse) SetResolution(v string)` SetResolution sets Resolution field to given value. ### HasResolution `func (o *CheckResponse) HasResolution() bool` HasResolution returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Computed.md000066400000000000000000000025571456721040100221100ustar00rootroot00000000000000# Computed ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Userset** | **string** | | ## Methods ### NewComputed `func NewComputed(userset string, ) *Computed` NewComputed instantiates a new Computed object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewComputedWithDefaults `func NewComputedWithDefaults() *Computed` NewComputedWithDefaults instantiates a new Computed object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetUserset `func (o *Computed) GetUserset() string` GetUserset returns the Userset field if non-nil, zero value otherwise. ### GetUsersetOk `func (o *Computed) GetUsersetOk() (*string, bool)` GetUsersetOk returns a tuple with the Userset field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUserset `func (o *Computed) SetUserset(v string)` SetUserset sets Userset field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Condition.md000066400000000000000000000054021456721040100222460ustar00rootroot00000000000000# Condition ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | **Expression** | **string** | A Google CEL expression, expressed as a string. | **Parameters** | Pointer to [**map[string]ConditionParamTypeRef**](ConditionParamTypeRef.md) | A map of parameter names to the parameter's defined type reference. | [optional] ## Methods ### NewCondition `func NewCondition(name string, expression string, ) *Condition` NewCondition instantiates a new Condition object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewConditionWithDefaults `func NewConditionWithDefaults() *Condition` NewConditionWithDefaults instantiates a new Condition object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetName `func (o *Condition) GetName() string` GetName returns the Name field if non-nil, zero value otherwise. ### GetNameOk `func (o *Condition) GetNameOk() (*string, bool)` GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetName `func (o *Condition) SetName(v string)` SetName sets Name field to given value. ### GetExpression `func (o *Condition) GetExpression() string` GetExpression returns the Expression field if non-nil, zero value otherwise. ### GetExpressionOk `func (o *Condition) GetExpressionOk() (*string, bool)` GetExpressionOk returns a tuple with the Expression field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetExpression `func (o *Condition) SetExpression(v string)` SetExpression sets Expression field to given value. ### GetParameters `func (o *Condition) GetParameters() map[string]ConditionParamTypeRef` GetParameters returns the Parameters field if non-nil, zero value otherwise. ### GetParametersOk `func (o *Condition) GetParametersOk() (*map[string]ConditionParamTypeRef, bool)` GetParametersOk returns a tuple with the Parameters field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetParameters `func (o *Condition) SetParameters(v map[string]ConditionParamTypeRef)` SetParameters sets Parameters field to given value. ### HasParameters `func (o *Condition) HasParameters() bool` HasParameters returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ConditionParamTypeRef.md000066400000000000000000000046541456721040100245360ustar00rootroot00000000000000# ConditionParamTypeRef ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TypeName** | [**TypeName**](TypeName.md) | | [default to UNSPECIFIED] **GenericTypes** | Pointer to [**[]ConditionParamTypeRef**](ConditionParamTypeRef.md) | | [optional] ## Methods ### NewConditionParamTypeRef `func NewConditionParamTypeRef(typeName TypeName, ) *ConditionParamTypeRef` NewConditionParamTypeRef instantiates a new ConditionParamTypeRef object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewConditionParamTypeRefWithDefaults `func NewConditionParamTypeRefWithDefaults() *ConditionParamTypeRef` NewConditionParamTypeRefWithDefaults instantiates a new ConditionParamTypeRef object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTypeName `func (o *ConditionParamTypeRef) GetTypeName() TypeName` GetTypeName returns the TypeName field if non-nil, zero value otherwise. ### GetTypeNameOk `func (o *ConditionParamTypeRef) GetTypeNameOk() (*TypeName, bool)` GetTypeNameOk returns a tuple with the TypeName field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTypeName `func (o *ConditionParamTypeRef) SetTypeName(v TypeName)` SetTypeName sets TypeName field to given value. ### GetGenericTypes `func (o *ConditionParamTypeRef) GetGenericTypes() []ConditionParamTypeRef` GetGenericTypes returns the GenericTypes field if non-nil, zero value otherwise. ### GetGenericTypesOk `func (o *ConditionParamTypeRef) GetGenericTypesOk() (*[]ConditionParamTypeRef, bool)` GetGenericTypesOk returns a tuple with the GenericTypes field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetGenericTypes `func (o *ConditionParamTypeRef) SetGenericTypes(v []ConditionParamTypeRef)` SetGenericTypes sets GenericTypes field to given value. ### HasGenericTypes `func (o *ConditionParamTypeRef) HasGenericTypes() bool` HasGenericTypes returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ContextualTupleKeys.md000066400000000000000000000031101456721040100243060ustar00rootroot00000000000000# ContextualTupleKeys ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TupleKeys** | [**[]TupleKey**](TupleKey.md) | | ## Methods ### NewContextualTupleKeys `func NewContextualTupleKeys(tupleKeys []TupleKey, ) *ContextualTupleKeys` NewContextualTupleKeys instantiates a new ContextualTupleKeys object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewContextualTupleKeysWithDefaults `func NewContextualTupleKeysWithDefaults() *ContextualTupleKeys` NewContextualTupleKeysWithDefaults instantiates a new ContextualTupleKeys object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTupleKeys `func (o *ContextualTupleKeys) GetTupleKeys() []TupleKey` GetTupleKeys returns the TupleKeys field if non-nil, zero value otherwise. ### GetTupleKeysOk `func (o *ContextualTupleKeys) GetTupleKeysOk() (*[]TupleKey, bool)` GetTupleKeysOk returns a tuple with the TupleKeys field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleKeys `func (o *ContextualTupleKeys) SetTupleKeys(v []TupleKey)` SetTupleKeys sets TupleKeys field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/CreateStoreRequest.md000066400000000000000000000027211456721040100241120ustar00rootroot00000000000000# CreateStoreRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | ## Methods ### NewCreateStoreRequest `func NewCreateStoreRequest(name string, ) *CreateStoreRequest` NewCreateStoreRequest instantiates a new CreateStoreRequest object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewCreateStoreRequestWithDefaults `func NewCreateStoreRequestWithDefaults() *CreateStoreRequest` NewCreateStoreRequestWithDefaults instantiates a new CreateStoreRequest object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetName `func (o *CreateStoreRequest) GetName() string` GetName returns the Name field if non-nil, zero value otherwise. ### GetNameOk `func (o *CreateStoreRequest) GetNameOk() (*string, bool)` GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetName `func (o *CreateStoreRequest) SetName(v string)` SetName sets Name field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/CreateStoreResponse.md000066400000000000000000000060421456721040100242600ustar00rootroot00000000000000# CreateStoreResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Id** | **string** | | **Name** | **string** | | **CreatedAt** | **time.Time** | | **UpdatedAt** | **time.Time** | | ## Methods ### NewCreateStoreResponse `func NewCreateStoreResponse(id string, name string, createdAt time.Time, updatedAt time.Time, ) *CreateStoreResponse` NewCreateStoreResponse instantiates a new CreateStoreResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewCreateStoreResponseWithDefaults `func NewCreateStoreResponseWithDefaults() *CreateStoreResponse` NewCreateStoreResponseWithDefaults instantiates a new CreateStoreResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetId `func (o *CreateStoreResponse) GetId() string` GetId returns the Id field if non-nil, zero value otherwise. ### GetIdOk `func (o *CreateStoreResponse) GetIdOk() (*string, bool)` GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetId `func (o *CreateStoreResponse) SetId(v string)` SetId sets Id field to given value. ### GetName `func (o *CreateStoreResponse) GetName() string` GetName returns the Name field if non-nil, zero value otherwise. ### GetNameOk `func (o *CreateStoreResponse) GetNameOk() (*string, bool)` GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetName `func (o *CreateStoreResponse) SetName(v string)` SetName sets Name field to given value. ### GetCreatedAt `func (o *CreateStoreResponse) GetCreatedAt() time.Time` GetCreatedAt returns the CreatedAt field if non-nil, zero value otherwise. ### GetCreatedAtOk `func (o *CreateStoreResponse) GetCreatedAtOk() (*time.Time, bool)` GetCreatedAtOk returns a tuple with the CreatedAt field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetCreatedAt `func (o *CreateStoreResponse) SetCreatedAt(v time.Time)` SetCreatedAt sets CreatedAt field to given value. ### GetUpdatedAt `func (o *CreateStoreResponse) GetUpdatedAt() time.Time` GetUpdatedAt returns the UpdatedAt field if non-nil, zero value otherwise. ### GetUpdatedAtOk `func (o *CreateStoreResponse) GetUpdatedAtOk() (*time.Time, bool)` GetUpdatedAtOk returns a tuple with the UpdatedAt field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUpdatedAt `func (o *CreateStoreResponse) SetUpdatedAt(v time.Time)` SetUpdatedAt sets UpdatedAt field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Difference.md000066400000000000000000000036131456721040100223540ustar00rootroot00000000000000# Difference ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Base** | [**Userset**](Userset.md) | | **Subtract** | [**Userset**](Userset.md) | | ## Methods ### NewDifference `func NewDifference(base Userset, subtract Userset, ) *Difference` NewDifference instantiates a new Difference object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewDifferenceWithDefaults `func NewDifferenceWithDefaults() *Difference` NewDifferenceWithDefaults instantiates a new Difference object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetBase `func (o *Difference) GetBase() Userset` GetBase returns the Base field if non-nil, zero value otherwise. ### GetBaseOk `func (o *Difference) GetBaseOk() (*Userset, bool)` GetBaseOk returns a tuple with the Base field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetBase `func (o *Difference) SetBase(v Userset)` SetBase sets Base field to given value. ### GetSubtract `func (o *Difference) GetSubtract() Userset` GetSubtract returns the Subtract field if non-nil, zero value otherwise. ### GetSubtractOk `func (o *Difference) GetSubtractOk() (*Userset, bool)` GetSubtractOk returns a tuple with the Subtract field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetSubtract `func (o *Difference) SetSubtract(v Userset)` SetSubtract sets Subtract field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ErrorCode.md000066400000000000000000000066741456721040100222200ustar00rootroot00000000000000# ErrorCode ## Enum * `NO_ERROR` (value: `"no_error"`) * `VALIDATION_ERROR` (value: `"validation_error"`) * `AUTHORIZATION_MODEL_NOT_FOUND` (value: `"authorization_model_not_found"`) * `AUTHORIZATION_MODEL_RESOLUTION_TOO_COMPLEX` (value: `"authorization_model_resolution_too_complex"`) * `INVALID_WRITE_INPUT` (value: `"invalid_write_input"`) * `CANNOT_ALLOW_DUPLICATE_TUPLES_IN_ONE_REQUEST` (value: `"cannot_allow_duplicate_tuples_in_one_request"`) * `CANNOT_ALLOW_DUPLICATE_TYPES_IN_ONE_REQUEST` (value: `"cannot_allow_duplicate_types_in_one_request"`) * `CANNOT_ALLOW_MULTIPLE_REFERENCES_TO_ONE_RELATION` (value: `"cannot_allow_multiple_references_to_one_relation"`) * `INVALID_CONTINUATION_TOKEN` (value: `"invalid_continuation_token"`) * `INVALID_TUPLE_SET` (value: `"invalid_tuple_set"`) * `INVALID_CHECK_INPUT` (value: `"invalid_check_input"`) * `INVALID_EXPAND_INPUT` (value: `"invalid_expand_input"`) * `UNSUPPORTED_USER_SET` (value: `"unsupported_user_set"`) * `INVALID_OBJECT_FORMAT` (value: `"invalid_object_format"`) * `WRITE_FAILED_DUE_TO_INVALID_INPUT` (value: `"write_failed_due_to_invalid_input"`) * `AUTHORIZATION_MODEL_ASSERTIONS_NOT_FOUND` (value: `"authorization_model_assertions_not_found"`) * `LATEST_AUTHORIZATION_MODEL_NOT_FOUND` (value: `"latest_authorization_model_not_found"`) * `TYPE_NOT_FOUND` (value: `"type_not_found"`) * `RELATION_NOT_FOUND` (value: `"relation_not_found"`) * `EMPTY_RELATION_DEFINITION` (value: `"empty_relation_definition"`) * `INVALID_USER` (value: `"invalid_user"`) * `INVALID_TUPLE` (value: `"invalid_tuple"`) * `UNKNOWN_RELATION` (value: `"unknown_relation"`) * `STORE_ID_INVALID_LENGTH` (value: `"store_id_invalid_length"`) * `ASSERTIONS_TOO_MANY_ITEMS` (value: `"assertions_too_many_items"`) * `ID_TOO_LONG` (value: `"id_too_long"`) * `AUTHORIZATION_MODEL_ID_TOO_LONG` (value: `"authorization_model_id_too_long"`) * `TUPLE_KEY_VALUE_NOT_SPECIFIED` (value: `"tuple_key_value_not_specified"`) * `TUPLE_KEYS_TOO_MANY_OR_TOO_FEW_ITEMS` (value: `"tuple_keys_too_many_or_too_few_items"`) * `PAGE_SIZE_INVALID` (value: `"page_size_invalid"`) * `PARAM_MISSING_VALUE` (value: `"param_missing_value"`) * `DIFFERENCE_BASE_MISSING_VALUE` (value: `"difference_base_missing_value"`) * `SUBTRACT_BASE_MISSING_VALUE` (value: `"subtract_base_missing_value"`) * `OBJECT_TOO_LONG` (value: `"object_too_long"`) * `RELATION_TOO_LONG` (value: `"relation_too_long"`) * `TYPE_DEFINITIONS_TOO_FEW_ITEMS` (value: `"type_definitions_too_few_items"`) * `TYPE_INVALID_LENGTH` (value: `"type_invalid_length"`) * `TYPE_INVALID_PATTERN` (value: `"type_invalid_pattern"`) * `RELATIONS_TOO_FEW_ITEMS` (value: `"relations_too_few_items"`) * `RELATIONS_TOO_LONG` (value: `"relations_too_long"`) * `RELATIONS_INVALID_PATTERN` (value: `"relations_invalid_pattern"`) * `OBJECT_INVALID_PATTERN` (value: `"object_invalid_pattern"`) * `QUERY_STRING_TYPE_CONTINUATION_TOKEN_MISMATCH` (value: `"query_string_type_continuation_token_mismatch"`) * `EXCEEDED_ENTITY_LIMIT` (value: `"exceeded_entity_limit"`) * `INVALID_CONTEXTUAL_TUPLE` (value: `"invalid_contextual_tuple"`) * `DUPLICATE_CONTEXTUAL_TUPLE` (value: `"duplicate_contextual_tuple"`) * `INVALID_AUTHORIZATION_MODEL` (value: `"invalid_authorization_model"`) * `UNSUPPORTED_SCHEMA_VERSION` (value: `"unsupported_schema_version"`) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ExpandRequest.md000066400000000000000000000045621456721040100231160ustar00rootroot00000000000000# ExpandRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TupleKey** | [**ExpandRequestTupleKey**](ExpandRequestTupleKey.md) | | **AuthorizationModelId** | Pointer to **string** | | [optional] ## Methods ### NewExpandRequest `func NewExpandRequest(tupleKey ExpandRequestTupleKey, ) *ExpandRequest` NewExpandRequest instantiates a new ExpandRequest object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewExpandRequestWithDefaults `func NewExpandRequestWithDefaults() *ExpandRequest` NewExpandRequestWithDefaults instantiates a new ExpandRequest object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTupleKey `func (o *ExpandRequest) GetTupleKey() ExpandRequestTupleKey` GetTupleKey returns the TupleKey field if non-nil, zero value otherwise. ### GetTupleKeyOk `func (o *ExpandRequest) GetTupleKeyOk() (*ExpandRequestTupleKey, bool)` GetTupleKeyOk returns a tuple with the TupleKey field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleKey `func (o *ExpandRequest) SetTupleKey(v ExpandRequestTupleKey)` SetTupleKey sets TupleKey field to given value. ### GetAuthorizationModelId `func (o *ExpandRequest) GetAuthorizationModelId() string` GetAuthorizationModelId returns the AuthorizationModelId field if non-nil, zero value otherwise. ### GetAuthorizationModelIdOk `func (o *ExpandRequest) GetAuthorizationModelIdOk() (*string, bool)` GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAuthorizationModelId `func (o *ExpandRequest) SetAuthorizationModelId(v string)` SetAuthorizationModelId sets AuthorizationModelId field to given value. ### HasAuthorizationModelId `func (o *ExpandRequest) HasAuthorizationModelId() bool` HasAuthorizationModelId returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ExpandRequestTupleKey.md000066400000000000000000000040741456721040100245770ustar00rootroot00000000000000# ExpandRequestTupleKey ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Relation** | **string** | | **Object** | **string** | | ## Methods ### NewExpandRequestTupleKey `func NewExpandRequestTupleKey(relation string, object string, ) *ExpandRequestTupleKey` NewExpandRequestTupleKey instantiates a new ExpandRequestTupleKey object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewExpandRequestTupleKeyWithDefaults `func NewExpandRequestTupleKeyWithDefaults() *ExpandRequestTupleKey` NewExpandRequestTupleKeyWithDefaults instantiates a new ExpandRequestTupleKey object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetRelation `func (o *ExpandRequestTupleKey) GetRelation() string` GetRelation returns the Relation field if non-nil, zero value otherwise. ### GetRelationOk `func (o *ExpandRequestTupleKey) GetRelationOk() (*string, bool)` GetRelationOk returns a tuple with the Relation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelation `func (o *ExpandRequestTupleKey) SetRelation(v string)` SetRelation sets Relation field to given value. ### GetObject `func (o *ExpandRequestTupleKey) GetObject() string` GetObject returns the Object field if non-nil, zero value otherwise. ### GetObjectOk `func (o *ExpandRequestTupleKey) GetObjectOk() (*string, bool)` GetObjectOk returns a tuple with the Object field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetObject `func (o *ExpandRequestTupleKey) SetObject(v string)` SetObject sets Object field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ExpandResponse.md000066400000000000000000000030631456721040100232570ustar00rootroot00000000000000# ExpandResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Tree** | Pointer to [**UsersetTree**](UsersetTree.md) | | [optional] ## Methods ### NewExpandResponse `func NewExpandResponse() *ExpandResponse` NewExpandResponse instantiates a new ExpandResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewExpandResponseWithDefaults `func NewExpandResponseWithDefaults() *ExpandResponse` NewExpandResponseWithDefaults instantiates a new ExpandResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTree `func (o *ExpandResponse) GetTree() UsersetTree` GetTree returns the Tree field if non-nil, zero value otherwise. ### GetTreeOk `func (o *ExpandResponse) GetTreeOk() (*UsersetTree, bool)` GetTreeOk returns a tuple with the Tree field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTree `func (o *ExpandResponse) SetTree(v UsersetTree)` SetTree sets Tree field to given value. ### HasTree `func (o *ExpandResponse) HasTree() bool` HasTree returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/GetStoreResponse.md000066400000000000000000000072151456721040100235770ustar00rootroot00000000000000# GetStoreResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Id** | **string** | | **Name** | **string** | | **CreatedAt** | **time.Time** | | **UpdatedAt** | **time.Time** | | **DeletedAt** | Pointer to **time.Time** | | [optional] ## Methods ### NewGetStoreResponse `func NewGetStoreResponse(id string, name string, createdAt time.Time, updatedAt time.Time, ) *GetStoreResponse` NewGetStoreResponse instantiates a new GetStoreResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewGetStoreResponseWithDefaults `func NewGetStoreResponseWithDefaults() *GetStoreResponse` NewGetStoreResponseWithDefaults instantiates a new GetStoreResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetId `func (o *GetStoreResponse) GetId() string` GetId returns the Id field if non-nil, zero value otherwise. ### GetIdOk `func (o *GetStoreResponse) GetIdOk() (*string, bool)` GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetId `func (o *GetStoreResponse) SetId(v string)` SetId sets Id field to given value. ### GetName `func (o *GetStoreResponse) GetName() string` GetName returns the Name field if non-nil, zero value otherwise. ### GetNameOk `func (o *GetStoreResponse) GetNameOk() (*string, bool)` GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetName `func (o *GetStoreResponse) SetName(v string)` SetName sets Name field to given value. ### GetCreatedAt `func (o *GetStoreResponse) GetCreatedAt() time.Time` GetCreatedAt returns the CreatedAt field if non-nil, zero value otherwise. ### GetCreatedAtOk `func (o *GetStoreResponse) GetCreatedAtOk() (*time.Time, bool)` GetCreatedAtOk returns a tuple with the CreatedAt field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetCreatedAt `func (o *GetStoreResponse) SetCreatedAt(v time.Time)` SetCreatedAt sets CreatedAt field to given value. ### GetUpdatedAt `func (o *GetStoreResponse) GetUpdatedAt() time.Time` GetUpdatedAt returns the UpdatedAt field if non-nil, zero value otherwise. ### GetUpdatedAtOk `func (o *GetStoreResponse) GetUpdatedAtOk() (*time.Time, bool)` GetUpdatedAtOk returns a tuple with the UpdatedAt field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUpdatedAt `func (o *GetStoreResponse) SetUpdatedAt(v time.Time)` SetUpdatedAt sets UpdatedAt field to given value. ### GetDeletedAt `func (o *GetStoreResponse) GetDeletedAt() time.Time` GetDeletedAt returns the DeletedAt field if non-nil, zero value otherwise. ### GetDeletedAtOk `func (o *GetStoreResponse) GetDeletedAtOk() (*time.Time, bool)` GetDeletedAtOk returns a tuple with the DeletedAt field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetDeletedAt `func (o *GetStoreResponse) SetDeletedAt(v time.Time)` SetDeletedAt sets DeletedAt field to given value. ### HasDeletedAt `func (o *GetStoreResponse) HasDeletedAt() bool` HasDeletedAt returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/InternalErrorCode.md000066400000000000000000000013061456721040100237000ustar00rootroot00000000000000# InternalErrorCode ## Enum * `NO_INTERNAL_ERROR` (value: `"no_internal_error"`) * `INTERNAL_ERROR` (value: `"internal_error"`) * `CANCELLED` (value: `"cancelled"`) * `DEADLINE_EXCEEDED` (value: `"deadline_exceeded"`) * `ALREADY_EXISTS` (value: `"already_exists"`) * `RESOURCE_EXHAUSTED` (value: `"resource_exhausted"`) * `FAILED_PRECONDITION` (value: `"failed_precondition"`) * `ABORTED` (value: `"aborted"`) * `OUT_OF_RANGE` (value: `"out_of_range"`) * `UNAVAILABLE` (value: `"unavailable"`) * `DATA_LOSS` (value: `"data_loss"`) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/InternalErrorMessageResponse.md000066400000000000000000000047651456721040100261450ustar00rootroot00000000000000# InternalErrorMessageResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Code** | Pointer to [**InternalErrorCode**](InternalErrorCode.md) | | [optional] [default to NO_INTERNAL_ERROR] **Message** | Pointer to **string** | | [optional] ## Methods ### NewInternalErrorMessageResponse `func NewInternalErrorMessageResponse() *InternalErrorMessageResponse` NewInternalErrorMessageResponse instantiates a new InternalErrorMessageResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewInternalErrorMessageResponseWithDefaults `func NewInternalErrorMessageResponseWithDefaults() *InternalErrorMessageResponse` NewInternalErrorMessageResponseWithDefaults instantiates a new InternalErrorMessageResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetCode `func (o *InternalErrorMessageResponse) GetCode() InternalErrorCode` GetCode returns the Code field if non-nil, zero value otherwise. ### GetCodeOk `func (o *InternalErrorMessageResponse) GetCodeOk() (*InternalErrorCode, bool)` GetCodeOk returns a tuple with the Code field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetCode `func (o *InternalErrorMessageResponse) SetCode(v InternalErrorCode)` SetCode sets Code field to given value. ### HasCode `func (o *InternalErrorMessageResponse) HasCode() bool` HasCode returns a boolean if a field has been set. ### GetMessage `func (o *InternalErrorMessageResponse) GetMessage() string` GetMessage returns the Message field if non-nil, zero value otherwise. ### GetMessageOk `func (o *InternalErrorMessageResponse) GetMessageOk() (*string, bool)` GetMessageOk returns a tuple with the Message field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetMessage `func (o *InternalErrorMessageResponse) SetMessage(v string)` SetMessage sets Message field to given value. ### HasMessage `func (o *InternalErrorMessageResponse) HasMessage() bool` HasMessage returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Leaf.md000066400000000000000000000054721456721040100211760ustar00rootroot00000000000000# Leaf ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Users** | Pointer to [**Users**](Users.md) | | [optional] **Computed** | Pointer to [**Computed**](Computed.md) | | [optional] **TupleToUserset** | Pointer to [**UsersetTreeTupleToUserset**](UsersetTreeTupleToUserset.md) | | [optional] ## Methods ### NewLeaf `func NewLeaf() *Leaf` NewLeaf instantiates a new Leaf object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewLeafWithDefaults `func NewLeafWithDefaults() *Leaf` NewLeafWithDefaults instantiates a new Leaf object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetUsers `func (o *Leaf) GetUsers() Users` GetUsers returns the Users field if non-nil, zero value otherwise. ### GetUsersOk `func (o *Leaf) GetUsersOk() (*Users, bool)` GetUsersOk returns a tuple with the Users field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUsers `func (o *Leaf) SetUsers(v Users)` SetUsers sets Users field to given value. ### HasUsers `func (o *Leaf) HasUsers() bool` HasUsers returns a boolean if a field has been set. ### GetComputed `func (o *Leaf) GetComputed() Computed` GetComputed returns the Computed field if non-nil, zero value otherwise. ### GetComputedOk `func (o *Leaf) GetComputedOk() (*Computed, bool)` GetComputedOk returns a tuple with the Computed field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetComputed `func (o *Leaf) SetComputed(v Computed)` SetComputed sets Computed field to given value. ### HasComputed `func (o *Leaf) HasComputed() bool` HasComputed returns a boolean if a field has been set. ### GetTupleToUserset `func (o *Leaf) GetTupleToUserset() UsersetTreeTupleToUserset` GetTupleToUserset returns the TupleToUserset field if non-nil, zero value otherwise. ### GetTupleToUsersetOk `func (o *Leaf) GetTupleToUsersetOk() (*UsersetTreeTupleToUserset, bool)` GetTupleToUsersetOk returns a tuple with the TupleToUserset field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleToUserset `func (o *Leaf) SetTupleToUserset(v UsersetTreeTupleToUserset)` SetTupleToUserset sets TupleToUserset field to given value. ### HasTupleToUserset `func (o *Leaf) HasTupleToUserset() bool` HasTupleToUserset returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ListObjectsRequest.md000066400000000000000000000117251456721040100241230ustar00rootroot00000000000000# ListObjectsRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **AuthorizationModelId** | Pointer to **string** | | [optional] **Type** | **string** | | **Relation** | **string** | | **User** | **string** | | **ContextualTuples** | Pointer to [**ContextualTupleKeys**](ContextualTupleKeys.md) | | [optional] **Context** | Pointer to **map[string]interface{}** | Additional request context that will be used to evaluate any ABAC conditions encountered in the query evaluation. | [optional] ## Methods ### NewListObjectsRequest `func NewListObjectsRequest(type_ string, relation string, user string, ) *ListObjectsRequest` NewListObjectsRequest instantiates a new ListObjectsRequest object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewListObjectsRequestWithDefaults `func NewListObjectsRequestWithDefaults() *ListObjectsRequest` NewListObjectsRequestWithDefaults instantiates a new ListObjectsRequest object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetAuthorizationModelId `func (o *ListObjectsRequest) GetAuthorizationModelId() string` GetAuthorizationModelId returns the AuthorizationModelId field if non-nil, zero value otherwise. ### GetAuthorizationModelIdOk `func (o *ListObjectsRequest) GetAuthorizationModelIdOk() (*string, bool)` GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAuthorizationModelId `func (o *ListObjectsRequest) SetAuthorizationModelId(v string)` SetAuthorizationModelId sets AuthorizationModelId field to given value. ### HasAuthorizationModelId `func (o *ListObjectsRequest) HasAuthorizationModelId() bool` HasAuthorizationModelId returns a boolean if a field has been set. ### GetType `func (o *ListObjectsRequest) GetType() string` GetType returns the Type field if non-nil, zero value otherwise. ### GetTypeOk `func (o *ListObjectsRequest) GetTypeOk() (*string, bool)` GetTypeOk returns a tuple with the Type field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetType `func (o *ListObjectsRequest) SetType(v string)` SetType sets Type field to given value. ### GetRelation `func (o *ListObjectsRequest) GetRelation() string` GetRelation returns the Relation field if non-nil, zero value otherwise. ### GetRelationOk `func (o *ListObjectsRequest) GetRelationOk() (*string, bool)` GetRelationOk returns a tuple with the Relation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelation `func (o *ListObjectsRequest) SetRelation(v string)` SetRelation sets Relation field to given value. ### GetUser `func (o *ListObjectsRequest) GetUser() string` GetUser returns the User field if non-nil, zero value otherwise. ### GetUserOk `func (o *ListObjectsRequest) GetUserOk() (*string, bool)` GetUserOk returns a tuple with the User field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUser `func (o *ListObjectsRequest) SetUser(v string)` SetUser sets User field to given value. ### GetContextualTuples `func (o *ListObjectsRequest) GetContextualTuples() ContextualTupleKeys` GetContextualTuples returns the ContextualTuples field if non-nil, zero value otherwise. ### GetContextualTuplesOk `func (o *ListObjectsRequest) GetContextualTuplesOk() (*ContextualTupleKeys, bool)` GetContextualTuplesOk returns a tuple with the ContextualTuples field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetContextualTuples `func (o *ListObjectsRequest) SetContextualTuples(v ContextualTupleKeys)` SetContextualTuples sets ContextualTuples field to given value. ### HasContextualTuples `func (o *ListObjectsRequest) HasContextualTuples() bool` HasContextualTuples returns a boolean if a field has been set. ### GetContext `func (o *ListObjectsRequest) GetContext() map[string]interface{}` GetContext returns the Context field if non-nil, zero value otherwise. ### GetContextOk `func (o *ListObjectsRequest) GetContextOk() (*map[string]interface{}, bool)` GetContextOk returns a tuple with the Context field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetContext `func (o *ListObjectsRequest) SetContext(v map[string]interface{})` SetContext sets Context field to given value. ### HasContext `func (o *ListObjectsRequest) HasContext() bool` HasContext returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ListObjectsResponse.md000066400000000000000000000030231456721040100242610ustar00rootroot00000000000000# ListObjectsResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Objects** | **[]string** | | ## Methods ### NewListObjectsResponse `func NewListObjectsResponse(objects []string, ) *ListObjectsResponse` NewListObjectsResponse instantiates a new ListObjectsResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewListObjectsResponseWithDefaults `func NewListObjectsResponseWithDefaults() *ListObjectsResponse` NewListObjectsResponseWithDefaults instantiates a new ListObjectsResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetObjects `func (o *ListObjectsResponse) GetObjects() []string` GetObjects returns the Objects field if non-nil, zero value otherwise. ### GetObjectsOk `func (o *ListObjectsResponse) GetObjectsOk() (*[]string, bool)` GetObjectsOk returns a tuple with the Objects field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetObjects `func (o *ListObjectsResponse) SetObjects(v []string)` SetObjects sets Objects field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ListStoresResponse.md000066400000000000000000000043311456721040100241520ustar00rootroot00000000000000# ListStoresResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Stores** | [**[]Store**](Store.md) | | **ContinuationToken** | **string** | The continuation token will be empty if there are no more stores. | ## Methods ### NewListStoresResponse `func NewListStoresResponse(stores []Store, continuationToken string, ) *ListStoresResponse` NewListStoresResponse instantiates a new ListStoresResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewListStoresResponseWithDefaults `func NewListStoresResponseWithDefaults() *ListStoresResponse` NewListStoresResponseWithDefaults instantiates a new ListStoresResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetStores `func (o *ListStoresResponse) GetStores() []Store` GetStores returns the Stores field if non-nil, zero value otherwise. ### GetStoresOk `func (o *ListStoresResponse) GetStoresOk() (*[]Store, bool)` GetStoresOk returns a tuple with the Stores field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetStores `func (o *ListStoresResponse) SetStores(v []Store)` SetStores sets Stores field to given value. ### GetContinuationToken `func (o *ListStoresResponse) GetContinuationToken() string` GetContinuationToken returns the ContinuationToken field if non-nil, zero value otherwise. ### GetContinuationTokenOk `func (o *ListStoresResponse) GetContinuationTokenOk() (*string, bool)` GetContinuationTokenOk returns a tuple with the ContinuationToken field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetContinuationToken `func (o *ListStoresResponse) SetContinuationToken(v string)` SetContinuationToken sets ContinuationToken field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Metadata.md000066400000000000000000000031561456721040100220440ustar00rootroot00000000000000# Metadata ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Relations** | Pointer to [**map[string]RelationMetadata**](RelationMetadata.md) | | [optional] ## Methods ### NewMetadata `func NewMetadata() *Metadata` NewMetadata instantiates a new Metadata object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewMetadataWithDefaults `func NewMetadataWithDefaults() *Metadata` NewMetadataWithDefaults instantiates a new Metadata object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetRelations `func (o *Metadata) GetRelations() map[string]RelationMetadata` GetRelations returns the Relations field if non-nil, zero value otherwise. ### GetRelationsOk `func (o *Metadata) GetRelationsOk() (*map[string]RelationMetadata, bool)` GetRelationsOk returns a tuple with the Relations field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelations `func (o *Metadata) SetRelations(v map[string]RelationMetadata)` SetRelations sets Relations field to given value. ### HasRelations `func (o *Metadata) HasRelations() bool` HasRelations returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Node.md000066400000000000000000000073701456721040100212130ustar00rootroot00000000000000# Node ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | **Leaf** | Pointer to [**Leaf**](Leaf.md) | | [optional] **Difference** | Pointer to [**UsersetTreeDifference**](UsersetTreeDifference.md) | | [optional] **Union** | Pointer to [**Nodes**](Nodes.md) | | [optional] **Intersection** | Pointer to [**Nodes**](Nodes.md) | | [optional] ## Methods ### NewNode `func NewNode(name string, ) *Node` NewNode instantiates a new Node object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewNodeWithDefaults `func NewNodeWithDefaults() *Node` NewNodeWithDefaults instantiates a new Node object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetName `func (o *Node) GetName() string` GetName returns the Name field if non-nil, zero value otherwise. ### GetNameOk `func (o *Node) GetNameOk() (*string, bool)` GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetName `func (o *Node) SetName(v string)` SetName sets Name field to given value. ### GetLeaf `func (o *Node) GetLeaf() Leaf` GetLeaf returns the Leaf field if non-nil, zero value otherwise. ### GetLeafOk `func (o *Node) GetLeafOk() (*Leaf, bool)` GetLeafOk returns a tuple with the Leaf field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetLeaf `func (o *Node) SetLeaf(v Leaf)` SetLeaf sets Leaf field to given value. ### HasLeaf `func (o *Node) HasLeaf() bool` HasLeaf returns a boolean if a field has been set. ### GetDifference `func (o *Node) GetDifference() UsersetTreeDifference` GetDifference returns the Difference field if non-nil, zero value otherwise. ### GetDifferenceOk `func (o *Node) GetDifferenceOk() (*UsersetTreeDifference, bool)` GetDifferenceOk returns a tuple with the Difference field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetDifference `func (o *Node) SetDifference(v UsersetTreeDifference)` SetDifference sets Difference field to given value. ### HasDifference `func (o *Node) HasDifference() bool` HasDifference returns a boolean if a field has been set. ### GetUnion `func (o *Node) GetUnion() Nodes` GetUnion returns the Union field if non-nil, zero value otherwise. ### GetUnionOk `func (o *Node) GetUnionOk() (*Nodes, bool)` GetUnionOk returns a tuple with the Union field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUnion `func (o *Node) SetUnion(v Nodes)` SetUnion sets Union field to given value. ### HasUnion `func (o *Node) HasUnion() bool` HasUnion returns a boolean if a field has been set. ### GetIntersection `func (o *Node) GetIntersection() Nodes` GetIntersection returns the Intersection field if non-nil, zero value otherwise. ### GetIntersectionOk `func (o *Node) GetIntersectionOk() (*Nodes, bool)` GetIntersectionOk returns a tuple with the Intersection field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetIntersection `func (o *Node) SetIntersection(v Nodes)` SetIntersection sets Intersection field to given value. ### HasIntersection `func (o *Node) HasIntersection() bool` HasIntersection returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Nodes.md000066400000000000000000000024641456721040100213750ustar00rootroot00000000000000# Nodes ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Nodes** | [**[]Node**](Node.md) | | ## Methods ### NewNodes `func NewNodes(nodes []Node, ) *Nodes` NewNodes instantiates a new Nodes object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewNodesWithDefaults `func NewNodesWithDefaults() *Nodes` NewNodesWithDefaults instantiates a new Nodes object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetNodes `func (o *Nodes) GetNodes() []Node` GetNodes returns the Nodes field if non-nil, zero value otherwise. ### GetNodesOk `func (o *Nodes) GetNodesOk() (*[]Node, bool)` GetNodesOk returns a tuple with the Nodes field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetNodes `func (o *Nodes) SetNodes(v []Node)` SetNodes sets Nodes field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/NotFoundErrorCode.md000066400000000000000000000006321456721040100236610ustar00rootroot00000000000000# NotFoundErrorCode ## Enum * `NO_NOT_FOUND_ERROR` (value: `"no_not_found_error"`) * `UNDEFINED_ENDPOINT` (value: `"undefined_endpoint"`) * `STORE_ID_NOT_FOUND` (value: `"store_id_not_found"`) * `UNIMPLEMENTED` (value: `"unimplemented"`) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/NullValue.md000066400000000000000000000003441456721040100222270ustar00rootroot00000000000000# NullValue ## Enum * `NULL_VALUE` (value: `"NULL_VALUE"`) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ObjectRelation.md000066400000000000000000000042711456721040100232270ustar00rootroot00000000000000# ObjectRelation ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Object** | Pointer to **string** | | [optional] **Relation** | Pointer to **string** | | [optional] ## Methods ### NewObjectRelation `func NewObjectRelation() *ObjectRelation` NewObjectRelation instantiates a new ObjectRelation object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewObjectRelationWithDefaults `func NewObjectRelationWithDefaults() *ObjectRelation` NewObjectRelationWithDefaults instantiates a new ObjectRelation object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetObject `func (o *ObjectRelation) GetObject() string` GetObject returns the Object field if non-nil, zero value otherwise. ### GetObjectOk `func (o *ObjectRelation) GetObjectOk() (*string, bool)` GetObjectOk returns a tuple with the Object field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetObject `func (o *ObjectRelation) SetObject(v string)` SetObject sets Object field to given value. ### HasObject `func (o *ObjectRelation) HasObject() bool` HasObject returns a boolean if a field has been set. ### GetRelation `func (o *ObjectRelation) GetRelation() string` GetRelation returns the Relation field if non-nil, zero value otherwise. ### GetRelationOk `func (o *ObjectRelation) GetRelationOk() (*string, bool)` GetRelationOk returns a tuple with the Relation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelation `func (o *ObjectRelation) SetRelation(v string)` SetRelation sets Relation field to given value. ### HasRelation `func (o *ObjectRelation) HasRelation() bool` HasRelation returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/OpenFgaApi.md000066400000000000000000001175731456721040100223060ustar00rootroot00000000000000# \OpenFgaApi All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- [**Check**](OpenFgaApi.md#Check) | **Post** /stores/{store_id}/check | Check whether a user is authorized to access an object [**CreateStore**](OpenFgaApi.md#CreateStore) | **Post** /stores | Create a store [**DeleteStore**](OpenFgaApi.md#DeleteStore) | **Delete** /stores/{store_id} | Delete a store [**Expand**](OpenFgaApi.md#Expand) | **Post** /stores/{store_id}/expand | Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship [**GetStore**](OpenFgaApi.md#GetStore) | **Get** /stores/{store_id} | Get a store [**ListObjects**](OpenFgaApi.md#ListObjects) | **Post** /stores/{store_id}/list-objects | List all objects of the given type that the user has a relation with [**ListStores**](OpenFgaApi.md#ListStores) | **Get** /stores | List all stores [**Read**](OpenFgaApi.md#Read) | **Post** /stores/{store_id}/read | Get tuples from the store that matches a query, without following userset rewrite rules [**ReadAssertions**](OpenFgaApi.md#ReadAssertions) | **Get** /stores/{store_id}/assertions/{authorization_model_id} | Read assertions for an authorization model ID [**ReadAuthorizationModel**](OpenFgaApi.md#ReadAuthorizationModel) | **Get** /stores/{store_id}/authorization-models/{id} | Return a particular version of an authorization model [**ReadAuthorizationModels**](OpenFgaApi.md#ReadAuthorizationModels) | **Get** /stores/{store_id}/authorization-models | Return all the authorization models for a particular store [**ReadChanges**](OpenFgaApi.md#ReadChanges) | **Get** /stores/{store_id}/changes | Return a list of all the tuple changes [**Write**](OpenFgaApi.md#Write) | **Post** /stores/{store_id}/write | Add or delete tuples from the store [**WriteAssertions**](OpenFgaApi.md#WriteAssertions) | **Put** /stores/{store_id}/assertions/{authorization_model_id} | Upsert assertions for an authorization model ID [**WriteAuthorizationModel**](OpenFgaApi.md#WriteAuthorizationModel) | **Post** /stores/{store_id}/authorization-models | Create a new authorization model ## Check > CheckResponse Check(ctx).Body(body).Execute() Check whether a user is authorized to access an object ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { body := *openapiclient.NewCheckRequest(*openapiclient.NewCheckRequestTupleKey("user:anne", "reader", "document:2021-budget")) // CheckRequest | configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.Check(context.Background()).Body(body).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.Check``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `Check`: CheckResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.Check`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. ### Other Parameters Other parameters are passed through a pointer to a apiCheckRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | [**CheckRequest**](CheckRequest.md) | | ### Return type [**CheckResponse**](CheckResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## CreateStore > CreateStoreResponse CreateStore(ctx).Body(body).Execute() Create a store ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.CreateStore(context.Background()).Body(body).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.CreateStore``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `CreateStore`: CreateStoreResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.CreateStore`: %v\n", resp) } ``` ### Path Parameters ### Other Parameters Other parameters are passed through a pointer to a apiCreateStoreRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | [**CreateStoreRequest**](CreateStoreRequest.md) | | ### Return type [**CreateStoreResponse**](CreateStoreResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## DeleteStore > DeleteStore(ctx).Execute() Delete a store ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.DeleteStore(context.Background()).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.DeleteStore``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. ### Other Parameters Other parameters are passed through a pointer to a apiDeleteStoreRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- ### Return type (empty response body) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## Expand > ExpandResponse Expand(ctx).Body(body).Execute() Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { body := *openapiclient.NewExpandRequest(*openapiclient.NewExpandRequestTupleKey("reader", "document:2021-budget")) // ExpandRequest | configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.Expand(context.Background()).Body(body).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.Expand``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `Expand`: ExpandResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.Expand`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. ### Other Parameters Other parameters are passed through a pointer to a apiExpandRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | [**ExpandRequest**](ExpandRequest.md) | | ### Return type [**ExpandResponse**](ExpandResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## GetStore > GetStoreResponse GetStore(ctx).Execute() Get a store ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.GetStore(context.Background()).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.GetStore``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `GetStore`: GetStoreResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.GetStore`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. ### Other Parameters Other parameters are passed through a pointer to a apiGetStoreRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- ### Return type [**GetStoreResponse**](GetStoreResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## ListObjects > ListObjectsResponse ListObjects(ctx).Body(body).Execute() List all objects of the given type that the user has a relation with ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { body := *openapiclient.NewListObjectsRequest("document", "reader", "user:anne") // ListObjectsRequest | configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.ListObjects(context.Background()).Body(body).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.ListObjects``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `ListObjects`: ListObjectsResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.ListObjects`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. ### Other Parameters Other parameters are passed through a pointer to a apiListObjectsRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | [**ListObjectsRequest**](ListObjectsRequest.md) | | ### Return type [**ListObjectsResponse**](ListObjectsResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## ListStores > ListStoresResponse ListStores(ctx).PageSize(pageSize).ContinuationToken(continuationToken).Execute() List all stores ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { continuationToken := "continuationToken_example" // string | (optional) configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.ListStores(context.Background()).PageSize(pageSize).ContinuationToken(continuationToken).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.ListStores``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `ListStores`: ListStoresResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.ListStores`: %v\n", resp) } ``` ### Path Parameters ### Other Parameters Other parameters are passed through a pointer to a apiListStoresRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pageSize** | **int32** | | **continuationToken** | **string** | | ### Return type [**ListStoresResponse**](ListStoresResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## Read > ReadResponse Read(ctx).Body(body).Execute() Get tuples from the store that matches a query, without following userset rewrite rules ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { body := *openapiclient.NewReadRequest() // ReadRequest | configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.Read(context.Background()).Body(body).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.Read``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `Read`: ReadResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.Read`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. ### Other Parameters Other parameters are passed through a pointer to a apiReadRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | [**ReadRequest**](ReadRequest.md) | | ### Return type [**ReadResponse**](ReadResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## ReadAssertions > ReadAssertionsResponse ReadAssertions(ctx, authorizationModelId).Execute() Read assertions for an authorization model ID ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { authorizationModelId := "authorizationModelId_example" // string | configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.ReadAssertions(context.Background(), authorizationModelId).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.ReadAssertions``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `ReadAssertions`: ReadAssertionsResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.ReadAssertions`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. **authorizationModelId** | **string** | | ### Other Parameters Other parameters are passed through a pointer to a apiReadAssertionsRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- ### Return type [**ReadAssertionsResponse**](ReadAssertionsResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## ReadAuthorizationModel > ReadAuthorizationModelResponse ReadAuthorizationModel(ctx, id).Execute() Return a particular version of an authorization model ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { id := "id_example" // string | configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.ReadAuthorizationModel(context.Background(), id).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.ReadAuthorizationModel``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `ReadAuthorizationModel`: ReadAuthorizationModelResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.ReadAuthorizationModel`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. **id** | **string** | | ### Other Parameters Other parameters are passed through a pointer to a apiReadAuthorizationModelRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- ### Return type [**ReadAuthorizationModelResponse**](ReadAuthorizationModelResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## ReadAuthorizationModels > ReadAuthorizationModelsResponse ReadAuthorizationModels(ctx).PageSize(pageSize).ContinuationToken(continuationToken).Execute() Return all the authorization models for a particular store ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { pageSize := int32(56) // int32 | (optional) continuationToken := "continuationToken_example" // string | (optional) configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.ReadAuthorizationModels(context.Background()).PageSize(pageSize).ContinuationToken(continuationToken).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.ReadAuthorizationModels``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `ReadAuthorizationModels`: ReadAuthorizationModelsResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.ReadAuthorizationModels`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. ### Other Parameters Other parameters are passed through a pointer to a apiReadAuthorizationModelsRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pageSize** | **int32** | | **continuationToken** | **string** | | ### Return type [**ReadAuthorizationModelsResponse**](ReadAuthorizationModelsResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## ReadChanges > ReadChangesResponse ReadChanges(ctx).Type_(type_).PageSize(pageSize).ContinuationToken(continuationToken).Execute() Return a list of all the tuple changes ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { type_ := "type__example" // string | (optional) pageSize := int32(56) // int32 | (optional) continuationToken := "continuationToken_example" // string | (optional) configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.ReadChanges(context.Background()).Type_(type_).PageSize(pageSize).ContinuationToken(continuationToken).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.ReadChanges``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `ReadChanges`: ReadChangesResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.ReadChanges`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. ### Other Parameters Other parameters are passed through a pointer to a apiReadChangesRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **type_** | **string** | | **pageSize** | **int32** | | **continuationToken** | **string** | | ### Return type [**ReadChangesResponse**](ReadChangesResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## Write > map[string]interface{} Write(ctx).Body(body).Execute() Add or delete tuples from the store ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { body := *openapiclient.NewWriteRequest() // WriteRequest | configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.Write(context.Background()).Body(body).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.Write``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `Write`: map[string]interface{} fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.Write`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. ### Other Parameters Other parameters are passed through a pointer to a apiWriteRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | [**WriteRequest**](WriteRequest.md) | | ### Return type **map[string]interface{}** ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## WriteAssertions > WriteAssertions(ctx, authorizationModelId).Body(body).Execute() Upsert assertions for an authorization model ID ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { authorizationModelId := "authorizationModelId_example" // string | body := *openapiclient.NewWriteAssertionsRequest([]openapiclient.Assertion{*openapiclient.NewAssertion(*openapiclient.NewAssertionTupleKey("document:2021-budget", "reader", "user:anne"), false)}) // WriteAssertionsRequest | configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.WriteAssertions(context.Background(), authorizationModelId).Body(body).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.WriteAssertions``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. **authorizationModelId** | **string** | | ### Other Parameters Other parameters are passed through a pointer to a apiWriteAssertionsRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | [**WriteAssertionsRequest**](WriteAssertionsRequest.md) | | ### Return type (empty response body) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) ## WriteAuthorizationModel > WriteAuthorizationModelResponse WriteAuthorizationModel(ctx).Body(body).Execute() Create a new authorization model ### Example ```go package main import ( "context" "fmt" "os" openfga "github.com/openfga/go-sdk" ) func main() { body := *openapiclient.NewWriteAuthorizationModelRequest([]openapiclient.TypeDefinition{*openapiclient.NewTypeDefinition("document")}, "SchemaVersion_example") // WriteAuthorizationModelRequest | configuration, err := openfga.NewConfiguration(openfga.Configuration{ ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` }) if err != nil { // .. Handle error } apiClient := openfga.NewAPIClient(configuration) resp, r, err := apiClient.OpenFgaApi.WriteAuthorizationModel(context.Background()).Body(body).Execute() if err != nil { fmt.Fprintf(os.Stderr, "Error when calling `OpenFgaApi.WriteAuthorizationModel``: %v\n", err) fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) switch v := err.(type) { case FgaApiAuthenticationError: // Handle authentication error case FgaApiValidationError: // Handle parameter validation error case FgaApiNotFoundError: // Handle not found error case FgaApiInternalError: // Handle API internal error case FgaApiRateLimitError: // Exponential backoff in handling rate limit error default: // Handle unknown/undefined error } } // response from `WriteAuthorizationModel`: WriteAuthorizationModelResponse fmt.Fprintf(os.Stdout, "Response from `OpenFgaApi.WriteAuthorizationModel`: %v\n", resp) } ``` ### Path Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. ### Other Parameters Other parameters are passed through a pointer to a apiWriteAuthorizationModelRequest struct via the builder pattern Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | [**WriteAuthorizationModelRequest**](WriteAuthorizationModelRequest.md) | | ### Return type [**WriteAuthorizationModelResponse**](WriteAuthorizationModelResponse.md) ### Authorization No authorization required ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/PathUnknownErrorMessageResponse.md000066400000000000000000000050571456721040100266400ustar00rootroot00000000000000# PathUnknownErrorMessageResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Code** | Pointer to [**NotFoundErrorCode**](NotFoundErrorCode.md) | | [optional] [default to NO_NOT_FOUND_ERROR] **Message** | Pointer to **string** | | [optional] ## Methods ### NewPathUnknownErrorMessageResponse `func NewPathUnknownErrorMessageResponse() *PathUnknownErrorMessageResponse` NewPathUnknownErrorMessageResponse instantiates a new PathUnknownErrorMessageResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewPathUnknownErrorMessageResponseWithDefaults `func NewPathUnknownErrorMessageResponseWithDefaults() *PathUnknownErrorMessageResponse` NewPathUnknownErrorMessageResponseWithDefaults instantiates a new PathUnknownErrorMessageResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetCode `func (o *PathUnknownErrorMessageResponse) GetCode() NotFoundErrorCode` GetCode returns the Code field if non-nil, zero value otherwise. ### GetCodeOk `func (o *PathUnknownErrorMessageResponse) GetCodeOk() (*NotFoundErrorCode, bool)` GetCodeOk returns a tuple with the Code field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetCode `func (o *PathUnknownErrorMessageResponse) SetCode(v NotFoundErrorCode)` SetCode sets Code field to given value. ### HasCode `func (o *PathUnknownErrorMessageResponse) HasCode() bool` HasCode returns a boolean if a field has been set. ### GetMessage `func (o *PathUnknownErrorMessageResponse) GetMessage() string` GetMessage returns the Message field if non-nil, zero value otherwise. ### GetMessageOk `func (o *PathUnknownErrorMessageResponse) GetMessageOk() (*string, bool)` GetMessageOk returns a tuple with the Message field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetMessage `func (o *PathUnknownErrorMessageResponse) SetMessage(v string)` SetMessage sets Message field to given value. ### HasMessage `func (o *PathUnknownErrorMessageResponse) HasMessage() bool` HasMessage returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ReadAssertionsResponse.md000066400000000000000000000047311456721040100247710ustar00rootroot00000000000000# ReadAssertionsResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **AuthorizationModelId** | **string** | | **Assertions** | Pointer to [**[]Assertion**](Assertion.md) | | [optional] ## Methods ### NewReadAssertionsResponse `func NewReadAssertionsResponse(authorizationModelId string, ) *ReadAssertionsResponse` NewReadAssertionsResponse instantiates a new ReadAssertionsResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewReadAssertionsResponseWithDefaults `func NewReadAssertionsResponseWithDefaults() *ReadAssertionsResponse` NewReadAssertionsResponseWithDefaults instantiates a new ReadAssertionsResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetAuthorizationModelId `func (o *ReadAssertionsResponse) GetAuthorizationModelId() string` GetAuthorizationModelId returns the AuthorizationModelId field if non-nil, zero value otherwise. ### GetAuthorizationModelIdOk `func (o *ReadAssertionsResponse) GetAuthorizationModelIdOk() (*string, bool)` GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAuthorizationModelId `func (o *ReadAssertionsResponse) SetAuthorizationModelId(v string)` SetAuthorizationModelId sets AuthorizationModelId field to given value. ### GetAssertions `func (o *ReadAssertionsResponse) GetAssertions() []Assertion` GetAssertions returns the Assertions field if non-nil, zero value otherwise. ### GetAssertionsOk `func (o *ReadAssertionsResponse) GetAssertionsOk() (*[]Assertion, bool)` GetAssertionsOk returns a tuple with the Assertions field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAssertions `func (o *ReadAssertionsResponse) SetAssertions(v []Assertion)` SetAssertions sets Assertions field to given value. ### HasAssertions `func (o *ReadAssertionsResponse) HasAssertions() bool` HasAssertions returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ReadAuthorizationModelResponse.md000066400000000000000000000040461456721040100264570ustar00rootroot00000000000000# ReadAuthorizationModelResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **AuthorizationModel** | Pointer to [**AuthorizationModel**](AuthorizationModel.md) | | [optional] ## Methods ### NewReadAuthorizationModelResponse `func NewReadAuthorizationModelResponse() *ReadAuthorizationModelResponse` NewReadAuthorizationModelResponse instantiates a new ReadAuthorizationModelResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewReadAuthorizationModelResponseWithDefaults `func NewReadAuthorizationModelResponseWithDefaults() *ReadAuthorizationModelResponse` NewReadAuthorizationModelResponseWithDefaults instantiates a new ReadAuthorizationModelResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetAuthorizationModel `func (o *ReadAuthorizationModelResponse) GetAuthorizationModel() AuthorizationModel` GetAuthorizationModel returns the AuthorizationModel field if non-nil, zero value otherwise. ### GetAuthorizationModelOk `func (o *ReadAuthorizationModelResponse) GetAuthorizationModelOk() (*AuthorizationModel, bool)` GetAuthorizationModelOk returns a tuple with the AuthorizationModel field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAuthorizationModel `func (o *ReadAuthorizationModelResponse) SetAuthorizationModel(v AuthorizationModel)` SetAuthorizationModel sets AuthorizationModel field to given value. ### HasAuthorizationModel `func (o *ReadAuthorizationModelResponse) HasAuthorizationModel() bool` HasAuthorizationModel returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ReadAuthorizationModelsResponse.md000066400000000000000000000055311456721040100266420ustar00rootroot00000000000000# ReadAuthorizationModelsResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **AuthorizationModels** | [**[]AuthorizationModel**](AuthorizationModel.md) | | **ContinuationToken** | Pointer to **string** | The continuation token will be empty if there are no more models. | [optional] ## Methods ### NewReadAuthorizationModelsResponse `func NewReadAuthorizationModelsResponse(authorizationModels []AuthorizationModel, ) *ReadAuthorizationModelsResponse` NewReadAuthorizationModelsResponse instantiates a new ReadAuthorizationModelsResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewReadAuthorizationModelsResponseWithDefaults `func NewReadAuthorizationModelsResponseWithDefaults() *ReadAuthorizationModelsResponse` NewReadAuthorizationModelsResponseWithDefaults instantiates a new ReadAuthorizationModelsResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetAuthorizationModels `func (o *ReadAuthorizationModelsResponse) GetAuthorizationModels() []AuthorizationModel` GetAuthorizationModels returns the AuthorizationModels field if non-nil, zero value otherwise. ### GetAuthorizationModelsOk `func (o *ReadAuthorizationModelsResponse) GetAuthorizationModelsOk() (*[]AuthorizationModel, bool)` GetAuthorizationModelsOk returns a tuple with the AuthorizationModels field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAuthorizationModels `func (o *ReadAuthorizationModelsResponse) SetAuthorizationModels(v []AuthorizationModel)` SetAuthorizationModels sets AuthorizationModels field to given value. ### GetContinuationToken `func (o *ReadAuthorizationModelsResponse) GetContinuationToken() string` GetContinuationToken returns the ContinuationToken field if non-nil, zero value otherwise. ### GetContinuationTokenOk `func (o *ReadAuthorizationModelsResponse) GetContinuationTokenOk() (*string, bool)` GetContinuationTokenOk returns a tuple with the ContinuationToken field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetContinuationToken `func (o *ReadAuthorizationModelsResponse) SetContinuationToken(v string)` SetContinuationToken sets ContinuationToken field to given value. ### HasContinuationToken `func (o *ReadAuthorizationModelsResponse) HasContinuationToken() bool` HasContinuationToken returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ReadChangesResponse.md000066400000000000000000000046631456721040100242130ustar00rootroot00000000000000# ReadChangesResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Changes** | [**[]TupleChange**](TupleChange.md) | | **ContinuationToken** | Pointer to **string** | The continuation token will be identical if there are no new changes. | [optional] ## Methods ### NewReadChangesResponse `func NewReadChangesResponse(changes []TupleChange, ) *ReadChangesResponse` NewReadChangesResponse instantiates a new ReadChangesResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewReadChangesResponseWithDefaults `func NewReadChangesResponseWithDefaults() *ReadChangesResponse` NewReadChangesResponseWithDefaults instantiates a new ReadChangesResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetChanges `func (o *ReadChangesResponse) GetChanges() []TupleChange` GetChanges returns the Changes field if non-nil, zero value otherwise. ### GetChangesOk `func (o *ReadChangesResponse) GetChangesOk() (*[]TupleChange, bool)` GetChangesOk returns a tuple with the Changes field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetChanges `func (o *ReadChangesResponse) SetChanges(v []TupleChange)` SetChanges sets Changes field to given value. ### GetContinuationToken `func (o *ReadChangesResponse) GetContinuationToken() string` GetContinuationToken returns the ContinuationToken field if non-nil, zero value otherwise. ### GetContinuationTokenOk `func (o *ReadChangesResponse) GetContinuationTokenOk() (*string, bool)` GetContinuationTokenOk returns a tuple with the ContinuationToken field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetContinuationToken `func (o *ReadChangesResponse) SetContinuationToken(v string)` SetContinuationToken sets ContinuationToken field to given value. ### HasContinuationToken `func (o *ReadChangesResponse) HasContinuationToken() bool` HasContinuationToken returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ReadRequest.md000066400000000000000000000057721456721040100225560ustar00rootroot00000000000000# ReadRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TupleKey** | Pointer to [**ReadRequestTupleKey**](ReadRequestTupleKey.md) | | [optional] **PageSize** | Pointer to **int32** | | [optional] **ContinuationToken** | Pointer to **string** | | [optional] ## Methods ### NewReadRequest `func NewReadRequest() *ReadRequest` NewReadRequest instantiates a new ReadRequest object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewReadRequestWithDefaults `func NewReadRequestWithDefaults() *ReadRequest` NewReadRequestWithDefaults instantiates a new ReadRequest object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTupleKey `func (o *ReadRequest) GetTupleKey() ReadRequestTupleKey` GetTupleKey returns the TupleKey field if non-nil, zero value otherwise. ### GetTupleKeyOk `func (o *ReadRequest) GetTupleKeyOk() (*ReadRequestTupleKey, bool)` GetTupleKeyOk returns a tuple with the TupleKey field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleKey `func (o *ReadRequest) SetTupleKey(v ReadRequestTupleKey)` SetTupleKey sets TupleKey field to given value. ### HasTupleKey `func (o *ReadRequest) HasTupleKey() bool` HasTupleKey returns a boolean if a field has been set. ### GetPageSize `func (o *ReadRequest) GetPageSize() int32` GetPageSize returns the PageSize field if non-nil, zero value otherwise. ### GetPageSizeOk `func (o *ReadRequest) GetPageSizeOk() (*int32, bool)` GetPageSizeOk returns a tuple with the PageSize field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetPageSize `func (o *ReadRequest) SetPageSize(v int32)` SetPageSize sets PageSize field to given value. ### HasPageSize `func (o *ReadRequest) HasPageSize() bool` HasPageSize returns a boolean if a field has been set. ### GetContinuationToken `func (o *ReadRequest) GetContinuationToken() string` GetContinuationToken returns the ContinuationToken field if non-nil, zero value otherwise. ### GetContinuationTokenOk `func (o *ReadRequest) GetContinuationTokenOk() (*string, bool)` GetContinuationTokenOk returns a tuple with the ContinuationToken field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetContinuationToken `func (o *ReadRequest) SetContinuationToken(v string)` SetContinuationToken sets ContinuationToken field to given value. ### HasContinuationToken `func (o *ReadRequest) HasContinuationToken() bool` HasContinuationToken returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ReadRequestTupleKey.md000066400000000000000000000055701456721040100242350ustar00rootroot00000000000000# ReadRequestTupleKey ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **User** | Pointer to **string** | | [optional] **Relation** | Pointer to **string** | | [optional] **Object** | Pointer to **string** | | [optional] ## Methods ### NewReadRequestTupleKey `func NewReadRequestTupleKey() *ReadRequestTupleKey` NewReadRequestTupleKey instantiates a new ReadRequestTupleKey object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewReadRequestTupleKeyWithDefaults `func NewReadRequestTupleKeyWithDefaults() *ReadRequestTupleKey` NewReadRequestTupleKeyWithDefaults instantiates a new ReadRequestTupleKey object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetUser `func (o *ReadRequestTupleKey) GetUser() string` GetUser returns the User field if non-nil, zero value otherwise. ### GetUserOk `func (o *ReadRequestTupleKey) GetUserOk() (*string, bool)` GetUserOk returns a tuple with the User field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUser `func (o *ReadRequestTupleKey) SetUser(v string)` SetUser sets User field to given value. ### HasUser `func (o *ReadRequestTupleKey) HasUser() bool` HasUser returns a boolean if a field has been set. ### GetRelation `func (o *ReadRequestTupleKey) GetRelation() string` GetRelation returns the Relation field if non-nil, zero value otherwise. ### GetRelationOk `func (o *ReadRequestTupleKey) GetRelationOk() (*string, bool)` GetRelationOk returns a tuple with the Relation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelation `func (o *ReadRequestTupleKey) SetRelation(v string)` SetRelation sets Relation field to given value. ### HasRelation `func (o *ReadRequestTupleKey) HasRelation() bool` HasRelation returns a boolean if a field has been set. ### GetObject `func (o *ReadRequestTupleKey) GetObject() string` GetObject returns the Object field if non-nil, zero value otherwise. ### GetObjectOk `func (o *ReadRequestTupleKey) GetObjectOk() (*string, bool)` GetObjectOk returns a tuple with the Object field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetObject `func (o *ReadRequestTupleKey) SetObject(v string)` SetObject sets Object field to given value. ### HasObject `func (o *ReadRequestTupleKey) HasObject() bool` HasObject returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ReadResponse.md000066400000000000000000000041631456721040100227150ustar00rootroot00000000000000# ReadResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Tuples** | [**[]Tuple**](Tuple.md) | | **ContinuationToken** | **string** | The continuation token will be empty if there are no more tuples. | ## Methods ### NewReadResponse `func NewReadResponse(tuples []Tuple, continuationToken string, ) *ReadResponse` NewReadResponse instantiates a new ReadResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewReadResponseWithDefaults `func NewReadResponseWithDefaults() *ReadResponse` NewReadResponseWithDefaults instantiates a new ReadResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTuples `func (o *ReadResponse) GetTuples() []Tuple` GetTuples returns the Tuples field if non-nil, zero value otherwise. ### GetTuplesOk `func (o *ReadResponse) GetTuplesOk() (*[]Tuple, bool)` GetTuplesOk returns a tuple with the Tuples field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTuples `func (o *ReadResponse) SetTuples(v []Tuple)` SetTuples sets Tuples field to given value. ### GetContinuationToken `func (o *ReadResponse) GetContinuationToken() string` GetContinuationToken returns the ContinuationToken field if non-nil, zero value otherwise. ### GetContinuationTokenOk `func (o *ReadResponse) GetContinuationTokenOk() (*string, bool)` GetContinuationTokenOk returns a tuple with the ContinuationToken field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetContinuationToken `func (o *ReadResponse) SetContinuationToken(v string)` SetContinuationToken sets ContinuationToken field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/RelationMetadata.md000066400000000000000000000036671456721040100235510ustar00rootroot00000000000000# RelationMetadata ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **DirectlyRelatedUserTypes** | Pointer to [**[]RelationReference**](RelationReference.md) | | [optional] ## Methods ### NewRelationMetadata `func NewRelationMetadata() *RelationMetadata` NewRelationMetadata instantiates a new RelationMetadata object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewRelationMetadataWithDefaults `func NewRelationMetadataWithDefaults() *RelationMetadata` NewRelationMetadataWithDefaults instantiates a new RelationMetadata object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetDirectlyRelatedUserTypes `func (o *RelationMetadata) GetDirectlyRelatedUserTypes() []RelationReference` GetDirectlyRelatedUserTypes returns the DirectlyRelatedUserTypes field if non-nil, zero value otherwise. ### GetDirectlyRelatedUserTypesOk `func (o *RelationMetadata) GetDirectlyRelatedUserTypesOk() (*[]RelationReference, bool)` GetDirectlyRelatedUserTypesOk returns a tuple with the DirectlyRelatedUserTypes field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetDirectlyRelatedUserTypes `func (o *RelationMetadata) SetDirectlyRelatedUserTypes(v []RelationReference)` SetDirectlyRelatedUserTypes sets DirectlyRelatedUserTypes field to given value. ### HasDirectlyRelatedUserTypes `func (o *RelationMetadata) HasDirectlyRelatedUserTypes() bool` HasDirectlyRelatedUserTypes returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/RelationReference.md000066400000000000000000000070371456721040100237220ustar00rootroot00000000000000# RelationReference ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Type** | **string** | | **Relation** | Pointer to **string** | | [optional] **Wildcard** | Pointer to **map[string]interface{}** | | [optional] **Condition** | Pointer to **string** | The name of a condition that is enforced over the allowed relation. | [optional] ## Methods ### NewRelationReference `func NewRelationReference(type_ string, ) *RelationReference` NewRelationReference instantiates a new RelationReference object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewRelationReferenceWithDefaults `func NewRelationReferenceWithDefaults() *RelationReference` NewRelationReferenceWithDefaults instantiates a new RelationReference object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetType `func (o *RelationReference) GetType() string` GetType returns the Type field if non-nil, zero value otherwise. ### GetTypeOk `func (o *RelationReference) GetTypeOk() (*string, bool)` GetTypeOk returns a tuple with the Type field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetType `func (o *RelationReference) SetType(v string)` SetType sets Type field to given value. ### GetRelation `func (o *RelationReference) GetRelation() string` GetRelation returns the Relation field if non-nil, zero value otherwise. ### GetRelationOk `func (o *RelationReference) GetRelationOk() (*string, bool)` GetRelationOk returns a tuple with the Relation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelation `func (o *RelationReference) SetRelation(v string)` SetRelation sets Relation field to given value. ### HasRelation `func (o *RelationReference) HasRelation() bool` HasRelation returns a boolean if a field has been set. ### GetWildcard `func (o *RelationReference) GetWildcard() map[string]interface{}` GetWildcard returns the Wildcard field if non-nil, zero value otherwise. ### GetWildcardOk `func (o *RelationReference) GetWildcardOk() (*map[string]interface{}, bool)` GetWildcardOk returns a tuple with the Wildcard field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetWildcard `func (o *RelationReference) SetWildcard(v map[string]interface{})` SetWildcard sets Wildcard field to given value. ### HasWildcard `func (o *RelationReference) HasWildcard() bool` HasWildcard returns a boolean if a field has been set. ### GetCondition `func (o *RelationReference) GetCondition() string` GetCondition returns the Condition field if non-nil, zero value otherwise. ### GetConditionOk `func (o *RelationReference) GetConditionOk() (*string, bool)` GetConditionOk returns a tuple with the Condition field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetCondition `func (o *RelationReference) SetCondition(v string)` SetCondition sets Condition field to given value. ### HasCondition `func (o *RelationReference) HasCondition() bool` HasCondition returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/RelationshipCondition.md000066400000000000000000000047421456721040100246360ustar00rootroot00000000000000# RelationshipCondition ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | A reference (by name) of the relationship condition defined in the authorization model. | **Context** | Pointer to **map[string]interface{}** | Additional context/data to persist along with the condition. The keys must match the parameters defined by the condition, and the value types must match the parameter type definitions. | [optional] ## Methods ### NewRelationshipCondition `func NewRelationshipCondition(name string, ) *RelationshipCondition` NewRelationshipCondition instantiates a new RelationshipCondition object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewRelationshipConditionWithDefaults `func NewRelationshipConditionWithDefaults() *RelationshipCondition` NewRelationshipConditionWithDefaults instantiates a new RelationshipCondition object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetName `func (o *RelationshipCondition) GetName() string` GetName returns the Name field if non-nil, zero value otherwise. ### GetNameOk `func (o *RelationshipCondition) GetNameOk() (*string, bool)` GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetName `func (o *RelationshipCondition) SetName(v string)` SetName sets Name field to given value. ### GetContext `func (o *RelationshipCondition) GetContext() map[string]interface{}` GetContext returns the Context field if non-nil, zero value otherwise. ### GetContextOk `func (o *RelationshipCondition) GetContextOk() (*map[string]interface{}, bool)` GetContextOk returns a tuple with the Context field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetContext `func (o *RelationshipCondition) SetContext(v map[string]interface{})` SetContext sets Context field to given value. ### HasContext `func (o *RelationshipCondition) HasContext() bool` HasContext returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Status.md000066400000000000000000000051171456721040100216060ustar00rootroot00000000000000# Status ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Code** | Pointer to **int32** | | [optional] **Message** | Pointer to **string** | | [optional] **Details** | Pointer to [**[]Any**](Any.md) | | [optional] ## Methods ### NewStatus `func NewStatus() *Status` NewStatus instantiates a new Status object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewStatusWithDefaults `func NewStatusWithDefaults() *Status` NewStatusWithDefaults instantiates a new Status object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetCode `func (o *Status) GetCode() int32` GetCode returns the Code field if non-nil, zero value otherwise. ### GetCodeOk `func (o *Status) GetCodeOk() (*int32, bool)` GetCodeOk returns a tuple with the Code field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetCode `func (o *Status) SetCode(v int32)` SetCode sets Code field to given value. ### HasCode `func (o *Status) HasCode() bool` HasCode returns a boolean if a field has been set. ### GetMessage `func (o *Status) GetMessage() string` GetMessage returns the Message field if non-nil, zero value otherwise. ### GetMessageOk `func (o *Status) GetMessageOk() (*string, bool)` GetMessageOk returns a tuple with the Message field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetMessage `func (o *Status) SetMessage(v string)` SetMessage sets Message field to given value. ### HasMessage `func (o *Status) HasMessage() bool` HasMessage returns a boolean if a field has been set. ### GetDetails `func (o *Status) GetDetails() []Any` GetDetails returns the Details field if non-nil, zero value otherwise. ### GetDetailsOk `func (o *Status) GetDetailsOk() (*[]Any, bool)` GetDetailsOk returns a tuple with the Details field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetDetails `func (o *Status) SetDetails(v []Any)` SetDetails sets Details field to given value. ### HasDetails `func (o *Status) HasDetails() bool` HasDetails returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Store.md000066400000000000000000000065441456721040100214240ustar00rootroot00000000000000# Store ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Id** | **string** | | **Name** | **string** | | **CreatedAt** | **time.Time** | | **UpdatedAt** | **time.Time** | | **DeletedAt** | Pointer to **time.Time** | | [optional] ## Methods ### NewStore `func NewStore(id string, name string, createdAt time.Time, updatedAt time.Time, ) *Store` NewStore instantiates a new Store object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewStoreWithDefaults `func NewStoreWithDefaults() *Store` NewStoreWithDefaults instantiates a new Store object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetId `func (o *Store) GetId() string` GetId returns the Id field if non-nil, zero value otherwise. ### GetIdOk `func (o *Store) GetIdOk() (*string, bool)` GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetId `func (o *Store) SetId(v string)` SetId sets Id field to given value. ### GetName `func (o *Store) GetName() string` GetName returns the Name field if non-nil, zero value otherwise. ### GetNameOk `func (o *Store) GetNameOk() (*string, bool)` GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetName `func (o *Store) SetName(v string)` SetName sets Name field to given value. ### GetCreatedAt `func (o *Store) GetCreatedAt() time.Time` GetCreatedAt returns the CreatedAt field if non-nil, zero value otherwise. ### GetCreatedAtOk `func (o *Store) GetCreatedAtOk() (*time.Time, bool)` GetCreatedAtOk returns a tuple with the CreatedAt field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetCreatedAt `func (o *Store) SetCreatedAt(v time.Time)` SetCreatedAt sets CreatedAt field to given value. ### GetUpdatedAt `func (o *Store) GetUpdatedAt() time.Time` GetUpdatedAt returns the UpdatedAt field if non-nil, zero value otherwise. ### GetUpdatedAtOk `func (o *Store) GetUpdatedAtOk() (*time.Time, bool)` GetUpdatedAtOk returns a tuple with the UpdatedAt field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUpdatedAt `func (o *Store) SetUpdatedAt(v time.Time)` SetUpdatedAt sets UpdatedAt field to given value. ### GetDeletedAt `func (o *Store) GetDeletedAt() time.Time` GetDeletedAt returns the DeletedAt field if non-nil, zero value otherwise. ### GetDeletedAtOk `func (o *Store) GetDeletedAtOk() (*time.Time, bool)` GetDeletedAtOk returns a tuple with the DeletedAt field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetDeletedAt `func (o *Store) SetDeletedAt(v time.Time)` SetDeletedAt sets DeletedAt field to given value. ### HasDeletedAt `func (o *Store) HasDeletedAt() bool` HasDeletedAt returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Tuple.md000066400000000000000000000034701456721040100214140ustar00rootroot00000000000000# Tuple ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Key** | [**TupleKey**](TupleKey.md) | | **Timestamp** | **time.Time** | | ## Methods ### NewTuple `func NewTuple(key TupleKey, timestamp time.Time, ) *Tuple` NewTuple instantiates a new Tuple object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewTupleWithDefaults `func NewTupleWithDefaults() *Tuple` NewTupleWithDefaults instantiates a new Tuple object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetKey `func (o *Tuple) GetKey() TupleKey` GetKey returns the Key field if non-nil, zero value otherwise. ### GetKeyOk `func (o *Tuple) GetKeyOk() (*TupleKey, bool)` GetKeyOk returns a tuple with the Key field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetKey `func (o *Tuple) SetKey(v TupleKey)` SetKey sets Key field to given value. ### GetTimestamp `func (o *Tuple) GetTimestamp() time.Time` GetTimestamp returns the Timestamp field if non-nil, zero value otherwise. ### GetTimestampOk `func (o *Tuple) GetTimestampOk() (*time.Time, bool)` GetTimestampOk returns a tuple with the Timestamp field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTimestamp `func (o *Tuple) SetTimestamp(v time.Time)` SetTimestamp sets Timestamp field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/TupleChange.md000066400000000000000000000051101456721040100225130ustar00rootroot00000000000000# TupleChange ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TupleKey** | [**TupleKey**](TupleKey.md) | | **Operation** | [**TupleOperation**](TupleOperation.md) | | [default to WRITE] **Timestamp** | **time.Time** | | ## Methods ### NewTupleChange `func NewTupleChange(tupleKey TupleKey, operation TupleOperation, timestamp time.Time, ) *TupleChange` NewTupleChange instantiates a new TupleChange object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewTupleChangeWithDefaults `func NewTupleChangeWithDefaults() *TupleChange` NewTupleChangeWithDefaults instantiates a new TupleChange object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTupleKey `func (o *TupleChange) GetTupleKey() TupleKey` GetTupleKey returns the TupleKey field if non-nil, zero value otherwise. ### GetTupleKeyOk `func (o *TupleChange) GetTupleKeyOk() (*TupleKey, bool)` GetTupleKeyOk returns a tuple with the TupleKey field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleKey `func (o *TupleChange) SetTupleKey(v TupleKey)` SetTupleKey sets TupleKey field to given value. ### GetOperation `func (o *TupleChange) GetOperation() TupleOperation` GetOperation returns the Operation field if non-nil, zero value otherwise. ### GetOperationOk `func (o *TupleChange) GetOperationOk() (*TupleOperation, bool)` GetOperationOk returns a tuple with the Operation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetOperation `func (o *TupleChange) SetOperation(v TupleOperation)` SetOperation sets Operation field to given value. ### GetTimestamp `func (o *TupleChange) GetTimestamp() time.Time` GetTimestamp returns the Timestamp field if non-nil, zero value otherwise. ### GetTimestampOk `func (o *TupleChange) GetTimestampOk() (*time.Time, bool)` GetTimestampOk returns a tuple with the Timestamp field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTimestamp `func (o *TupleChange) SetTimestamp(v time.Time)` SetTimestamp sets Timestamp field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/TupleKey.md000066400000000000000000000060011456721040100220560ustar00rootroot00000000000000# TupleKey ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **User** | **string** | | **Relation** | **string** | | **Object** | **string** | | **Condition** | Pointer to [**RelationshipCondition**](RelationshipCondition.md) | | [optional] ## Methods ### NewTupleKey `func NewTupleKey(user string, relation string, object string, ) *TupleKey` NewTupleKey instantiates a new TupleKey object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewTupleKeyWithDefaults `func NewTupleKeyWithDefaults() *TupleKey` NewTupleKeyWithDefaults instantiates a new TupleKey object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetUser `func (o *TupleKey) GetUser() string` GetUser returns the User field if non-nil, zero value otherwise. ### GetUserOk `func (o *TupleKey) GetUserOk() (*string, bool)` GetUserOk returns a tuple with the User field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUser `func (o *TupleKey) SetUser(v string)` SetUser sets User field to given value. ### GetRelation `func (o *TupleKey) GetRelation() string` GetRelation returns the Relation field if non-nil, zero value otherwise. ### GetRelationOk `func (o *TupleKey) GetRelationOk() (*string, bool)` GetRelationOk returns a tuple with the Relation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelation `func (o *TupleKey) SetRelation(v string)` SetRelation sets Relation field to given value. ### GetObject `func (o *TupleKey) GetObject() string` GetObject returns the Object field if non-nil, zero value otherwise. ### GetObjectOk `func (o *TupleKey) GetObjectOk() (*string, bool)` GetObjectOk returns a tuple with the Object field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetObject `func (o *TupleKey) SetObject(v string)` SetObject sets Object field to given value. ### GetCondition `func (o *TupleKey) GetCondition() RelationshipCondition` GetCondition returns the Condition field if non-nil, zero value otherwise. ### GetConditionOk `func (o *TupleKey) GetConditionOk() (*RelationshipCondition, bool)` GetConditionOk returns a tuple with the Condition field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetCondition `func (o *TupleKey) SetCondition(v RelationshipCondition)` SetCondition sets Condition field to given value. ### HasCondition `func (o *TupleKey) HasCondition() bool` HasCondition returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/TupleKeyWithoutCondition.md000066400000000000000000000051451456721040100253210ustar00rootroot00000000000000# TupleKeyWithoutCondition ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **User** | **string** | | **Relation** | **string** | | **Object** | **string** | | ## Methods ### NewTupleKeyWithoutCondition `func NewTupleKeyWithoutCondition(user string, relation string, object string, ) *TupleKeyWithoutCondition` NewTupleKeyWithoutCondition instantiates a new TupleKeyWithoutCondition object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewTupleKeyWithoutConditionWithDefaults `func NewTupleKeyWithoutConditionWithDefaults() *TupleKeyWithoutCondition` NewTupleKeyWithoutConditionWithDefaults instantiates a new TupleKeyWithoutCondition object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetUser `func (o *TupleKeyWithoutCondition) GetUser() string` GetUser returns the User field if non-nil, zero value otherwise. ### GetUserOk `func (o *TupleKeyWithoutCondition) GetUserOk() (*string, bool)` GetUserOk returns a tuple with the User field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUser `func (o *TupleKeyWithoutCondition) SetUser(v string)` SetUser sets User field to given value. ### GetRelation `func (o *TupleKeyWithoutCondition) GetRelation() string` GetRelation returns the Relation field if non-nil, zero value otherwise. ### GetRelationOk `func (o *TupleKeyWithoutCondition) GetRelationOk() (*string, bool)` GetRelationOk returns a tuple with the Relation field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelation `func (o *TupleKeyWithoutCondition) SetRelation(v string)` SetRelation sets Relation field to given value. ### GetObject `func (o *TupleKeyWithoutCondition) GetObject() string` GetObject returns the Object field if non-nil, zero value otherwise. ### GetObjectOk `func (o *TupleKeyWithoutCondition) GetObjectOk() (*string, bool)` GetObjectOk returns a tuple with the Object field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetObject `func (o *TupleKeyWithoutCondition) SetObject(v string)` SetObject sets Object field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/TupleOperation.md000066400000000000000000000004371456721040100232750ustar00rootroot00000000000000# TupleOperation ## Enum * `WRITE` (value: `"TUPLE_OPERATION_WRITE"`) * `DELETE` (value: `"TUPLE_OPERATION_DELETE"`) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/TupleToUserset.md000066400000000000000000000042751456721040100232760ustar00rootroot00000000000000# TupleToUserset ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Tupleset** | [**ObjectRelation**](ObjectRelation.md) | | **ComputedUserset** | [**ObjectRelation**](ObjectRelation.md) | | ## Methods ### NewTupleToUserset `func NewTupleToUserset(tupleset ObjectRelation, computedUserset ObjectRelation, ) *TupleToUserset` NewTupleToUserset instantiates a new TupleToUserset object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewTupleToUsersetWithDefaults `func NewTupleToUsersetWithDefaults() *TupleToUserset` NewTupleToUsersetWithDefaults instantiates a new TupleToUserset object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTupleset `func (o *TupleToUserset) GetTupleset() ObjectRelation` GetTupleset returns the Tupleset field if non-nil, zero value otherwise. ### GetTuplesetOk `func (o *TupleToUserset) GetTuplesetOk() (*ObjectRelation, bool)` GetTuplesetOk returns a tuple with the Tupleset field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleset `func (o *TupleToUserset) SetTupleset(v ObjectRelation)` SetTupleset sets Tupleset field to given value. ### GetComputedUserset `func (o *TupleToUserset) GetComputedUserset() ObjectRelation` GetComputedUserset returns the ComputedUserset field if non-nil, zero value otherwise. ### GetComputedUsersetOk `func (o *TupleToUserset) GetComputedUsersetOk() (*ObjectRelation, bool)` GetComputedUsersetOk returns a tuple with the ComputedUserset field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetComputedUserset `func (o *TupleToUserset) SetComputedUserset(v ObjectRelation)` SetComputedUserset sets ComputedUserset field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/TypeDefinition.md000066400000000000000000000054271456721040100232610ustar00rootroot00000000000000# TypeDefinition ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Type** | **string** | | **Relations** | Pointer to [**map[string]Userset**](Userset.md) | | [optional] **Metadata** | Pointer to [**Metadata**](Metadata.md) | | [optional] ## Methods ### NewTypeDefinition `func NewTypeDefinition(type_ string, ) *TypeDefinition` NewTypeDefinition instantiates a new TypeDefinition object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewTypeDefinitionWithDefaults `func NewTypeDefinitionWithDefaults() *TypeDefinition` NewTypeDefinitionWithDefaults instantiates a new TypeDefinition object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetType `func (o *TypeDefinition) GetType() string` GetType returns the Type field if non-nil, zero value otherwise. ### GetTypeOk `func (o *TypeDefinition) GetTypeOk() (*string, bool)` GetTypeOk returns a tuple with the Type field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetType `func (o *TypeDefinition) SetType(v string)` SetType sets Type field to given value. ### GetRelations `func (o *TypeDefinition) GetRelations() map[string]Userset` GetRelations returns the Relations field if non-nil, zero value otherwise. ### GetRelationsOk `func (o *TypeDefinition) GetRelationsOk() (*map[string]Userset, bool)` GetRelationsOk returns a tuple with the Relations field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRelations `func (o *TypeDefinition) SetRelations(v map[string]Userset)` SetRelations sets Relations field to given value. ### HasRelations `func (o *TypeDefinition) HasRelations() bool` HasRelations returns a boolean if a field has been set. ### GetMetadata `func (o *TypeDefinition) GetMetadata() Metadata` GetMetadata returns the Metadata field if non-nil, zero value otherwise. ### GetMetadataOk `func (o *TypeDefinition) GetMetadataOk() (*Metadata, bool)` GetMetadataOk returns a tuple with the Metadata field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetMetadata `func (o *TypeDefinition) SetMetadata(v Metadata)` SetMetadata sets Metadata field to given value. ### HasMetadata `func (o *TypeDefinition) HasMetadata() bool` HasMetadata returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/TypeName.md000066400000000000000000000012571456721040100220460ustar00rootroot00000000000000# TypeName ## Enum * `UNSPECIFIED` (value: `"TYPE_NAME_UNSPECIFIED"`) * `ANY` (value: `"TYPE_NAME_ANY"`) * `BOOL` (value: `"TYPE_NAME_BOOL"`) * `STRING` (value: `"TYPE_NAME_STRING"`) * `INT` (value: `"TYPE_NAME_INT"`) * `UINT` (value: `"TYPE_NAME_UINT"`) * `DOUBLE` (value: `"TYPE_NAME_DOUBLE"`) * `DURATION` (value: `"TYPE_NAME_DURATION"`) * `TIMESTAMP` (value: `"TYPE_NAME_TIMESTAMP"`) * `MAP` (value: `"TYPE_NAME_MAP"`) * `LIST` (value: `"TYPE_NAME_LIST"`) * `IPADDRESS` (value: `"TYPE_NAME_IPADDRESS"`) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Users.md000066400000000000000000000024631456721040100214250ustar00rootroot00000000000000# Users ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Users** | **[]string** | | ## Methods ### NewUsers `func NewUsers(users []string, ) *Users` NewUsers instantiates a new Users object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewUsersWithDefaults `func NewUsersWithDefaults() *Users` NewUsersWithDefaults instantiates a new Users object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetUsers `func (o *Users) GetUsers() []string` GetUsers returns the Users field if non-nil, zero value otherwise. ### GetUsersOk `func (o *Users) GetUsersOk() (*[]string, bool)` GetUsersOk returns a tuple with the Users field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUsers `func (o *Users) SetUsers(v []string)` SetUsers sets Users field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Userset.md000066400000000000000000000120761456721040100217570ustar00rootroot00000000000000# Userset ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **This** | Pointer to **map[string]interface{}** | A DirectUserset is a sentinel message for referencing the direct members specified by an object/relation mapping. | [optional] **ComputedUserset** | Pointer to [**ObjectRelation**](ObjectRelation.md) | | [optional] **TupleToUserset** | Pointer to [**TupleToUserset**](TupleToUserset.md) | | [optional] **Union** | Pointer to [**Usersets**](Usersets.md) | | [optional] **Intersection** | Pointer to [**Usersets**](Usersets.md) | | [optional] **Difference** | Pointer to [**Difference**](Difference.md) | | [optional] ## Methods ### NewUserset `func NewUserset() *Userset` NewUserset instantiates a new Userset object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewUsersetWithDefaults `func NewUsersetWithDefaults() *Userset` NewUsersetWithDefaults instantiates a new Userset object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetThis `func (o *Userset) GetThis() map[string]interface{}` GetThis returns the This field if non-nil, zero value otherwise. ### GetThisOk `func (o *Userset) GetThisOk() (*map[string]interface{}, bool)` GetThisOk returns a tuple with the This field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetThis `func (o *Userset) SetThis(v map[string]interface{})` SetThis sets This field to given value. ### HasThis `func (o *Userset) HasThis() bool` HasThis returns a boolean if a field has been set. ### GetComputedUserset `func (o *Userset) GetComputedUserset() ObjectRelation` GetComputedUserset returns the ComputedUserset field if non-nil, zero value otherwise. ### GetComputedUsersetOk `func (o *Userset) GetComputedUsersetOk() (*ObjectRelation, bool)` GetComputedUsersetOk returns a tuple with the ComputedUserset field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetComputedUserset `func (o *Userset) SetComputedUserset(v ObjectRelation)` SetComputedUserset sets ComputedUserset field to given value. ### HasComputedUserset `func (o *Userset) HasComputedUserset() bool` HasComputedUserset returns a boolean if a field has been set. ### GetTupleToUserset `func (o *Userset) GetTupleToUserset() TupleToUserset` GetTupleToUserset returns the TupleToUserset field if non-nil, zero value otherwise. ### GetTupleToUsersetOk `func (o *Userset) GetTupleToUsersetOk() (*TupleToUserset, bool)` GetTupleToUsersetOk returns a tuple with the TupleToUserset field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleToUserset `func (o *Userset) SetTupleToUserset(v TupleToUserset)` SetTupleToUserset sets TupleToUserset field to given value. ### HasTupleToUserset `func (o *Userset) HasTupleToUserset() bool` HasTupleToUserset returns a boolean if a field has been set. ### GetUnion `func (o *Userset) GetUnion() Usersets` GetUnion returns the Union field if non-nil, zero value otherwise. ### GetUnionOk `func (o *Userset) GetUnionOk() (*Usersets, bool)` GetUnionOk returns a tuple with the Union field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetUnion `func (o *Userset) SetUnion(v Usersets)` SetUnion sets Union field to given value. ### HasUnion `func (o *Userset) HasUnion() bool` HasUnion returns a boolean if a field has been set. ### GetIntersection `func (o *Userset) GetIntersection() Usersets` GetIntersection returns the Intersection field if non-nil, zero value otherwise. ### GetIntersectionOk `func (o *Userset) GetIntersectionOk() (*Usersets, bool)` GetIntersectionOk returns a tuple with the Intersection field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetIntersection `func (o *Userset) SetIntersection(v Usersets)` SetIntersection sets Intersection field to given value. ### HasIntersection `func (o *Userset) HasIntersection() bool` HasIntersection returns a boolean if a field has been set. ### GetDifference `func (o *Userset) GetDifference() Difference` GetDifference returns the Difference field if non-nil, zero value otherwise. ### GetDifferenceOk `func (o *Userset) GetDifferenceOk() (*Difference, bool)` GetDifferenceOk returns a tuple with the Difference field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetDifference `func (o *Userset) SetDifference(v Difference)` SetDifference sets Difference field to given value. ### HasDifference `func (o *Userset) HasDifference() bool` HasDifference returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/UsersetTree.md000066400000000000000000000027431456721040100225770ustar00rootroot00000000000000# UsersetTree ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Root** | Pointer to [**Node**](Node.md) | | [optional] ## Methods ### NewUsersetTree `func NewUsersetTree() *UsersetTree` NewUsersetTree instantiates a new UsersetTree object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewUsersetTreeWithDefaults `func NewUsersetTreeWithDefaults() *UsersetTree` NewUsersetTreeWithDefaults instantiates a new UsersetTree object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetRoot `func (o *UsersetTree) GetRoot() Node` GetRoot returns the Root field if non-nil, zero value otherwise. ### GetRootOk `func (o *UsersetTree) GetRootOk() (*Node, bool)` GetRootOk returns a tuple with the Root field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetRoot `func (o *UsersetTree) SetRoot(v Node)` SetRoot sets Root field to given value. ### HasRoot `func (o *UsersetTree) HasRoot() bool` HasRoot returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/UsersetTreeDifference.md000066400000000000000000000040421456721040100245440ustar00rootroot00000000000000# UsersetTreeDifference ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Base** | [**Node**](Node.md) | | **Subtract** | [**Node**](Node.md) | | ## Methods ### NewUsersetTreeDifference `func NewUsersetTreeDifference(base Node, subtract Node, ) *UsersetTreeDifference` NewUsersetTreeDifference instantiates a new UsersetTreeDifference object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewUsersetTreeDifferenceWithDefaults `func NewUsersetTreeDifferenceWithDefaults() *UsersetTreeDifference` NewUsersetTreeDifferenceWithDefaults instantiates a new UsersetTreeDifference object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetBase `func (o *UsersetTreeDifference) GetBase() Node` GetBase returns the Base field if non-nil, zero value otherwise. ### GetBaseOk `func (o *UsersetTreeDifference) GetBaseOk() (*Node, bool)` GetBaseOk returns a tuple with the Base field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetBase `func (o *UsersetTreeDifference) SetBase(v Node)` SetBase sets Base field to given value. ### GetSubtract `func (o *UsersetTreeDifference) GetSubtract() Node` GetSubtract returns the Subtract field if non-nil, zero value otherwise. ### GetSubtractOk `func (o *UsersetTreeDifference) GetSubtractOk() (*Node, bool)` GetSubtractOk returns a tuple with the Subtract field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetSubtract `func (o *UsersetTreeDifference) SetSubtract(v Node)` SetSubtract sets Subtract field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/UsersetTreeTupleToUserset.md000066400000000000000000000042771456721040100254730ustar00rootroot00000000000000# UsersetTreeTupleToUserset ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Tupleset** | **string** | | **Computed** | [**[]Computed**](Computed.md) | | ## Methods ### NewUsersetTreeTupleToUserset `func NewUsersetTreeTupleToUserset(tupleset string, computed []Computed, ) *UsersetTreeTupleToUserset` NewUsersetTreeTupleToUserset instantiates a new UsersetTreeTupleToUserset object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewUsersetTreeTupleToUsersetWithDefaults `func NewUsersetTreeTupleToUsersetWithDefaults() *UsersetTreeTupleToUserset` NewUsersetTreeTupleToUsersetWithDefaults instantiates a new UsersetTreeTupleToUserset object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTupleset `func (o *UsersetTreeTupleToUserset) GetTupleset() string` GetTupleset returns the Tupleset field if non-nil, zero value otherwise. ### GetTuplesetOk `func (o *UsersetTreeTupleToUserset) GetTuplesetOk() (*string, bool)` GetTuplesetOk returns a tuple with the Tupleset field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleset `func (o *UsersetTreeTupleToUserset) SetTupleset(v string)` SetTupleset sets Tupleset field to given value. ### GetComputed `func (o *UsersetTreeTupleToUserset) GetComputed() []Computed` GetComputed returns the Computed field if non-nil, zero value otherwise. ### GetComputedOk `func (o *UsersetTreeTupleToUserset) GetComputedOk() (*[]Computed, bool)` GetComputedOk returns a tuple with the Computed field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetComputed `func (o *UsersetTreeTupleToUserset) SetComputed(v []Computed)` SetComputed sets Computed field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/Usersets.md000066400000000000000000000025601456721040100221370ustar00rootroot00000000000000# Usersets ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Child** | [**[]Userset**](Userset.md) | | ## Methods ### NewUsersets `func NewUsersets(child []Userset, ) *Usersets` NewUsersets instantiates a new Usersets object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewUsersetsWithDefaults `func NewUsersetsWithDefaults() *Usersets` NewUsersetsWithDefaults instantiates a new Usersets object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetChild `func (o *Usersets) GetChild() []Userset` GetChild returns the Child field if non-nil, zero value otherwise. ### GetChildOk `func (o *Usersets) GetChildOk() (*[]Userset, bool)` GetChildOk returns a tuple with the Child field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetChild `func (o *Usersets) SetChild(v []Userset)` SetChild sets Child field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/ValidationErrorMessageResponse.md000066400000000000000000000047521456721040100264570ustar00rootroot00000000000000# ValidationErrorMessageResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Code** | Pointer to [**ErrorCode**](ErrorCode.md) | | [optional] [default to NO_ERROR] **Message** | Pointer to **string** | | [optional] ## Methods ### NewValidationErrorMessageResponse `func NewValidationErrorMessageResponse() *ValidationErrorMessageResponse` NewValidationErrorMessageResponse instantiates a new ValidationErrorMessageResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewValidationErrorMessageResponseWithDefaults `func NewValidationErrorMessageResponseWithDefaults() *ValidationErrorMessageResponse` NewValidationErrorMessageResponseWithDefaults instantiates a new ValidationErrorMessageResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetCode `func (o *ValidationErrorMessageResponse) GetCode() ErrorCode` GetCode returns the Code field if non-nil, zero value otherwise. ### GetCodeOk `func (o *ValidationErrorMessageResponse) GetCodeOk() (*ErrorCode, bool)` GetCodeOk returns a tuple with the Code field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetCode `func (o *ValidationErrorMessageResponse) SetCode(v ErrorCode)` SetCode sets Code field to given value. ### HasCode `func (o *ValidationErrorMessageResponse) HasCode() bool` HasCode returns a boolean if a field has been set. ### GetMessage `func (o *ValidationErrorMessageResponse) GetMessage() string` GetMessage returns the Message field if non-nil, zero value otherwise. ### GetMessageOk `func (o *ValidationErrorMessageResponse) GetMessageOk() (*string, bool)` GetMessageOk returns a tuple with the Message field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetMessage `func (o *ValidationErrorMessageResponse) SetMessage(v string)` SetMessage sets Message field to given value. ### HasMessage `func (o *ValidationErrorMessageResponse) HasMessage() bool` HasMessage returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/WriteAssertionsRequest.md000066400000000000000000000032061456721040100250360ustar00rootroot00000000000000# WriteAssertionsRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Assertions** | [**[]Assertion**](Assertion.md) | | ## Methods ### NewWriteAssertionsRequest `func NewWriteAssertionsRequest(assertions []Assertion, ) *WriteAssertionsRequest` NewWriteAssertionsRequest instantiates a new WriteAssertionsRequest object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewWriteAssertionsRequestWithDefaults `func NewWriteAssertionsRequestWithDefaults() *WriteAssertionsRequest` NewWriteAssertionsRequestWithDefaults instantiates a new WriteAssertionsRequest object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetAssertions `func (o *WriteAssertionsRequest) GetAssertions() []Assertion` GetAssertions returns the Assertions field if non-nil, zero value otherwise. ### GetAssertionsOk `func (o *WriteAssertionsRequest) GetAssertionsOk() (*[]Assertion, bool)` GetAssertionsOk returns a tuple with the Assertions field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAssertions `func (o *WriteAssertionsRequest) SetAssertions(v []Assertion)` SetAssertions sets Assertions field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/WriteAuthorizationModelRequest.md000066400000000000000000000064241456721040100265320ustar00rootroot00000000000000# WriteAuthorizationModelRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TypeDefinitions** | [**[]TypeDefinition**](TypeDefinition.md) | | **SchemaVersion** | **string** | | **Conditions** | Pointer to [**map[string]Condition**](Condition.md) | | [optional] ## Methods ### NewWriteAuthorizationModelRequest `func NewWriteAuthorizationModelRequest(typeDefinitions []TypeDefinition, schemaVersion string, ) *WriteAuthorizationModelRequest` NewWriteAuthorizationModelRequest instantiates a new WriteAuthorizationModelRequest object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewWriteAuthorizationModelRequestWithDefaults `func NewWriteAuthorizationModelRequestWithDefaults() *WriteAuthorizationModelRequest` NewWriteAuthorizationModelRequestWithDefaults instantiates a new WriteAuthorizationModelRequest object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTypeDefinitions `func (o *WriteAuthorizationModelRequest) GetTypeDefinitions() []TypeDefinition` GetTypeDefinitions returns the TypeDefinitions field if non-nil, zero value otherwise. ### GetTypeDefinitionsOk `func (o *WriteAuthorizationModelRequest) GetTypeDefinitionsOk() (*[]TypeDefinition, bool)` GetTypeDefinitionsOk returns a tuple with the TypeDefinitions field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTypeDefinitions `func (o *WriteAuthorizationModelRequest) SetTypeDefinitions(v []TypeDefinition)` SetTypeDefinitions sets TypeDefinitions field to given value. ### GetSchemaVersion `func (o *WriteAuthorizationModelRequest) GetSchemaVersion() string` GetSchemaVersion returns the SchemaVersion field if non-nil, zero value otherwise. ### GetSchemaVersionOk `func (o *WriteAuthorizationModelRequest) GetSchemaVersionOk() (*string, bool)` GetSchemaVersionOk returns a tuple with the SchemaVersion field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetSchemaVersion `func (o *WriteAuthorizationModelRequest) SetSchemaVersion(v string)` SetSchemaVersion sets SchemaVersion field to given value. ### GetConditions `func (o *WriteAuthorizationModelRequest) GetConditions() map[string]Condition` GetConditions returns the Conditions field if non-nil, zero value otherwise. ### GetConditionsOk `func (o *WriteAuthorizationModelRequest) GetConditionsOk() (*map[string]Condition, bool)` GetConditionsOk returns a tuple with the Conditions field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetConditions `func (o *WriteAuthorizationModelRequest) SetConditions(v map[string]Condition)` SetConditions sets Conditions field to given value. ### HasConditions `func (o *WriteAuthorizationModelRequest) HasConditions() bool` HasConditions returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/WriteAuthorizationModelResponse.md000066400000000000000000000035471456721040100267030ustar00rootroot00000000000000# WriteAuthorizationModelResponse ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **AuthorizationModelId** | **string** | | ## Methods ### NewWriteAuthorizationModelResponse `func NewWriteAuthorizationModelResponse(authorizationModelId string, ) *WriteAuthorizationModelResponse` NewWriteAuthorizationModelResponse instantiates a new WriteAuthorizationModelResponse object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewWriteAuthorizationModelResponseWithDefaults `func NewWriteAuthorizationModelResponseWithDefaults() *WriteAuthorizationModelResponse` NewWriteAuthorizationModelResponseWithDefaults instantiates a new WriteAuthorizationModelResponse object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetAuthorizationModelId `func (o *WriteAuthorizationModelResponse) GetAuthorizationModelId() string` GetAuthorizationModelId returns the AuthorizationModelId field if non-nil, zero value otherwise. ### GetAuthorizationModelIdOk `func (o *WriteAuthorizationModelResponse) GetAuthorizationModelIdOk() (*string, bool)` GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAuthorizationModelId `func (o *WriteAuthorizationModelResponse) SetAuthorizationModelId(v string)` SetAuthorizationModelId sets AuthorizationModelId field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/WriteRequest.md000066400000000000000000000061361456721040100227700ustar00rootroot00000000000000# WriteRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Writes** | Pointer to [**WriteRequestWrites**](WriteRequestWrites.md) | | [optional] **Deletes** | Pointer to [**WriteRequestDeletes**](WriteRequestDeletes.md) | | [optional] **AuthorizationModelId** | Pointer to **string** | | [optional] ## Methods ### NewWriteRequest `func NewWriteRequest() *WriteRequest` NewWriteRequest instantiates a new WriteRequest object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewWriteRequestWithDefaults `func NewWriteRequestWithDefaults() *WriteRequest` NewWriteRequestWithDefaults instantiates a new WriteRequest object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetWrites `func (o *WriteRequest) GetWrites() WriteRequestWrites` GetWrites returns the Writes field if non-nil, zero value otherwise. ### GetWritesOk `func (o *WriteRequest) GetWritesOk() (*WriteRequestWrites, bool)` GetWritesOk returns a tuple with the Writes field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetWrites `func (o *WriteRequest) SetWrites(v WriteRequestWrites)` SetWrites sets Writes field to given value. ### HasWrites `func (o *WriteRequest) HasWrites() bool` HasWrites returns a boolean if a field has been set. ### GetDeletes `func (o *WriteRequest) GetDeletes() WriteRequestDeletes` GetDeletes returns the Deletes field if non-nil, zero value otherwise. ### GetDeletesOk `func (o *WriteRequest) GetDeletesOk() (*WriteRequestDeletes, bool)` GetDeletesOk returns a tuple with the Deletes field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetDeletes `func (o *WriteRequest) SetDeletes(v WriteRequestDeletes)` SetDeletes sets Deletes field to given value. ### HasDeletes `func (o *WriteRequest) HasDeletes() bool` HasDeletes returns a boolean if a field has been set. ### GetAuthorizationModelId `func (o *WriteRequest) GetAuthorizationModelId() string` GetAuthorizationModelId returns the AuthorizationModelId field if non-nil, zero value otherwise. ### GetAuthorizationModelIdOk `func (o *WriteRequest) GetAuthorizationModelIdOk() (*string, bool)` GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetAuthorizationModelId `func (o *WriteRequest) SetAuthorizationModelId(v string)` SetAuthorizationModelId sets AuthorizationModelId field to given value. ### HasAuthorizationModelId `func (o *WriteRequest) HasAuthorizationModelId() bool` HasAuthorizationModelId returns a boolean if a field has been set. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/WriteRequestDeletes.md000066400000000000000000000032501456721040100242700ustar00rootroot00000000000000# WriteRequestDeletes ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TupleKeys** | [**[]TupleKeyWithoutCondition**](TupleKeyWithoutCondition.md) | | ## Methods ### NewWriteRequestDeletes `func NewWriteRequestDeletes(tupleKeys []TupleKeyWithoutCondition, ) *WriteRequestDeletes` NewWriteRequestDeletes instantiates a new WriteRequestDeletes object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewWriteRequestDeletesWithDefaults `func NewWriteRequestDeletesWithDefaults() *WriteRequestDeletes` NewWriteRequestDeletesWithDefaults instantiates a new WriteRequestDeletes object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTupleKeys `func (o *WriteRequestDeletes) GetTupleKeys() []TupleKeyWithoutCondition` GetTupleKeys returns the TupleKeys field if non-nil, zero value otherwise. ### GetTupleKeysOk `func (o *WriteRequestDeletes) GetTupleKeysOk() (*[]TupleKeyWithoutCondition, bool)` GetTupleKeysOk returns a tuple with the TupleKeys field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleKeys `func (o *WriteRequestDeletes) SetTupleKeys(v []TupleKeyWithoutCondition)` SetTupleKeys sets TupleKeys field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/docs/WriteRequestWrites.md000066400000000000000000000030721456721040100241620ustar00rootroot00000000000000# WriteRequestWrites ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **TupleKeys** | [**[]TupleKey**](TupleKey.md) | | ## Methods ### NewWriteRequestWrites `func NewWriteRequestWrites(tupleKeys []TupleKey, ) *WriteRequestWrites` NewWriteRequestWrites instantiates a new WriteRequestWrites object This constructor will assign default values to properties that have it defined, and makes sure properties required by API are set, but the set of arguments will change when the set of required properties is changed ### NewWriteRequestWritesWithDefaults `func NewWriteRequestWritesWithDefaults() *WriteRequestWrites` NewWriteRequestWritesWithDefaults instantiates a new WriteRequestWrites object This constructor will only assign default values to properties that have it defined, but it doesn't guarantee that properties required by API are set ### GetTupleKeys `func (o *WriteRequestWrites) GetTupleKeys() []TupleKey` GetTupleKeys returns the TupleKeys field if non-nil, zero value otherwise. ### GetTupleKeysOk `func (o *WriteRequestWrites) GetTupleKeysOk() (*[]TupleKey, bool)` GetTupleKeysOk returns a tuple with the TupleKeys field if it's non-nil, zero value otherwise and a boolean to check if the value has been set. ### SetTupleKeys `func (o *WriteRequestWrites) SetTupleKeys(v []TupleKey)` SetTupleKeys sets TupleKeys field to given value. [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) golang-github-openfga-go-sdk-0.3.5/example/000077500000000000000000000000001456721040100205005ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/example/Makefile000066400000000000000000000004371456721040100221440ustar00rootroot00000000000000all: run project_name=example1 openfga_version=latest restore: go mod tidy run: restore go run ${project_name}/${project_name}.go run-openfga: docker pull docker.io/openfga/openfga:${openfga_version} && \ docker run -p 8080:8080 docker.io/openfga/openfga:${openfga_version} run golang-github-openfga-go-sdk-0.3.5/example/README.md000066400000000000000000000022521456721040100217600ustar00rootroot00000000000000## Examples of using the OpenFGA Go SDK A set of examples on how to call the OpenFGA Go SDK ### Examples Example 1: A bare bones example. It creates a store, and runs a set of calls against it including creating a model, writing tuples and checking for access. ### Running the Examples Prerequisites: - `docker` - `make` - `go` 1.20+ #### Run using a published SDK Steps 1. Clone/Copy the example folder 2. If you have an OpenFGA server running, you can use it, otherwise run `make run-openfga` to spin up an instance (you'll need to switch to a different terminal after - don't forget to close it when done) 3. Run `make run` to run the example #### Run using a local unpublished SDK build Steps 1. Build the SDK 2. In the Example `go.mod`, uncomment out the part that replaces the remote SDK with the local one, e.g. ``` // To refrence local build, uncomment below and run `go mod tidy` replace github.com/openfga/go-sdk v0.3.2 => ../../ ``` 3. If you have an OpenFGA server running, you can use it, otherwise run `make run-openfga` to spin up an instance (you'll need to switch to a different terminal after - don't forget to close it when done) 4. Run `make run` to run the examplegolang-github-openfga-go-sdk-0.3.5/example/example1/000077500000000000000000000000001456721040100222145ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/example/example1/example1.go000066400000000000000000000171501456721040100242630ustar00rootroot00000000000000package main import ( "context" "fmt" openfga "github.com/openfga/go-sdk" "github.com/openfga/go-sdk/client" "github.com/openfga/go-sdk/credentials" "os" ) func mainInner() error { ctx := context.Background() creds := credentials.Credentials{} if os.Getenv("FGA_CLIENT_ID") != "" { creds = credentials.Credentials{ Method: credentials.CredentialsMethodClientCredentials, Config: &credentials.Config{ ClientCredentialsClientId: os.Getenv("FGA_CLIENT_ID"), ClientCredentialsClientSecret: os.Getenv("FGA_CLIENT_SECRET"), ClientCredentialsApiAudience: os.Getenv("FGA_API_AUDIENCE"), ClientCredentialsApiTokenIssuer: os.Getenv("FGA_API_TOKEN_ISSUER"), }, } } apiUrl := os.Getenv("FGA_API_URL") if apiUrl == "" { apiUrl = "http://localhost:8080" } fgaClient, err := client.NewSdkClient(&client.ClientConfiguration{ ApiUrl: apiUrl, StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores` AuthorizationModelId: os.Getenv("FGA_AUTHORIZATION_MODEL_ID"), // optional, recommended to be set for production Credentials: &creds, }) if err != nil { return err } // ListStores fmt.Println("Listing Stores") stores1, err := fgaClient.ListStores(ctx).Execute() if err != nil { return err } fmt.Printf("Stores Count: %d\n", len(stores1.GetStores())) // CreateStore fmt.Println("Creating Test Store") store, err := fgaClient.CreateStore(ctx).Body(client.ClientCreateStoreRequest{Name: "Test Store"}).Execute() if err != nil { return err } fmt.Printf("Test Store ID: %v\n", store.Id) // Set the store id fgaClient.SetStoreId(store.Id) // ListStores after Create fmt.Println("Listing Stores") stores, err := fgaClient.ListStores(ctx).Execute() if err != nil { return err } fmt.Printf("Stores Count: %d\n", len(stores.Stores)) // GetStore fmt.Println("Getting Current Store") currentStore, err := fgaClient.GetStore(ctx).Execute() if err != nil { return err } fmt.Println("Current Store Name: %v\n" + currentStore.Name) // ReadAuthorizationModels fmt.Println("Reading Authorization Models") models, err := fgaClient.ReadAuthorizationModels(ctx).Execute() if err != nil { return err } fmt.Printf("Models Count: %d\n", len(models.AuthorizationModels)) // ReadLatestAuthorizationModel latestAuthorizationModel, err := fgaClient.ReadLatestAuthorizationModel(ctx).Execute() if err != nil { return err } if latestAuthorizationModel.AuthorizationModel != nil { fmt.Printf("Latest Authorization Model ID: %v\n", (*latestAuthorizationModel.AuthorizationModel).Id) } else { fmt.Println("Latest Authorization Model not found") } // WriteAuthorizationModel fmt.Println("Writing an Authorization Model") body := client.ClientWriteAuthorizationModelRequest{ SchemaVersion: "1.1", TypeDefinitions: []openfga.TypeDefinition{ { Type: "user", Relations: &map[string]openfga.Userset{}, }, { Type: "document", Relations: &map[string]openfga.Userset{ "writer": {This: &map[string]interface{}{}}, "viewer": {Union: &openfga.Usersets{ Child: []openfga.Userset{ {This: &map[string]interface{}{}}, {ComputedUserset: &openfga.ObjectRelation{ Object: openfga.PtrString(""), Relation: openfga.PtrString("writer"), }}, }, }}, }, Metadata: &openfga.Metadata{ Relations: &map[string]openfga.RelationMetadata{ "writer": { DirectlyRelatedUserTypes: &[]openfga.RelationReference{ {Type: "user"}, {Type: "user", Condition: openfga.PtrString("ViewCountLessThan200")}, }, }, "viewer": { DirectlyRelatedUserTypes: &[]openfga.RelationReference{ {Type: "user"}, }, }, }, }, }, }, Conditions: &map[string]openfga.Condition{ "ViewCountLessThan200": { Name: "ViewCountLessThan200", Expression: "ViewCount < 200", Parameters: &map[string]openfga.ConditionParamTypeRef{ "ViewCount": { TypeName: openfga.INT, }, "Type": { TypeName: openfga.STRING, }, "Name": { TypeName: openfga.STRING, }, }, }, }, } authorizationModel, err := fgaClient.WriteAuthorizationModel(ctx).Body(body).Execute() if err != nil { return err } fmt.Printf("Authorization Model ID: %v\n", authorizationModel.AuthorizationModelId) // ReadAuthorizationModels - after Write fmt.Println("Reading Authorization Models") models, err = fgaClient.ReadAuthorizationModels(ctx).Execute() if err != nil { return err } fmt.Printf("Models Count: %d\n", len(models.AuthorizationModels)) // ReadLatestAuthorizationModel - after Write latestAuthorizationModel, err = fgaClient.ReadLatestAuthorizationModel(ctx).Execute() if err != nil { return err } fmt.Printf("Latest Authorization Model ID: %v\n", (*latestAuthorizationModel.AuthorizationModel).Id) // Write fmt.Println("Writing Tuples") _, err = fgaClient.Write(ctx).Body(client.ClientWriteRequest{ Writes: []client.ClientTupleKey{ { User: "user:anne", Relation: "writer", Object: "document:roadmap", Condition: &openfga.RelationshipCondition{ Name: "ViewCountLessThan200", Context: &map[string]interface{}{"Name": "Roadmap", "Type": "document"}, }, }, }, }).Options(client.ClientWriteOptions{ AuthorizationModelId: &authorizationModel.AuthorizationModelId, }).Execute() if err != nil { return err } fmt.Println("Done Writing Tuples") // Set the model ID err = fgaClient.SetAuthorizationModelId(latestAuthorizationModel.AuthorizationModel.Id) if err != nil { return err } // Read fmt.Println("Reading Tuples") readTuples, err := fgaClient.Read(ctx).Execute() if err != nil { return err } fmt.Printf("Read Tuples: %v\n", readTuples) // ReadChanges fmt.Println("Reading Tuple Changes") readChangesTuples, err := fgaClient.ReadChanges(ctx).Execute() if err != nil { return err } fmt.Printf("Read Changes Tuples: %v\n", readChangesTuples) // Check fmt.Println("Checking for access") failingCheckResponse, err := fgaClient.Check(ctx).Body(client.ClientCheckRequest{ User: "user:anne", Relation: "viewer", Object: "document:roadmap", }).Execute() if err != nil { fmt.Printf("Failed due to: %w\n", err.Error()) } else { fmt.Printf("Allowed: %v\n", failingCheckResponse.Allowed) } // Checking for access with context fmt.Println("Checking for access with context") checkResponse, err := fgaClient.Check(ctx).Body(client.ClientCheckRequest{ User: "user:anne", Relation: "viewer", Object: "document:roadmap", Context: &map[string]interface{}{"ViewCount": 100}, }).Execute() if err != nil { return err } fmt.Printf("Allowed: %v\n", checkResponse.Allowed) // WriteAssertions _, err = fgaClient.WriteAssertions(ctx).Body([]client.ClientAssertion{ { User: "user:carl", Relation: "writer", Object: "document:budget", Expectation: true, }, { User: "user:anne", Relation: "viewer", Object: "document:roadmap", Expectation: false, }, }).Execute() if err != nil { return err } fmt.Println("Assertions updated") // ReadAssertions fmt.Println("Reading Assertions") assertions, err := fgaClient.ReadAssertions(ctx).Execute() if err != nil { return err } fmt.Printf("Assertions: %v\n", assertions) // DeleteStore fmt.Println("Deleting Current Store") _, err = fgaClient.DeleteStore(ctx).Execute() if err != nil { return err } fmt.Printf("Deleted Store: %v\n", currentStore.Name) return nil } func main() { if err := mainInner(); err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } } golang-github-openfga-go-sdk-0.3.5/example/example1/go.mod000066400000000000000000000003511456721040100233210ustar00rootroot00000000000000module example1 go 1.20 require github.com/openfga/go-sdk v0.3.5 require golang.org/x/sync v0.6.0 // indirect // To reference local build, uncomment below and run `go mod tidy` //replace github.com/openfga/go-sdk v0.3.5 => ../../golang-github-openfga-go-sdk-0.3.5/example/example1/go.sum000066400000000000000000000006251456721040100233520ustar00rootroot00000000000000github.com/jarcoal/httpmock v1.3.1 h1:iUx3whfZWVf3jT01hQTO/Eo5sAYtB2/rqaUuOtpInww= github.com/openfga/go-sdk v0.3.3 h1:eMZGCEDW/sz9S3gNxbpO5rNpDezz7cjT+zwjpDgqTt0= github.com/openfga/go-sdk v0.3.3/go.mod h1:W4SNYMSxptGOtA9aGYxsYUmSC7LaZYP7y9qbT36ouCc= golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang-github-openfga-go-sdk-0.3.5/go.mod000066400000000000000000000001651456721040100201550ustar00rootroot00000000000000module github.com/openfga/go-sdk go 1.20 require ( github.com/jarcoal/httpmock v1.3.1 golang.org/x/sync v0.6.0 ) golang-github-openfga-go-sdk-0.3.5/go.sum000066400000000000000000000007601456721040100202030ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/jarcoal/httpmock v1.3.1 h1:iUx3whfZWVf3jT01hQTO/Eo5sAYtB2/rqaUuOtpInww= github.com/jarcoal/httpmock v1.3.1/go.mod h1:3yb8rc4BI7TCBhFY8ng0gjuLKJNquuDNiPaZjnENuYg= github.com/maxatome/go-testdeep v1.12.0 h1:Ql7Go8Tg0C1D/uMMX59LAoYK7LffeJQ6X2T04nTH68g= golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang-github-openfga-go-sdk-0.3.5/internal/000077500000000000000000000000001456721040100206615ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/internal/utils/000077500000000000000000000000001456721040100220215ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/internal/utils/randomtime.go000066400000000000000000000012511456721040100245060ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package internalutils import ( _math "math" _rand "math/rand" ) // RandomTime provides a randomized time func RandomTime(loopCount int, minWaitInMs int) int { min := int(_math.Pow(2, float64(loopCount))) * minWaitInMs max := int(_math.Pow(2, float64(loopCount+1))) * minWaitInMs return _rand.Intn(max-min+1) + min } golang-github-openfga-go-sdk-0.3.5/internal/utils/ulid.go000066400000000000000000000013241456721040100233050ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package internalutils import ( "regexp" ) // cUlidRegex contains the regex for valid ULID const cUlidRegex = "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" // IsWellFormedUlidString returns whethr the ulidString is a properly formatted ulid string func IsWellFormedUlidString(ulidString string) bool { re := regexp.MustCompile(cUlidRegex) return re.MatchString(ulidString) } golang-github-openfga-go-sdk-0.3.5/internal/utils/ulid_test.go000066400000000000000000000023661456721040100243530ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package internalutils import ( "testing" ) func TestIsWellFormedUlidString(t *testing.T) { tests := []struct { name string input string isValid bool }{ { name: "valid_ulid", input: "01GRC27AM72M4SGK4VBHF3DY0F", isValid: true, }, { name: "invalid_symbols", input: "01GRC27AM72M4S$^4VBHF3DY0F", isValid: false, }, { name: "not_start_in_0-7", input: "A1GRC27AM72M4SGK4VBHF3DY0F", isValid: false, }, { name: "too_long", input: "01GRC27AM72M4SGK4VBHF3DY0FA", isValid: false, }, { name: "too_short", input: "01GRC27AM72M4SGK4VBHF3DY0", isValid: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { isValid := IsWellFormedUlidString(test.input) if isValid != test.isValid { t.Errorf("Expect %s to be valid %v actual %v", test.input, test.isValid, isValid) } }) } } golang-github-openfga-go-sdk-0.3.5/model_aborted_message_response.go000066400000000000000000000103451456721040100256210ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // AbortedMessageResponse struct for AbortedMessageResponse type AbortedMessageResponse struct { Code *string `json:"code,omitempty"yaml:"code,omitempty"` Message *string `json:"message,omitempty"yaml:"message,omitempty"` } // NewAbortedMessageResponse instantiates a new AbortedMessageResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewAbortedMessageResponse() *AbortedMessageResponse { this := AbortedMessageResponse{} return &this } // NewAbortedMessageResponseWithDefaults instantiates a new AbortedMessageResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewAbortedMessageResponseWithDefaults() *AbortedMessageResponse { this := AbortedMessageResponse{} return &this } // GetCode returns the Code field value if set, zero value otherwise. func (o *AbortedMessageResponse) GetCode() string { if o == nil || o.Code == nil { var ret string return ret } return *o.Code } // GetCodeOk returns a tuple with the Code field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AbortedMessageResponse) GetCodeOk() (*string, bool) { if o == nil || o.Code == nil { return nil, false } return o.Code, true } // HasCode returns a boolean if a field has been set. func (o *AbortedMessageResponse) HasCode() bool { if o != nil && o.Code != nil { return true } return false } // SetCode gets a reference to the given string and assigns it to the Code field. func (o *AbortedMessageResponse) SetCode(v string) { o.Code = &v } // GetMessage returns the Message field value if set, zero value otherwise. func (o *AbortedMessageResponse) GetMessage() string { if o == nil || o.Message == nil { var ret string return ret } return *o.Message } // GetMessageOk returns a tuple with the Message field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AbortedMessageResponse) GetMessageOk() (*string, bool) { if o == nil || o.Message == nil { return nil, false } return o.Message, true } // HasMessage returns a boolean if a field has been set. func (o *AbortedMessageResponse) HasMessage() bool { if o != nil && o.Message != nil { return true } return false } // SetMessage gets a reference to the given string and assigns it to the Message field. func (o *AbortedMessageResponse) SetMessage(v string) { o.Message = &v } func (o AbortedMessageResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Code != nil { toSerialize["code"] = o.Code } if o.Message != nil { toSerialize["message"] = o.Message } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableAbortedMessageResponse struct { value *AbortedMessageResponse isSet bool } func (v NullableAbortedMessageResponse) Get() *AbortedMessageResponse { return v.value } func (v *NullableAbortedMessageResponse) Set(val *AbortedMessageResponse) { v.value = val v.isSet = true } func (v NullableAbortedMessageResponse) IsSet() bool { return v.isSet } func (v *NullableAbortedMessageResponse) Unset() { v.value = nil v.isSet = false } func NewNullableAbortedMessageResponse(val *AbortedMessageResponse) *NullableAbortedMessageResponse { return &NullableAbortedMessageResponse{value: val, isSet: true} } func (v NullableAbortedMessageResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableAbortedMessageResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_any.go000066400000000000000000000052571456721040100213540ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Any struct for Any type Any struct { Type *string `json:"@type,omitempty"yaml:"@type,omitempty"` } // NewAny instantiates a new Any object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewAny() *Any { this := Any{} return &this } // NewAnyWithDefaults instantiates a new Any object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewAnyWithDefaults() *Any { this := Any{} return &this } // GetType returns the Type field value if set, zero value otherwise. func (o *Any) GetType() string { if o == nil || o.Type == nil { var ret string return ret } return *o.Type } // GetTypeOk returns a tuple with the Type field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Any) GetTypeOk() (*string, bool) { if o == nil || o.Type == nil { return nil, false } return o.Type, true } // HasType returns a boolean if a field has been set. func (o *Any) HasType() bool { if o != nil && o.Type != nil { return true } return false } // SetType gets a reference to the given string and assigns it to the Type field. func (o *Any) SetType(v string) { o.Type = &v } func (o Any) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Type != nil { toSerialize["@type"] = o.Type } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableAny struct { value *Any isSet bool } func (v NullableAny) Get() *Any { return v.value } func (v *NullableAny) Set(val *Any) { v.value = val v.isSet = true } func (v NullableAny) IsSet() bool { return v.isSet } func (v *NullableAny) Unset() { v.value = nil v.isSet = false } func NewNullableAny(val *Any) *NullableAny { return &NullableAny{value: val, isSet: true} } func (v NullableAny) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableAny) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_assertion.go000066400000000000000000000065611456721040100225730ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Assertion struct for Assertion type Assertion struct { TupleKey AssertionTupleKey `json:"tuple_key"yaml:"tuple_key"` Expectation bool `json:"expectation"yaml:"expectation"` } // NewAssertion instantiates a new Assertion object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewAssertion(tupleKey AssertionTupleKey, expectation bool) *Assertion { this := Assertion{} this.TupleKey = tupleKey this.Expectation = expectation return &this } // NewAssertionWithDefaults instantiates a new Assertion object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewAssertionWithDefaults() *Assertion { this := Assertion{} return &this } // GetTupleKey returns the TupleKey field value func (o *Assertion) GetTupleKey() AssertionTupleKey { if o == nil { var ret AssertionTupleKey return ret } return o.TupleKey } // GetTupleKeyOk returns a tuple with the TupleKey field value // and a boolean to check if the value has been set. func (o *Assertion) GetTupleKeyOk() (*AssertionTupleKey, bool) { if o == nil { return nil, false } return &o.TupleKey, true } // SetTupleKey sets field value func (o *Assertion) SetTupleKey(v AssertionTupleKey) { o.TupleKey = v } // GetExpectation returns the Expectation field value func (o *Assertion) GetExpectation() bool { if o == nil { var ret bool return ret } return o.Expectation } // GetExpectationOk returns a tuple with the Expectation field value // and a boolean to check if the value has been set. func (o *Assertion) GetExpectationOk() (*bool, bool) { if o == nil { return nil, false } return &o.Expectation, true } // SetExpectation sets field value func (o *Assertion) SetExpectation(v bool) { o.Expectation = v } func (o Assertion) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tuple_key"] = o.TupleKey toSerialize["expectation"] = o.Expectation var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableAssertion struct { value *Assertion isSet bool } func (v NullableAssertion) Get() *Assertion { return v.value } func (v *NullableAssertion) Set(val *Assertion) { v.value = val v.isSet = true } func (v NullableAssertion) IsSet() bool { return v.isSet } func (v *NullableAssertion) Unset() { v.value = nil v.isSet = false } func NewNullableAssertion(val *Assertion) *NullableAssertion { return &NullableAssertion{value: val, isSet: true} } func (v NullableAssertion) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableAssertion) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_assertion_tuple_key.go000066400000000000000000000100341456721040100246420ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // AssertionTupleKey struct for AssertionTupleKey type AssertionTupleKey struct { Object string `json:"object"yaml:"object"` Relation string `json:"relation"yaml:"relation"` User string `json:"user"yaml:"user"` } // NewAssertionTupleKey instantiates a new AssertionTupleKey object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewAssertionTupleKey(object string, relation string, user string) *AssertionTupleKey { this := AssertionTupleKey{} this.Object = object this.Relation = relation this.User = user return &this } // NewAssertionTupleKeyWithDefaults instantiates a new AssertionTupleKey object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewAssertionTupleKeyWithDefaults() *AssertionTupleKey { this := AssertionTupleKey{} return &this } // GetObject returns the Object field value func (o *AssertionTupleKey) GetObject() string { if o == nil { var ret string return ret } return o.Object } // GetObjectOk returns a tuple with the Object field value // and a boolean to check if the value has been set. func (o *AssertionTupleKey) GetObjectOk() (*string, bool) { if o == nil { return nil, false } return &o.Object, true } // SetObject sets field value func (o *AssertionTupleKey) SetObject(v string) { o.Object = v } // GetRelation returns the Relation field value func (o *AssertionTupleKey) GetRelation() string { if o == nil { var ret string return ret } return o.Relation } // GetRelationOk returns a tuple with the Relation field value // and a boolean to check if the value has been set. func (o *AssertionTupleKey) GetRelationOk() (*string, bool) { if o == nil { return nil, false } return &o.Relation, true } // SetRelation sets field value func (o *AssertionTupleKey) SetRelation(v string) { o.Relation = v } // GetUser returns the User field value func (o *AssertionTupleKey) GetUser() string { if o == nil { var ret string return ret } return o.User } // GetUserOk returns a tuple with the User field value // and a boolean to check if the value has been set. func (o *AssertionTupleKey) GetUserOk() (*string, bool) { if o == nil { return nil, false } return &o.User, true } // SetUser sets field value func (o *AssertionTupleKey) SetUser(v string) { o.User = v } func (o AssertionTupleKey) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["object"] = o.Object toSerialize["relation"] = o.Relation toSerialize["user"] = o.User var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableAssertionTupleKey struct { value *AssertionTupleKey isSet bool } func (v NullableAssertionTupleKey) Get() *AssertionTupleKey { return v.value } func (v *NullableAssertionTupleKey) Set(val *AssertionTupleKey) { v.value = val v.isSet = true } func (v NullableAssertionTupleKey) IsSet() bool { return v.isSet } func (v *NullableAssertionTupleKey) Unset() { v.value = nil v.isSet = false } func NewNullableAssertionTupleKey(val *AssertionTupleKey) *NullableAssertionTupleKey { return &NullableAssertionTupleKey{value: val, isSet: true} } func (v NullableAssertionTupleKey) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableAssertionTupleKey) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_authorization_model.go000066400000000000000000000127671456721040100246510ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // AuthorizationModel struct for AuthorizationModel type AuthorizationModel struct { Id string `json:"id"yaml:"id"` SchemaVersion string `json:"schema_version"yaml:"schema_version"` TypeDefinitions []TypeDefinition `json:"type_definitions"yaml:"type_definitions"` Conditions *map[string]Condition `json:"conditions,omitempty"yaml:"conditions,omitempty"` } // NewAuthorizationModel instantiates a new AuthorizationModel object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewAuthorizationModel(id string, schemaVersion string, typeDefinitions []TypeDefinition) *AuthorizationModel { this := AuthorizationModel{} this.Id = id this.SchemaVersion = schemaVersion this.TypeDefinitions = typeDefinitions return &this } // NewAuthorizationModelWithDefaults instantiates a new AuthorizationModel object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewAuthorizationModelWithDefaults() *AuthorizationModel { this := AuthorizationModel{} return &this } // GetId returns the Id field value func (o *AuthorizationModel) GetId() string { if o == nil { var ret string return ret } return o.Id } // GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. func (o *AuthorizationModel) GetIdOk() (*string, bool) { if o == nil { return nil, false } return &o.Id, true } // SetId sets field value func (o *AuthorizationModel) SetId(v string) { o.Id = v } // GetSchemaVersion returns the SchemaVersion field value func (o *AuthorizationModel) GetSchemaVersion() string { if o == nil { var ret string return ret } return o.SchemaVersion } // GetSchemaVersionOk returns a tuple with the SchemaVersion field value // and a boolean to check if the value has been set. func (o *AuthorizationModel) GetSchemaVersionOk() (*string, bool) { if o == nil { return nil, false } return &o.SchemaVersion, true } // SetSchemaVersion sets field value func (o *AuthorizationModel) SetSchemaVersion(v string) { o.SchemaVersion = v } // GetTypeDefinitions returns the TypeDefinitions field value func (o *AuthorizationModel) GetTypeDefinitions() []TypeDefinition { if o == nil { var ret []TypeDefinition return ret } return o.TypeDefinitions } // GetTypeDefinitionsOk returns a tuple with the TypeDefinitions field value // and a boolean to check if the value has been set. func (o *AuthorizationModel) GetTypeDefinitionsOk() (*[]TypeDefinition, bool) { if o == nil { return nil, false } return &o.TypeDefinitions, true } // SetTypeDefinitions sets field value func (o *AuthorizationModel) SetTypeDefinitions(v []TypeDefinition) { o.TypeDefinitions = v } // GetConditions returns the Conditions field value if set, zero value otherwise. func (o *AuthorizationModel) GetConditions() map[string]Condition { if o == nil || o.Conditions == nil { var ret map[string]Condition return ret } return *o.Conditions } // GetConditionsOk returns a tuple with the Conditions field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AuthorizationModel) GetConditionsOk() (*map[string]Condition, bool) { if o == nil || o.Conditions == nil { return nil, false } return o.Conditions, true } // HasConditions returns a boolean if a field has been set. func (o *AuthorizationModel) HasConditions() bool { if o != nil && o.Conditions != nil { return true } return false } // SetConditions gets a reference to the given map[string]Condition and assigns it to the Conditions field. func (o *AuthorizationModel) SetConditions(v map[string]Condition) { o.Conditions = &v } func (o AuthorizationModel) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["id"] = o.Id toSerialize["schema_version"] = o.SchemaVersion toSerialize["type_definitions"] = o.TypeDefinitions if o.Conditions != nil { toSerialize["conditions"] = o.Conditions } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableAuthorizationModel struct { value *AuthorizationModel isSet bool } func (v NullableAuthorizationModel) Get() *AuthorizationModel { return v.value } func (v *NullableAuthorizationModel) Set(val *AuthorizationModel) { v.value = val v.isSet = true } func (v NullableAuthorizationModel) IsSet() bool { return v.isSet } func (v *NullableAuthorizationModel) Unset() { v.value = nil v.isSet = false } func NewNullableAuthorizationModel(val *AuthorizationModel) *NullableAuthorizationModel { return &NullableAuthorizationModel{value: val, isSet: true} } func (v NullableAuthorizationModel) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableAuthorizationModel) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_check_request.go000066400000000000000000000164701456721040100234110ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // CheckRequest struct for CheckRequest type CheckRequest struct { TupleKey CheckRequestTupleKey `json:"tuple_key"yaml:"tuple_key"` ContextualTuples *ContextualTupleKeys `json:"contextual_tuples,omitempty"yaml:"contextual_tuples,omitempty"` AuthorizationModelId *string `json:"authorization_model_id,omitempty"yaml:"authorization_model_id,omitempty"` // Defaults to false. Making it true has performance implications. Trace *bool `json:"trace,omitempty"yaml:"trace,omitempty"` // Additional request context that will be used to evaluate any ABAC conditions encountered in the query evaluation. Context *map[string]interface{} `json:"context,omitempty"yaml:"context,omitempty"` } // NewCheckRequest instantiates a new CheckRequest object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewCheckRequest(tupleKey CheckRequestTupleKey) *CheckRequest { this := CheckRequest{} this.TupleKey = tupleKey return &this } // NewCheckRequestWithDefaults instantiates a new CheckRequest object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewCheckRequestWithDefaults() *CheckRequest { this := CheckRequest{} return &this } // GetTupleKey returns the TupleKey field value func (o *CheckRequest) GetTupleKey() CheckRequestTupleKey { if o == nil { var ret CheckRequestTupleKey return ret } return o.TupleKey } // GetTupleKeyOk returns a tuple with the TupleKey field value // and a boolean to check if the value has been set. func (o *CheckRequest) GetTupleKeyOk() (*CheckRequestTupleKey, bool) { if o == nil { return nil, false } return &o.TupleKey, true } // SetTupleKey sets field value func (o *CheckRequest) SetTupleKey(v CheckRequestTupleKey) { o.TupleKey = v } // GetContextualTuples returns the ContextualTuples field value if set, zero value otherwise. func (o *CheckRequest) GetContextualTuples() ContextualTupleKeys { if o == nil || o.ContextualTuples == nil { var ret ContextualTupleKeys return ret } return *o.ContextualTuples } // GetContextualTuplesOk returns a tuple with the ContextualTuples field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CheckRequest) GetContextualTuplesOk() (*ContextualTupleKeys, bool) { if o == nil || o.ContextualTuples == nil { return nil, false } return o.ContextualTuples, true } // HasContextualTuples returns a boolean if a field has been set. func (o *CheckRequest) HasContextualTuples() bool { if o != nil && o.ContextualTuples != nil { return true } return false } // SetContextualTuples gets a reference to the given ContextualTupleKeys and assigns it to the ContextualTuples field. func (o *CheckRequest) SetContextualTuples(v ContextualTupleKeys) { o.ContextualTuples = &v } // GetAuthorizationModelId returns the AuthorizationModelId field value if set, zero value otherwise. func (o *CheckRequest) GetAuthorizationModelId() string { if o == nil || o.AuthorizationModelId == nil { var ret string return ret } return *o.AuthorizationModelId } // GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CheckRequest) GetAuthorizationModelIdOk() (*string, bool) { if o == nil || o.AuthorizationModelId == nil { return nil, false } return o.AuthorizationModelId, true } // HasAuthorizationModelId returns a boolean if a field has been set. func (o *CheckRequest) HasAuthorizationModelId() bool { if o != nil && o.AuthorizationModelId != nil { return true } return false } // SetAuthorizationModelId gets a reference to the given string and assigns it to the AuthorizationModelId field. func (o *CheckRequest) SetAuthorizationModelId(v string) { o.AuthorizationModelId = &v } // GetTrace returns the Trace field value if set, zero value otherwise. func (o *CheckRequest) GetTrace() bool { if o == nil || o.Trace == nil { var ret bool return ret } return *o.Trace } // GetTraceOk returns a tuple with the Trace field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CheckRequest) GetTraceOk() (*bool, bool) { if o == nil || o.Trace == nil { return nil, false } return o.Trace, true } // HasTrace returns a boolean if a field has been set. func (o *CheckRequest) HasTrace() bool { if o != nil && o.Trace != nil { return true } return false } // SetTrace gets a reference to the given bool and assigns it to the Trace field. func (o *CheckRequest) SetTrace(v bool) { o.Trace = &v } // GetContext returns the Context field value if set, zero value otherwise. func (o *CheckRequest) GetContext() map[string]interface{} { if o == nil || o.Context == nil { var ret map[string]interface{} return ret } return *o.Context } // GetContextOk returns a tuple with the Context field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CheckRequest) GetContextOk() (*map[string]interface{}, bool) { if o == nil || o.Context == nil { return nil, false } return o.Context, true } // HasContext returns a boolean if a field has been set. func (o *CheckRequest) HasContext() bool { if o != nil && o.Context != nil { return true } return false } // SetContext gets a reference to the given map[string]interface{} and assigns it to the Context field. func (o *CheckRequest) SetContext(v map[string]interface{}) { o.Context = &v } func (o CheckRequest) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tuple_key"] = o.TupleKey if o.ContextualTuples != nil { toSerialize["contextual_tuples"] = o.ContextualTuples } if o.AuthorizationModelId != nil { toSerialize["authorization_model_id"] = o.AuthorizationModelId } if o.Trace != nil { toSerialize["trace"] = o.Trace } if o.Context != nil { toSerialize["context"] = o.Context } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableCheckRequest struct { value *CheckRequest isSet bool } func (v NullableCheckRequest) Get() *CheckRequest { return v.value } func (v *NullableCheckRequest) Set(val *CheckRequest) { v.value = val v.isSet = true } func (v NullableCheckRequest) IsSet() bool { return v.isSet } func (v *NullableCheckRequest) Unset() { v.value = nil v.isSet = false } func NewNullableCheckRequest(val *CheckRequest) *NullableCheckRequest { return &NullableCheckRequest{value: val, isSet: true} } func (v NullableCheckRequest) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableCheckRequest) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_check_request_tuple_key.go000066400000000000000000000102131456721040100254570ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // CheckRequestTupleKey struct for CheckRequestTupleKey type CheckRequestTupleKey struct { User string `json:"user"yaml:"user"` Relation string `json:"relation"yaml:"relation"` Object string `json:"object"yaml:"object"` } // NewCheckRequestTupleKey instantiates a new CheckRequestTupleKey object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewCheckRequestTupleKey(user string, relation string, object string) *CheckRequestTupleKey { this := CheckRequestTupleKey{} this.User = user this.Relation = relation this.Object = object return &this } // NewCheckRequestTupleKeyWithDefaults instantiates a new CheckRequestTupleKey object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewCheckRequestTupleKeyWithDefaults() *CheckRequestTupleKey { this := CheckRequestTupleKey{} return &this } // GetUser returns the User field value func (o *CheckRequestTupleKey) GetUser() string { if o == nil { var ret string return ret } return o.User } // GetUserOk returns a tuple with the User field value // and a boolean to check if the value has been set. func (o *CheckRequestTupleKey) GetUserOk() (*string, bool) { if o == nil { return nil, false } return &o.User, true } // SetUser sets field value func (o *CheckRequestTupleKey) SetUser(v string) { o.User = v } // GetRelation returns the Relation field value func (o *CheckRequestTupleKey) GetRelation() string { if o == nil { var ret string return ret } return o.Relation } // GetRelationOk returns a tuple with the Relation field value // and a boolean to check if the value has been set. func (o *CheckRequestTupleKey) GetRelationOk() (*string, bool) { if o == nil { return nil, false } return &o.Relation, true } // SetRelation sets field value func (o *CheckRequestTupleKey) SetRelation(v string) { o.Relation = v } // GetObject returns the Object field value func (o *CheckRequestTupleKey) GetObject() string { if o == nil { var ret string return ret } return o.Object } // GetObjectOk returns a tuple with the Object field value // and a boolean to check if the value has been set. func (o *CheckRequestTupleKey) GetObjectOk() (*string, bool) { if o == nil { return nil, false } return &o.Object, true } // SetObject sets field value func (o *CheckRequestTupleKey) SetObject(v string) { o.Object = v } func (o CheckRequestTupleKey) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["user"] = o.User toSerialize["relation"] = o.Relation toSerialize["object"] = o.Object var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableCheckRequestTupleKey struct { value *CheckRequestTupleKey isSet bool } func (v NullableCheckRequestTupleKey) Get() *CheckRequestTupleKey { return v.value } func (v *NullableCheckRequestTupleKey) Set(val *CheckRequestTupleKey) { v.value = val v.isSet = true } func (v NullableCheckRequestTupleKey) IsSet() bool { return v.isSet } func (v *NullableCheckRequestTupleKey) Unset() { v.value = nil v.isSet = false } func NewNullableCheckRequestTupleKey(val *CheckRequestTupleKey) *NullableCheckRequestTupleKey { return &NullableCheckRequestTupleKey{value: val, isSet: true} } func (v NullableCheckRequestTupleKey) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableCheckRequestTupleKey) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_check_response.go000066400000000000000000000100671456721040100235530ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // CheckResponse struct for CheckResponse type CheckResponse struct { Allowed *bool `json:"allowed,omitempty"yaml:"allowed,omitempty"` // For internal use only. Resolution *string `json:"resolution,omitempty"yaml:"resolution,omitempty"` } // NewCheckResponse instantiates a new CheckResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewCheckResponse() *CheckResponse { this := CheckResponse{} return &this } // NewCheckResponseWithDefaults instantiates a new CheckResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewCheckResponseWithDefaults() *CheckResponse { this := CheckResponse{} return &this } // GetAllowed returns the Allowed field value if set, zero value otherwise. func (o *CheckResponse) GetAllowed() bool { if o == nil || o.Allowed == nil { var ret bool return ret } return *o.Allowed } // GetAllowedOk returns a tuple with the Allowed field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CheckResponse) GetAllowedOk() (*bool, bool) { if o == nil || o.Allowed == nil { return nil, false } return o.Allowed, true } // HasAllowed returns a boolean if a field has been set. func (o *CheckResponse) HasAllowed() bool { if o != nil && o.Allowed != nil { return true } return false } // SetAllowed gets a reference to the given bool and assigns it to the Allowed field. func (o *CheckResponse) SetAllowed(v bool) { o.Allowed = &v } // GetResolution returns the Resolution field value if set, zero value otherwise. func (o *CheckResponse) GetResolution() string { if o == nil || o.Resolution == nil { var ret string return ret } return *o.Resolution } // GetResolutionOk returns a tuple with the Resolution field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CheckResponse) GetResolutionOk() (*string, bool) { if o == nil || o.Resolution == nil { return nil, false } return o.Resolution, true } // HasResolution returns a boolean if a field has been set. func (o *CheckResponse) HasResolution() bool { if o != nil && o.Resolution != nil { return true } return false } // SetResolution gets a reference to the given string and assigns it to the Resolution field. func (o *CheckResponse) SetResolution(v string) { o.Resolution = &v } func (o CheckResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Allowed != nil { toSerialize["allowed"] = o.Allowed } if o.Resolution != nil { toSerialize["resolution"] = o.Resolution } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableCheckResponse struct { value *CheckResponse isSet bool } func (v NullableCheckResponse) Get() *CheckResponse { return v.value } func (v *NullableCheckResponse) Set(val *CheckResponse) { v.value = val v.isSet = true } func (v NullableCheckResponse) IsSet() bool { return v.isSet } func (v *NullableCheckResponse) Unset() { v.value = nil v.isSet = false } func NewNullableCheckResponse(val *CheckResponse) *NullableCheckResponse { return &NullableCheckResponse{value: val, isSet: true} } func (v NullableCheckResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableCheckResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_computed.go000066400000000000000000000051141456721040100223750ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Computed struct for Computed type Computed struct { Userset string `json:"userset"yaml:"userset"` } // NewComputed instantiates a new Computed object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewComputed(userset string) *Computed { this := Computed{} this.Userset = userset return &this } // NewComputedWithDefaults instantiates a new Computed object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewComputedWithDefaults() *Computed { this := Computed{} return &this } // GetUserset returns the Userset field value func (o *Computed) GetUserset() string { if o == nil { var ret string return ret } return o.Userset } // GetUsersetOk returns a tuple with the Userset field value // and a boolean to check if the value has been set. func (o *Computed) GetUsersetOk() (*string, bool) { if o == nil { return nil, false } return &o.Userset, true } // SetUserset sets field value func (o *Computed) SetUserset(v string) { o.Userset = v } func (o Computed) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["userset"] = o.Userset var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableComputed struct { value *Computed isSet bool } func (v NullableComputed) Get() *Computed { return v.value } func (v *NullableComputed) Set(val *Computed) { v.value = val v.isSet = true } func (v NullableComputed) IsSet() bool { return v.isSet } func (v *NullableComputed) Unset() { v.value = nil v.isSet = false } func NewNullableComputed(val *Computed) *NullableComputed { return &NullableComputed{value: val, isSet: true} } func (v NullableComputed) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableComputed) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_condition.go000066400000000000000000000107101456721040100225410ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Condition struct for Condition type Condition struct { Name string `json:"name"yaml:"name"` // A Google CEL expression, expressed as a string. Expression string `json:"expression"yaml:"expression"` // A map of parameter names to the parameter's defined type reference. Parameters *map[string]ConditionParamTypeRef `json:"parameters,omitempty"yaml:"parameters,omitempty"` } // NewCondition instantiates a new Condition object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewCondition(name string, expression string) *Condition { this := Condition{} this.Name = name this.Expression = expression return &this } // NewConditionWithDefaults instantiates a new Condition object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewConditionWithDefaults() *Condition { this := Condition{} return &this } // GetName returns the Name field value func (o *Condition) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *Condition) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *Condition) SetName(v string) { o.Name = v } // GetExpression returns the Expression field value func (o *Condition) GetExpression() string { if o == nil { var ret string return ret } return o.Expression } // GetExpressionOk returns a tuple with the Expression field value // and a boolean to check if the value has been set. func (o *Condition) GetExpressionOk() (*string, bool) { if o == nil { return nil, false } return &o.Expression, true } // SetExpression sets field value func (o *Condition) SetExpression(v string) { o.Expression = v } // GetParameters returns the Parameters field value if set, zero value otherwise. func (o *Condition) GetParameters() map[string]ConditionParamTypeRef { if o == nil || o.Parameters == nil { var ret map[string]ConditionParamTypeRef return ret } return *o.Parameters } // GetParametersOk returns a tuple with the Parameters field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Condition) GetParametersOk() (*map[string]ConditionParamTypeRef, bool) { if o == nil || o.Parameters == nil { return nil, false } return o.Parameters, true } // HasParameters returns a boolean if a field has been set. func (o *Condition) HasParameters() bool { if o != nil && o.Parameters != nil { return true } return false } // SetParameters gets a reference to the given map[string]ConditionParamTypeRef and assigns it to the Parameters field. func (o *Condition) SetParameters(v map[string]ConditionParamTypeRef) { o.Parameters = &v } func (o Condition) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["name"] = o.Name toSerialize["expression"] = o.Expression if o.Parameters != nil { toSerialize["parameters"] = o.Parameters } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableCondition struct { value *Condition isSet bool } func (v NullableCondition) Get() *Condition { return v.value } func (v *NullableCondition) Set(val *Condition) { v.value = val v.isSet = true } func (v NullableCondition) IsSet() bool { return v.isSet } func (v *NullableCondition) Unset() { v.value = nil v.isSet = false } func NewNullableCondition(val *Condition) *NullableCondition { return &NullableCondition{value: val, isSet: true} } func (v NullableCondition) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableCondition) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_condition_param_type_ref.go000066400000000000000000000104021456721040100256140ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ConditionParamTypeRef struct for ConditionParamTypeRef type ConditionParamTypeRef struct { TypeName TypeName `json:"type_name"yaml:"type_name"` GenericTypes *[]ConditionParamTypeRef `json:"generic_types,omitempty"yaml:"generic_types,omitempty"` } // NewConditionParamTypeRef instantiates a new ConditionParamTypeRef object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewConditionParamTypeRef(typeName TypeName) *ConditionParamTypeRef { this := ConditionParamTypeRef{} this.TypeName = typeName return &this } // NewConditionParamTypeRefWithDefaults instantiates a new ConditionParamTypeRef object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewConditionParamTypeRefWithDefaults() *ConditionParamTypeRef { this := ConditionParamTypeRef{} var typeName TypeName = UNSPECIFIED this.TypeName = typeName return &this } // GetTypeName returns the TypeName field value func (o *ConditionParamTypeRef) GetTypeName() TypeName { if o == nil { var ret TypeName return ret } return o.TypeName } // GetTypeNameOk returns a tuple with the TypeName field value // and a boolean to check if the value has been set. func (o *ConditionParamTypeRef) GetTypeNameOk() (*TypeName, bool) { if o == nil { return nil, false } return &o.TypeName, true } // SetTypeName sets field value func (o *ConditionParamTypeRef) SetTypeName(v TypeName) { o.TypeName = v } // GetGenericTypes returns the GenericTypes field value if set, zero value otherwise. func (o *ConditionParamTypeRef) GetGenericTypes() []ConditionParamTypeRef { if o == nil || o.GenericTypes == nil { var ret []ConditionParamTypeRef return ret } return *o.GenericTypes } // GetGenericTypesOk returns a tuple with the GenericTypes field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ConditionParamTypeRef) GetGenericTypesOk() (*[]ConditionParamTypeRef, bool) { if o == nil || o.GenericTypes == nil { return nil, false } return o.GenericTypes, true } // HasGenericTypes returns a boolean if a field has been set. func (o *ConditionParamTypeRef) HasGenericTypes() bool { if o != nil && o.GenericTypes != nil { return true } return false } // SetGenericTypes gets a reference to the given []ConditionParamTypeRef and assigns it to the GenericTypes field. func (o *ConditionParamTypeRef) SetGenericTypes(v []ConditionParamTypeRef) { o.GenericTypes = &v } func (o ConditionParamTypeRef) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["type_name"] = o.TypeName if o.GenericTypes != nil { toSerialize["generic_types"] = o.GenericTypes } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableConditionParamTypeRef struct { value *ConditionParamTypeRef isSet bool } func (v NullableConditionParamTypeRef) Get() *ConditionParamTypeRef { return v.value } func (v *NullableConditionParamTypeRef) Set(val *ConditionParamTypeRef) { v.value = val v.isSet = true } func (v NullableConditionParamTypeRef) IsSet() bool { return v.isSet } func (v *NullableConditionParamTypeRef) Unset() { v.value = nil v.isSet = false } func NewNullableConditionParamTypeRef(val *ConditionParamTypeRef) *NullableConditionParamTypeRef { return &NullableConditionParamTypeRef{value: val, isSet: true} } func (v NullableConditionParamTypeRef) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableConditionParamTypeRef) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_contextual_tuple_keys.go000066400000000000000000000057421456721040100252160ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ContextualTupleKeys struct for ContextualTupleKeys type ContextualTupleKeys struct { TupleKeys []TupleKey `json:"tuple_keys"yaml:"tuple_keys"` } // NewContextualTupleKeys instantiates a new ContextualTupleKeys object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewContextualTupleKeys(tupleKeys []TupleKey) *ContextualTupleKeys { this := ContextualTupleKeys{} this.TupleKeys = tupleKeys return &this } // NewContextualTupleKeysWithDefaults instantiates a new ContextualTupleKeys object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewContextualTupleKeysWithDefaults() *ContextualTupleKeys { this := ContextualTupleKeys{} return &this } // GetTupleKeys returns the TupleKeys field value func (o *ContextualTupleKeys) GetTupleKeys() []TupleKey { if o == nil { var ret []TupleKey return ret } return o.TupleKeys } // GetTupleKeysOk returns a tuple with the TupleKeys field value // and a boolean to check if the value has been set. func (o *ContextualTupleKeys) GetTupleKeysOk() (*[]TupleKey, bool) { if o == nil { return nil, false } return &o.TupleKeys, true } // SetTupleKeys sets field value func (o *ContextualTupleKeys) SetTupleKeys(v []TupleKey) { o.TupleKeys = v } func (o ContextualTupleKeys) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tuple_keys"] = o.TupleKeys var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableContextualTupleKeys struct { value *ContextualTupleKeys isSet bool } func (v NullableContextualTupleKeys) Get() *ContextualTupleKeys { return v.value } func (v *NullableContextualTupleKeys) Set(val *ContextualTupleKeys) { v.value = val v.isSet = true } func (v NullableContextualTupleKeys) IsSet() bool { return v.isSet } func (v *NullableContextualTupleKeys) Unset() { v.value = nil v.isSet = false } func NewNullableContextualTupleKeys(val *ContextualTupleKeys) *NullableContextualTupleKeys { return &NullableContextualTupleKeys{value: val, isSet: true} } func (v NullableContextualTupleKeys) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableContextualTupleKeys) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_create_store_request.go000066400000000000000000000055111456721040100250050ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // CreateStoreRequest struct for CreateStoreRequest type CreateStoreRequest struct { Name string `json:"name"yaml:"name"` } // NewCreateStoreRequest instantiates a new CreateStoreRequest object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewCreateStoreRequest(name string) *CreateStoreRequest { this := CreateStoreRequest{} this.Name = name return &this } // NewCreateStoreRequestWithDefaults instantiates a new CreateStoreRequest object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewCreateStoreRequestWithDefaults() *CreateStoreRequest { this := CreateStoreRequest{} return &this } // GetName returns the Name field value func (o *CreateStoreRequest) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *CreateStoreRequest) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *CreateStoreRequest) SetName(v string) { o.Name = v } func (o CreateStoreRequest) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["name"] = o.Name var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableCreateStoreRequest struct { value *CreateStoreRequest isSet bool } func (v NullableCreateStoreRequest) Get() *CreateStoreRequest { return v.value } func (v *NullableCreateStoreRequest) Set(val *CreateStoreRequest) { v.value = val v.isSet = true } func (v NullableCreateStoreRequest) IsSet() bool { return v.isSet } func (v *NullableCreateStoreRequest) Unset() { v.value = nil v.isSet = false } func NewNullableCreateStoreRequest(val *CreateStoreRequest) *NullableCreateStoreRequest { return &NullableCreateStoreRequest{value: val, isSet: true} } func (v NullableCreateStoreRequest) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableCreateStoreRequest) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_create_store_response.go000066400000000000000000000114151456721040100251530ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" "time" ) // CreateStoreResponse struct for CreateStoreResponse type CreateStoreResponse struct { Id string `json:"id"yaml:"id"` Name string `json:"name"yaml:"name"` CreatedAt time.Time `json:"created_at"yaml:"created_at"` UpdatedAt time.Time `json:"updated_at"yaml:"updated_at"` } // NewCreateStoreResponse instantiates a new CreateStoreResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewCreateStoreResponse(id string, name string, createdAt time.Time, updatedAt time.Time) *CreateStoreResponse { this := CreateStoreResponse{} this.Id = id this.Name = name this.CreatedAt = createdAt this.UpdatedAt = updatedAt return &this } // NewCreateStoreResponseWithDefaults instantiates a new CreateStoreResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewCreateStoreResponseWithDefaults() *CreateStoreResponse { this := CreateStoreResponse{} return &this } // GetId returns the Id field value func (o *CreateStoreResponse) GetId() string { if o == nil { var ret string return ret } return o.Id } // GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. func (o *CreateStoreResponse) GetIdOk() (*string, bool) { if o == nil { return nil, false } return &o.Id, true } // SetId sets field value func (o *CreateStoreResponse) SetId(v string) { o.Id = v } // GetName returns the Name field value func (o *CreateStoreResponse) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *CreateStoreResponse) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *CreateStoreResponse) SetName(v string) { o.Name = v } // GetCreatedAt returns the CreatedAt field value func (o *CreateStoreResponse) GetCreatedAt() time.Time { if o == nil { var ret time.Time return ret } return o.CreatedAt } // GetCreatedAtOk returns a tuple with the CreatedAt field value // and a boolean to check if the value has been set. func (o *CreateStoreResponse) GetCreatedAtOk() (*time.Time, bool) { if o == nil { return nil, false } return &o.CreatedAt, true } // SetCreatedAt sets field value func (o *CreateStoreResponse) SetCreatedAt(v time.Time) { o.CreatedAt = v } // GetUpdatedAt returns the UpdatedAt field value func (o *CreateStoreResponse) GetUpdatedAt() time.Time { if o == nil { var ret time.Time return ret } return o.UpdatedAt } // GetUpdatedAtOk returns a tuple with the UpdatedAt field value // and a boolean to check if the value has been set. func (o *CreateStoreResponse) GetUpdatedAtOk() (*time.Time, bool) { if o == nil { return nil, false } return &o.UpdatedAt, true } // SetUpdatedAt sets field value func (o *CreateStoreResponse) SetUpdatedAt(v time.Time) { o.UpdatedAt = v } func (o CreateStoreResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["id"] = o.Id toSerialize["name"] = o.Name toSerialize["created_at"] = o.CreatedAt toSerialize["updated_at"] = o.UpdatedAt var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableCreateStoreResponse struct { value *CreateStoreResponse isSet bool } func (v NullableCreateStoreResponse) Get() *CreateStoreResponse { return v.value } func (v *NullableCreateStoreResponse) Set(val *CreateStoreResponse) { v.value = val v.isSet = true } func (v NullableCreateStoreResponse) IsSet() bool { return v.isSet } func (v *NullableCreateStoreResponse) Unset() { v.value = nil v.isSet = false } func NewNullableCreateStoreResponse(val *CreateStoreResponse) *NullableCreateStoreResponse { return &NullableCreateStoreResponse{value: val, isSet: true} } func (v NullableCreateStoreResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableCreateStoreResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_difference.go000066400000000000000000000063251456721040100226540ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Difference struct for Difference type Difference struct { Base Userset `json:"base"yaml:"base"` Subtract Userset `json:"subtract"yaml:"subtract"` } // NewDifference instantiates a new Difference object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewDifference(base Userset, subtract Userset) *Difference { this := Difference{} this.Base = base this.Subtract = subtract return &this } // NewDifferenceWithDefaults instantiates a new Difference object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewDifferenceWithDefaults() *Difference { this := Difference{} return &this } // GetBase returns the Base field value func (o *Difference) GetBase() Userset { if o == nil { var ret Userset return ret } return o.Base } // GetBaseOk returns a tuple with the Base field value // and a boolean to check if the value has been set. func (o *Difference) GetBaseOk() (*Userset, bool) { if o == nil { return nil, false } return &o.Base, true } // SetBase sets field value func (o *Difference) SetBase(v Userset) { o.Base = v } // GetSubtract returns the Subtract field value func (o *Difference) GetSubtract() Userset { if o == nil { var ret Userset return ret } return o.Subtract } // GetSubtractOk returns a tuple with the Subtract field value // and a boolean to check if the value has been set. func (o *Difference) GetSubtractOk() (*Userset, bool) { if o == nil { return nil, false } return &o.Subtract, true } // SetSubtract sets field value func (o *Difference) SetSubtract(v Userset) { o.Subtract = v } func (o Difference) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["base"] = o.Base toSerialize["subtract"] = o.Subtract var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableDifference struct { value *Difference isSet bool } func (v NullableDifference) Get() *Difference { return v.value } func (v *NullableDifference) Set(val *Difference) { v.value = val v.isSet = true } func (v NullableDifference) IsSet() bool { return v.isSet } func (v *NullableDifference) Unset() { v.value = nil v.isSet = false } func NewNullableDifference(val *Difference) *NullableDifference { return &NullableDifference{value: val, isSet: true} } func (v NullableDifference) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableDifference) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_error_code.go000066400000000000000000000175621456721040100227120ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "encoding/json" "fmt" ) // ErrorCode the model 'ErrorCode' type ErrorCode string // List of ErrorCode const ( NO_ERROR ErrorCode = "no_error" VALIDATION_ERROR ErrorCode = "validation_error" AUTHORIZATION_MODEL_NOT_FOUND ErrorCode = "authorization_model_not_found" AUTHORIZATION_MODEL_RESOLUTION_TOO_COMPLEX ErrorCode = "authorization_model_resolution_too_complex" INVALID_WRITE_INPUT ErrorCode = "invalid_write_input" CANNOT_ALLOW_DUPLICATE_TUPLES_IN_ONE_REQUEST ErrorCode = "cannot_allow_duplicate_tuples_in_one_request" CANNOT_ALLOW_DUPLICATE_TYPES_IN_ONE_REQUEST ErrorCode = "cannot_allow_duplicate_types_in_one_request" CANNOT_ALLOW_MULTIPLE_REFERENCES_TO_ONE_RELATION ErrorCode = "cannot_allow_multiple_references_to_one_relation" INVALID_CONTINUATION_TOKEN ErrorCode = "invalid_continuation_token" INVALID_TUPLE_SET ErrorCode = "invalid_tuple_set" INVALID_CHECK_INPUT ErrorCode = "invalid_check_input" INVALID_EXPAND_INPUT ErrorCode = "invalid_expand_input" UNSUPPORTED_USER_SET ErrorCode = "unsupported_user_set" INVALID_OBJECT_FORMAT ErrorCode = "invalid_object_format" WRITE_FAILED_DUE_TO_INVALID_INPUT ErrorCode = "write_failed_due_to_invalid_input" AUTHORIZATION_MODEL_ASSERTIONS_NOT_FOUND ErrorCode = "authorization_model_assertions_not_found" LATEST_AUTHORIZATION_MODEL_NOT_FOUND ErrorCode = "latest_authorization_model_not_found" TYPE_NOT_FOUND ErrorCode = "type_not_found" RELATION_NOT_FOUND ErrorCode = "relation_not_found" EMPTY_RELATION_DEFINITION ErrorCode = "empty_relation_definition" INVALID_USER ErrorCode = "invalid_user" INVALID_TUPLE ErrorCode = "invalid_tuple" UNKNOWN_RELATION ErrorCode = "unknown_relation" STORE_ID_INVALID_LENGTH ErrorCode = "store_id_invalid_length" ASSERTIONS_TOO_MANY_ITEMS ErrorCode = "assertions_too_many_items" ID_TOO_LONG ErrorCode = "id_too_long" AUTHORIZATION_MODEL_ID_TOO_LONG ErrorCode = "authorization_model_id_too_long" TUPLE_KEY_VALUE_NOT_SPECIFIED ErrorCode = "tuple_key_value_not_specified" TUPLE_KEYS_TOO_MANY_OR_TOO_FEW_ITEMS ErrorCode = "tuple_keys_too_many_or_too_few_items" PAGE_SIZE_INVALID ErrorCode = "page_size_invalid" PARAM_MISSING_VALUE ErrorCode = "param_missing_value" DIFFERENCE_BASE_MISSING_VALUE ErrorCode = "difference_base_missing_value" SUBTRACT_BASE_MISSING_VALUE ErrorCode = "subtract_base_missing_value" OBJECT_TOO_LONG ErrorCode = "object_too_long" RELATION_TOO_LONG ErrorCode = "relation_too_long" TYPE_DEFINITIONS_TOO_FEW_ITEMS ErrorCode = "type_definitions_too_few_items" TYPE_INVALID_LENGTH ErrorCode = "type_invalid_length" TYPE_INVALID_PATTERN ErrorCode = "type_invalid_pattern" RELATIONS_TOO_FEW_ITEMS ErrorCode = "relations_too_few_items" RELATIONS_TOO_LONG ErrorCode = "relations_too_long" RELATIONS_INVALID_PATTERN ErrorCode = "relations_invalid_pattern" OBJECT_INVALID_PATTERN ErrorCode = "object_invalid_pattern" QUERY_STRING_TYPE_CONTINUATION_TOKEN_MISMATCH ErrorCode = "query_string_type_continuation_token_mismatch" EXCEEDED_ENTITY_LIMIT ErrorCode = "exceeded_entity_limit" INVALID_CONTEXTUAL_TUPLE ErrorCode = "invalid_contextual_tuple" DUPLICATE_CONTEXTUAL_TUPLE ErrorCode = "duplicate_contextual_tuple" INVALID_AUTHORIZATION_MODEL ErrorCode = "invalid_authorization_model" UNSUPPORTED_SCHEMA_VERSION ErrorCode = "unsupported_schema_version" ) var allowedErrorCodeEnumValues = []ErrorCode{ "no_error", "validation_error", "authorization_model_not_found", "authorization_model_resolution_too_complex", "invalid_write_input", "cannot_allow_duplicate_tuples_in_one_request", "cannot_allow_duplicate_types_in_one_request", "cannot_allow_multiple_references_to_one_relation", "invalid_continuation_token", "invalid_tuple_set", "invalid_check_input", "invalid_expand_input", "unsupported_user_set", "invalid_object_format", "write_failed_due_to_invalid_input", "authorization_model_assertions_not_found", "latest_authorization_model_not_found", "type_not_found", "relation_not_found", "empty_relation_definition", "invalid_user", "invalid_tuple", "unknown_relation", "store_id_invalid_length", "assertions_too_many_items", "id_too_long", "authorization_model_id_too_long", "tuple_key_value_not_specified", "tuple_keys_too_many_or_too_few_items", "page_size_invalid", "param_missing_value", "difference_base_missing_value", "subtract_base_missing_value", "object_too_long", "relation_too_long", "type_definitions_too_few_items", "type_invalid_length", "type_invalid_pattern", "relations_too_few_items", "relations_too_long", "relations_invalid_pattern", "object_invalid_pattern", "query_string_type_continuation_token_mismatch", "exceeded_entity_limit", "invalid_contextual_tuple", "duplicate_contextual_tuple", "invalid_authorization_model", "unsupported_schema_version", } func (v *ErrorCode) UnmarshalJSON(src []byte) error { var value string err := json.Unmarshal(src, &value) if err != nil { return err } enumTypeValue := ErrorCode(value) for _, existing := range allowedErrorCodeEnumValues { if existing == enumTypeValue { *v = enumTypeValue return nil } } return fmt.Errorf("%+v is not a valid ErrorCode", value) } // NewErrorCodeFromValue returns a pointer to a valid ErrorCode // for the value passed as argument, or an error if the value passed is not allowed by the enum func NewErrorCodeFromValue(v string) (*ErrorCode, error) { ev := ErrorCode(v) if ev.IsValid() { return &ev, nil } else { return nil, fmt.Errorf("invalid value '%v' for ErrorCode: valid values are %v", v, allowedErrorCodeEnumValues) } } // IsValid return true if the value is valid for the enum, false otherwise func (v ErrorCode) IsValid() bool { for _, existing := range allowedErrorCodeEnumValues { if existing == v { return true } } return false } // Ptr returns reference to ErrorCode value func (v ErrorCode) Ptr() *ErrorCode { return &v } type NullableErrorCode struct { value *ErrorCode isSet bool } func (v NullableErrorCode) Get() *ErrorCode { return v.value } func (v *NullableErrorCode) Set(val *ErrorCode) { v.value = val v.isSet = true } func (v NullableErrorCode) IsSet() bool { return v.isSet } func (v *NullableErrorCode) Unset() { v.value = nil v.isSet = false } func NewNullableErrorCode(val *ErrorCode) *NullableErrorCode { return &NullableErrorCode{value: val, isSet: true} } func (v NullableErrorCode) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableErrorCode) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_expand_request.go000066400000000000000000000101241456721040100236010ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ExpandRequest struct for ExpandRequest type ExpandRequest struct { TupleKey ExpandRequestTupleKey `json:"tuple_key"yaml:"tuple_key"` AuthorizationModelId *string `json:"authorization_model_id,omitempty"yaml:"authorization_model_id,omitempty"` } // NewExpandRequest instantiates a new ExpandRequest object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewExpandRequest(tupleKey ExpandRequestTupleKey) *ExpandRequest { this := ExpandRequest{} this.TupleKey = tupleKey return &this } // NewExpandRequestWithDefaults instantiates a new ExpandRequest object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewExpandRequestWithDefaults() *ExpandRequest { this := ExpandRequest{} return &this } // GetTupleKey returns the TupleKey field value func (o *ExpandRequest) GetTupleKey() ExpandRequestTupleKey { if o == nil { var ret ExpandRequestTupleKey return ret } return o.TupleKey } // GetTupleKeyOk returns a tuple with the TupleKey field value // and a boolean to check if the value has been set. func (o *ExpandRequest) GetTupleKeyOk() (*ExpandRequestTupleKey, bool) { if o == nil { return nil, false } return &o.TupleKey, true } // SetTupleKey sets field value func (o *ExpandRequest) SetTupleKey(v ExpandRequestTupleKey) { o.TupleKey = v } // GetAuthorizationModelId returns the AuthorizationModelId field value if set, zero value otherwise. func (o *ExpandRequest) GetAuthorizationModelId() string { if o == nil || o.AuthorizationModelId == nil { var ret string return ret } return *o.AuthorizationModelId } // GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ExpandRequest) GetAuthorizationModelIdOk() (*string, bool) { if o == nil || o.AuthorizationModelId == nil { return nil, false } return o.AuthorizationModelId, true } // HasAuthorizationModelId returns a boolean if a field has been set. func (o *ExpandRequest) HasAuthorizationModelId() bool { if o != nil && o.AuthorizationModelId != nil { return true } return false } // SetAuthorizationModelId gets a reference to the given string and assigns it to the AuthorizationModelId field. func (o *ExpandRequest) SetAuthorizationModelId(v string) { o.AuthorizationModelId = &v } func (o ExpandRequest) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tuple_key"] = o.TupleKey if o.AuthorizationModelId != nil { toSerialize["authorization_model_id"] = o.AuthorizationModelId } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableExpandRequest struct { value *ExpandRequest isSet bool } func (v NullableExpandRequest) Get() *ExpandRequest { return v.value } func (v *NullableExpandRequest) Set(val *ExpandRequest) { v.value = val v.isSet = true } func (v NullableExpandRequest) IsSet() bool { return v.isSet } func (v *NullableExpandRequest) Unset() { v.value = nil v.isSet = false } func NewNullableExpandRequest(val *ExpandRequest) *NullableExpandRequest { return &NullableExpandRequest{value: val, isSet: true} } func (v NullableExpandRequest) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableExpandRequest) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_expand_request_tuple_key.go000066400000000000000000000071431456721040100256710ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ExpandRequestTupleKey struct for ExpandRequestTupleKey type ExpandRequestTupleKey struct { Relation string `json:"relation"yaml:"relation"` Object string `json:"object"yaml:"object"` } // NewExpandRequestTupleKey instantiates a new ExpandRequestTupleKey object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewExpandRequestTupleKey(relation string, object string) *ExpandRequestTupleKey { this := ExpandRequestTupleKey{} this.Relation = relation this.Object = object return &this } // NewExpandRequestTupleKeyWithDefaults instantiates a new ExpandRequestTupleKey object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewExpandRequestTupleKeyWithDefaults() *ExpandRequestTupleKey { this := ExpandRequestTupleKey{} return &this } // GetRelation returns the Relation field value func (o *ExpandRequestTupleKey) GetRelation() string { if o == nil { var ret string return ret } return o.Relation } // GetRelationOk returns a tuple with the Relation field value // and a boolean to check if the value has been set. func (o *ExpandRequestTupleKey) GetRelationOk() (*string, bool) { if o == nil { return nil, false } return &o.Relation, true } // SetRelation sets field value func (o *ExpandRequestTupleKey) SetRelation(v string) { o.Relation = v } // GetObject returns the Object field value func (o *ExpandRequestTupleKey) GetObject() string { if o == nil { var ret string return ret } return o.Object } // GetObjectOk returns a tuple with the Object field value // and a boolean to check if the value has been set. func (o *ExpandRequestTupleKey) GetObjectOk() (*string, bool) { if o == nil { return nil, false } return &o.Object, true } // SetObject sets field value func (o *ExpandRequestTupleKey) SetObject(v string) { o.Object = v } func (o ExpandRequestTupleKey) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["relation"] = o.Relation toSerialize["object"] = o.Object var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableExpandRequestTupleKey struct { value *ExpandRequestTupleKey isSet bool } func (v NullableExpandRequestTupleKey) Get() *ExpandRequestTupleKey { return v.value } func (v *NullableExpandRequestTupleKey) Set(val *ExpandRequestTupleKey) { v.value = val v.isSet = true } func (v NullableExpandRequestTupleKey) IsSet() bool { return v.isSet } func (v *NullableExpandRequestTupleKey) Unset() { v.value = nil v.isSet = false } func NewNullableExpandRequestTupleKey(val *ExpandRequestTupleKey) *NullableExpandRequestTupleKey { return &NullableExpandRequestTupleKey{value: val, isSet: true} } func (v NullableExpandRequestTupleKey) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableExpandRequestTupleKey) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_expand_response.go000066400000000000000000000060521456721040100237540ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ExpandResponse struct for ExpandResponse type ExpandResponse struct { Tree *UsersetTree `json:"tree,omitempty"yaml:"tree,omitempty"` } // NewExpandResponse instantiates a new ExpandResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewExpandResponse() *ExpandResponse { this := ExpandResponse{} return &this } // NewExpandResponseWithDefaults instantiates a new ExpandResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewExpandResponseWithDefaults() *ExpandResponse { this := ExpandResponse{} return &this } // GetTree returns the Tree field value if set, zero value otherwise. func (o *ExpandResponse) GetTree() UsersetTree { if o == nil || o.Tree == nil { var ret UsersetTree return ret } return *o.Tree } // GetTreeOk returns a tuple with the Tree field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ExpandResponse) GetTreeOk() (*UsersetTree, bool) { if o == nil || o.Tree == nil { return nil, false } return o.Tree, true } // HasTree returns a boolean if a field has been set. func (o *ExpandResponse) HasTree() bool { if o != nil && o.Tree != nil { return true } return false } // SetTree gets a reference to the given UsersetTree and assigns it to the Tree field. func (o *ExpandResponse) SetTree(v UsersetTree) { o.Tree = &v } func (o ExpandResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Tree != nil { toSerialize["tree"] = o.Tree } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableExpandResponse struct { value *ExpandResponse isSet bool } func (v NullableExpandResponse) Get() *ExpandResponse { return v.value } func (v *NullableExpandResponse) Set(val *ExpandResponse) { v.value = val v.isSet = true } func (v NullableExpandResponse) IsSet() bool { return v.isSet } func (v *NullableExpandResponse) Unset() { v.value = nil v.isSet = false } func NewNullableExpandResponse(val *ExpandResponse) *NullableExpandResponse { return &NullableExpandResponse{value: val, isSet: true} } func (v NullableExpandResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableExpandResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_get_store_response.go000066400000000000000000000132321456721040100244660ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" "time" ) // GetStoreResponse struct for GetStoreResponse type GetStoreResponse struct { Id string `json:"id"yaml:"id"` Name string `json:"name"yaml:"name"` CreatedAt time.Time `json:"created_at"yaml:"created_at"` UpdatedAt time.Time `json:"updated_at"yaml:"updated_at"` DeletedAt *time.Time `json:"deleted_at,omitempty"yaml:"deleted_at,omitempty"` } // NewGetStoreResponse instantiates a new GetStoreResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewGetStoreResponse(id string, name string, createdAt time.Time, updatedAt time.Time) *GetStoreResponse { this := GetStoreResponse{} this.Id = id this.Name = name this.CreatedAt = createdAt this.UpdatedAt = updatedAt return &this } // NewGetStoreResponseWithDefaults instantiates a new GetStoreResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewGetStoreResponseWithDefaults() *GetStoreResponse { this := GetStoreResponse{} return &this } // GetId returns the Id field value func (o *GetStoreResponse) GetId() string { if o == nil { var ret string return ret } return o.Id } // GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. func (o *GetStoreResponse) GetIdOk() (*string, bool) { if o == nil { return nil, false } return &o.Id, true } // SetId sets field value func (o *GetStoreResponse) SetId(v string) { o.Id = v } // GetName returns the Name field value func (o *GetStoreResponse) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *GetStoreResponse) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *GetStoreResponse) SetName(v string) { o.Name = v } // GetCreatedAt returns the CreatedAt field value func (o *GetStoreResponse) GetCreatedAt() time.Time { if o == nil { var ret time.Time return ret } return o.CreatedAt } // GetCreatedAtOk returns a tuple with the CreatedAt field value // and a boolean to check if the value has been set. func (o *GetStoreResponse) GetCreatedAtOk() (*time.Time, bool) { if o == nil { return nil, false } return &o.CreatedAt, true } // SetCreatedAt sets field value func (o *GetStoreResponse) SetCreatedAt(v time.Time) { o.CreatedAt = v } // GetUpdatedAt returns the UpdatedAt field value func (o *GetStoreResponse) GetUpdatedAt() time.Time { if o == nil { var ret time.Time return ret } return o.UpdatedAt } // GetUpdatedAtOk returns a tuple with the UpdatedAt field value // and a boolean to check if the value has been set. func (o *GetStoreResponse) GetUpdatedAtOk() (*time.Time, bool) { if o == nil { return nil, false } return &o.UpdatedAt, true } // SetUpdatedAt sets field value func (o *GetStoreResponse) SetUpdatedAt(v time.Time) { o.UpdatedAt = v } // GetDeletedAt returns the DeletedAt field value if set, zero value otherwise. func (o *GetStoreResponse) GetDeletedAt() time.Time { if o == nil || o.DeletedAt == nil { var ret time.Time return ret } return *o.DeletedAt } // GetDeletedAtOk returns a tuple with the DeletedAt field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *GetStoreResponse) GetDeletedAtOk() (*time.Time, bool) { if o == nil || o.DeletedAt == nil { return nil, false } return o.DeletedAt, true } // HasDeletedAt returns a boolean if a field has been set. func (o *GetStoreResponse) HasDeletedAt() bool { if o != nil && o.DeletedAt != nil { return true } return false } // SetDeletedAt gets a reference to the given time.Time and assigns it to the DeletedAt field. func (o *GetStoreResponse) SetDeletedAt(v time.Time) { o.DeletedAt = &v } func (o GetStoreResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["id"] = o.Id toSerialize["name"] = o.Name toSerialize["created_at"] = o.CreatedAt toSerialize["updated_at"] = o.UpdatedAt if o.DeletedAt != nil { toSerialize["deleted_at"] = o.DeletedAt } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableGetStoreResponse struct { value *GetStoreResponse isSet bool } func (v NullableGetStoreResponse) Get() *GetStoreResponse { return v.value } func (v *NullableGetStoreResponse) Set(val *GetStoreResponse) { v.value = val v.isSet = true } func (v NullableGetStoreResponse) IsSet() bool { return v.isSet } func (v *NullableGetStoreResponse) Unset() { v.value = nil v.isSet = false } func NewNullableGetStoreResponse(val *GetStoreResponse) *NullableGetStoreResponse { return &NullableGetStoreResponse{value: val, isSet: true} } func (v NullableGetStoreResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableGetStoreResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_internal_error_code.go000066400000000000000000000065631456721040100246050ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "encoding/json" "fmt" ) // InternalErrorCode the model 'InternalErrorCode' type InternalErrorCode string // List of InternalErrorCode const ( NO_INTERNAL_ERROR InternalErrorCode = "no_internal_error" INTERNAL_ERROR InternalErrorCode = "internal_error" CANCELLED InternalErrorCode = "cancelled" DEADLINE_EXCEEDED InternalErrorCode = "deadline_exceeded" ALREADY_EXISTS InternalErrorCode = "already_exists" RESOURCE_EXHAUSTED InternalErrorCode = "resource_exhausted" FAILED_PRECONDITION InternalErrorCode = "failed_precondition" ABORTED InternalErrorCode = "aborted" OUT_OF_RANGE InternalErrorCode = "out_of_range" UNAVAILABLE InternalErrorCode = "unavailable" DATA_LOSS InternalErrorCode = "data_loss" ) var allowedInternalErrorCodeEnumValues = []InternalErrorCode{ "no_internal_error", "internal_error", "cancelled", "deadline_exceeded", "already_exists", "resource_exhausted", "failed_precondition", "aborted", "out_of_range", "unavailable", "data_loss", } func (v *InternalErrorCode) UnmarshalJSON(src []byte) error { var value string err := json.Unmarshal(src, &value) if err != nil { return err } enumTypeValue := InternalErrorCode(value) for _, existing := range allowedInternalErrorCodeEnumValues { if existing == enumTypeValue { *v = enumTypeValue return nil } } return fmt.Errorf("%+v is not a valid InternalErrorCode", value) } // NewInternalErrorCodeFromValue returns a pointer to a valid InternalErrorCode // for the value passed as argument, or an error if the value passed is not allowed by the enum func NewInternalErrorCodeFromValue(v string) (*InternalErrorCode, error) { ev := InternalErrorCode(v) if ev.IsValid() { return &ev, nil } else { return nil, fmt.Errorf("invalid value '%v' for InternalErrorCode: valid values are %v", v, allowedInternalErrorCodeEnumValues) } } // IsValid return true if the value is valid for the enum, false otherwise func (v InternalErrorCode) IsValid() bool { for _, existing := range allowedInternalErrorCodeEnumValues { if existing == v { return true } } return false } // Ptr returns reference to InternalErrorCode value func (v InternalErrorCode) Ptr() *InternalErrorCode { return &v } type NullableInternalErrorCode struct { value *InternalErrorCode isSet bool } func (v NullableInternalErrorCode) Get() *InternalErrorCode { return v.value } func (v *NullableInternalErrorCode) Set(val *InternalErrorCode) { v.value = val v.isSet = true } func (v NullableInternalErrorCode) IsSet() bool { return v.isSet } func (v *NullableInternalErrorCode) Unset() { v.value = nil v.isSet = false } func NewNullableInternalErrorCode(val *InternalErrorCode) *NullableInternalErrorCode { return &NullableInternalErrorCode{value: val, isSet: true} } func (v NullableInternalErrorCode) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableInternalErrorCode) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_internal_error_message_response.go000066400000000000000000000112201456721040100272170ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // InternalErrorMessageResponse struct for InternalErrorMessageResponse type InternalErrorMessageResponse struct { Code *InternalErrorCode `json:"code,omitempty"yaml:"code,omitempty"` Message *string `json:"message,omitempty"yaml:"message,omitempty"` } // NewInternalErrorMessageResponse instantiates a new InternalErrorMessageResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewInternalErrorMessageResponse() *InternalErrorMessageResponse { this := InternalErrorMessageResponse{} var code InternalErrorCode = NO_INTERNAL_ERROR this.Code = &code return &this } // NewInternalErrorMessageResponseWithDefaults instantiates a new InternalErrorMessageResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewInternalErrorMessageResponseWithDefaults() *InternalErrorMessageResponse { this := InternalErrorMessageResponse{} var code InternalErrorCode = NO_INTERNAL_ERROR this.Code = &code return &this } // GetCode returns the Code field value if set, zero value otherwise. func (o *InternalErrorMessageResponse) GetCode() InternalErrorCode { if o == nil || o.Code == nil { var ret InternalErrorCode return ret } return *o.Code } // GetCodeOk returns a tuple with the Code field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *InternalErrorMessageResponse) GetCodeOk() (*InternalErrorCode, bool) { if o == nil || o.Code == nil { return nil, false } return o.Code, true } // HasCode returns a boolean if a field has been set. func (o *InternalErrorMessageResponse) HasCode() bool { if o != nil && o.Code != nil { return true } return false } // SetCode gets a reference to the given InternalErrorCode and assigns it to the Code field. func (o *InternalErrorMessageResponse) SetCode(v InternalErrorCode) { o.Code = &v } // GetMessage returns the Message field value if set, zero value otherwise. func (o *InternalErrorMessageResponse) GetMessage() string { if o == nil || o.Message == nil { var ret string return ret } return *o.Message } // GetMessageOk returns a tuple with the Message field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *InternalErrorMessageResponse) GetMessageOk() (*string, bool) { if o == nil || o.Message == nil { return nil, false } return o.Message, true } // HasMessage returns a boolean if a field has been set. func (o *InternalErrorMessageResponse) HasMessage() bool { if o != nil && o.Message != nil { return true } return false } // SetMessage gets a reference to the given string and assigns it to the Message field. func (o *InternalErrorMessageResponse) SetMessage(v string) { o.Message = &v } func (o InternalErrorMessageResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Code != nil { toSerialize["code"] = o.Code } if o.Message != nil { toSerialize["message"] = o.Message } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableInternalErrorMessageResponse struct { value *InternalErrorMessageResponse isSet bool } func (v NullableInternalErrorMessageResponse) Get() *InternalErrorMessageResponse { return v.value } func (v *NullableInternalErrorMessageResponse) Set(val *InternalErrorMessageResponse) { v.value = val v.isSet = true } func (v NullableInternalErrorMessageResponse) IsSet() bool { return v.isSet } func (v *NullableInternalErrorMessageResponse) Unset() { v.value = nil v.isSet = false } func NewNullableInternalErrorMessageResponse(val *InternalErrorMessageResponse) *NullableInternalErrorMessageResponse { return &NullableInternalErrorMessageResponse{value: val, isSet: true} } func (v NullableInternalErrorMessageResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableInternalErrorMessageResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_leaf.go000066400000000000000000000122331456721040100214640ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Leaf A leaf node contains either - a set of users (which may be individual users, or usersets referencing other relations) - a computed node, which is the result of a computed userset value in the authorization model - a tupleToUserset nodes, containing the result of expanding a tupleToUserset value in a authorization model. type Leaf struct { Users *Users `json:"users,omitempty"yaml:"users,omitempty"` Computed *Computed `json:"computed,omitempty"yaml:"computed,omitempty"` TupleToUserset *UsersetTreeTupleToUserset `json:"tupleToUserset,omitempty"yaml:"tupleToUserset,omitempty"` } // NewLeaf instantiates a new Leaf object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewLeaf() *Leaf { this := Leaf{} return &this } // NewLeafWithDefaults instantiates a new Leaf object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewLeafWithDefaults() *Leaf { this := Leaf{} return &this } // GetUsers returns the Users field value if set, zero value otherwise. func (o *Leaf) GetUsers() Users { if o == nil || o.Users == nil { var ret Users return ret } return *o.Users } // GetUsersOk returns a tuple with the Users field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Leaf) GetUsersOk() (*Users, bool) { if o == nil || o.Users == nil { return nil, false } return o.Users, true } // HasUsers returns a boolean if a field has been set. func (o *Leaf) HasUsers() bool { if o != nil && o.Users != nil { return true } return false } // SetUsers gets a reference to the given Users and assigns it to the Users field. func (o *Leaf) SetUsers(v Users) { o.Users = &v } // GetComputed returns the Computed field value if set, zero value otherwise. func (o *Leaf) GetComputed() Computed { if o == nil || o.Computed == nil { var ret Computed return ret } return *o.Computed } // GetComputedOk returns a tuple with the Computed field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Leaf) GetComputedOk() (*Computed, bool) { if o == nil || o.Computed == nil { return nil, false } return o.Computed, true } // HasComputed returns a boolean if a field has been set. func (o *Leaf) HasComputed() bool { if o != nil && o.Computed != nil { return true } return false } // SetComputed gets a reference to the given Computed and assigns it to the Computed field. func (o *Leaf) SetComputed(v Computed) { o.Computed = &v } // GetTupleToUserset returns the TupleToUserset field value if set, zero value otherwise. func (o *Leaf) GetTupleToUserset() UsersetTreeTupleToUserset { if o == nil || o.TupleToUserset == nil { var ret UsersetTreeTupleToUserset return ret } return *o.TupleToUserset } // GetTupleToUsersetOk returns a tuple with the TupleToUserset field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Leaf) GetTupleToUsersetOk() (*UsersetTreeTupleToUserset, bool) { if o == nil || o.TupleToUserset == nil { return nil, false } return o.TupleToUserset, true } // HasTupleToUserset returns a boolean if a field has been set. func (o *Leaf) HasTupleToUserset() bool { if o != nil && o.TupleToUserset != nil { return true } return false } // SetTupleToUserset gets a reference to the given UsersetTreeTupleToUserset and assigns it to the TupleToUserset field. func (o *Leaf) SetTupleToUserset(v UsersetTreeTupleToUserset) { o.TupleToUserset = &v } func (o Leaf) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Users != nil { toSerialize["users"] = o.Users } if o.Computed != nil { toSerialize["computed"] = o.Computed } if o.TupleToUserset != nil { toSerialize["tupleToUserset"] = o.TupleToUserset } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableLeaf struct { value *Leaf isSet bool } func (v NullableLeaf) Get() *Leaf { return v.value } func (v *NullableLeaf) Set(val *Leaf) { v.value = val v.isSet = true } func (v NullableLeaf) IsSet() bool { return v.isSet } func (v *NullableLeaf) Unset() { v.value = nil v.isSet = false } func NewNullableLeaf(val *Leaf) *NullableLeaf { return &NullableLeaf{value: val, isSet: true} } func (v NullableLeaf) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableLeaf) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_list_objects_request.go000066400000000000000000000173671456721040100250260ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ListObjectsRequest struct for ListObjectsRequest type ListObjectsRequest struct { AuthorizationModelId *string `json:"authorization_model_id,omitempty"yaml:"authorization_model_id,omitempty"` Type string `json:"type"yaml:"type"` Relation string `json:"relation"yaml:"relation"` User string `json:"user"yaml:"user"` ContextualTuples *ContextualTupleKeys `json:"contextual_tuples,omitempty"yaml:"contextual_tuples,omitempty"` // Additional request context that will be used to evaluate any ABAC conditions encountered in the query evaluation. Context *map[string]interface{} `json:"context,omitempty"yaml:"context,omitempty"` } // NewListObjectsRequest instantiates a new ListObjectsRequest object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewListObjectsRequest(type_ string, relation string, user string) *ListObjectsRequest { this := ListObjectsRequest{} this.Type = type_ this.Relation = relation this.User = user return &this } // NewListObjectsRequestWithDefaults instantiates a new ListObjectsRequest object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewListObjectsRequestWithDefaults() *ListObjectsRequest { this := ListObjectsRequest{} return &this } // GetAuthorizationModelId returns the AuthorizationModelId field value if set, zero value otherwise. func (o *ListObjectsRequest) GetAuthorizationModelId() string { if o == nil || o.AuthorizationModelId == nil { var ret string return ret } return *o.AuthorizationModelId } // GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ListObjectsRequest) GetAuthorizationModelIdOk() (*string, bool) { if o == nil || o.AuthorizationModelId == nil { return nil, false } return o.AuthorizationModelId, true } // HasAuthorizationModelId returns a boolean if a field has been set. func (o *ListObjectsRequest) HasAuthorizationModelId() bool { if o != nil && o.AuthorizationModelId != nil { return true } return false } // SetAuthorizationModelId gets a reference to the given string and assigns it to the AuthorizationModelId field. func (o *ListObjectsRequest) SetAuthorizationModelId(v string) { o.AuthorizationModelId = &v } // GetType returns the Type field value func (o *ListObjectsRequest) GetType() string { if o == nil { var ret string return ret } return o.Type } // GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. func (o *ListObjectsRequest) GetTypeOk() (*string, bool) { if o == nil { return nil, false } return &o.Type, true } // SetType sets field value func (o *ListObjectsRequest) SetType(v string) { o.Type = v } // GetRelation returns the Relation field value func (o *ListObjectsRequest) GetRelation() string { if o == nil { var ret string return ret } return o.Relation } // GetRelationOk returns a tuple with the Relation field value // and a boolean to check if the value has been set. func (o *ListObjectsRequest) GetRelationOk() (*string, bool) { if o == nil { return nil, false } return &o.Relation, true } // SetRelation sets field value func (o *ListObjectsRequest) SetRelation(v string) { o.Relation = v } // GetUser returns the User field value func (o *ListObjectsRequest) GetUser() string { if o == nil { var ret string return ret } return o.User } // GetUserOk returns a tuple with the User field value // and a boolean to check if the value has been set. func (o *ListObjectsRequest) GetUserOk() (*string, bool) { if o == nil { return nil, false } return &o.User, true } // SetUser sets field value func (o *ListObjectsRequest) SetUser(v string) { o.User = v } // GetContextualTuples returns the ContextualTuples field value if set, zero value otherwise. func (o *ListObjectsRequest) GetContextualTuples() ContextualTupleKeys { if o == nil || o.ContextualTuples == nil { var ret ContextualTupleKeys return ret } return *o.ContextualTuples } // GetContextualTuplesOk returns a tuple with the ContextualTuples field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ListObjectsRequest) GetContextualTuplesOk() (*ContextualTupleKeys, bool) { if o == nil || o.ContextualTuples == nil { return nil, false } return o.ContextualTuples, true } // HasContextualTuples returns a boolean if a field has been set. func (o *ListObjectsRequest) HasContextualTuples() bool { if o != nil && o.ContextualTuples != nil { return true } return false } // SetContextualTuples gets a reference to the given ContextualTupleKeys and assigns it to the ContextualTuples field. func (o *ListObjectsRequest) SetContextualTuples(v ContextualTupleKeys) { o.ContextualTuples = &v } // GetContext returns the Context field value if set, zero value otherwise. func (o *ListObjectsRequest) GetContext() map[string]interface{} { if o == nil || o.Context == nil { var ret map[string]interface{} return ret } return *o.Context } // GetContextOk returns a tuple with the Context field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ListObjectsRequest) GetContextOk() (*map[string]interface{}, bool) { if o == nil || o.Context == nil { return nil, false } return o.Context, true } // HasContext returns a boolean if a field has been set. func (o *ListObjectsRequest) HasContext() bool { if o != nil && o.Context != nil { return true } return false } // SetContext gets a reference to the given map[string]interface{} and assigns it to the Context field. func (o *ListObjectsRequest) SetContext(v map[string]interface{}) { o.Context = &v } func (o ListObjectsRequest) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.AuthorizationModelId != nil { toSerialize["authorization_model_id"] = o.AuthorizationModelId } toSerialize["type"] = o.Type toSerialize["relation"] = o.Relation toSerialize["user"] = o.User if o.ContextualTuples != nil { toSerialize["contextual_tuples"] = o.ContextualTuples } if o.Context != nil { toSerialize["context"] = o.Context } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableListObjectsRequest struct { value *ListObjectsRequest isSet bool } func (v NullableListObjectsRequest) Get() *ListObjectsRequest { return v.value } func (v *NullableListObjectsRequest) Set(val *ListObjectsRequest) { v.value = val v.isSet = true } func (v NullableListObjectsRequest) IsSet() bool { return v.isSet } func (v *NullableListObjectsRequest) Unset() { v.value = nil v.isSet = false } func NewNullableListObjectsRequest(val *ListObjectsRequest) *NullableListObjectsRequest { return &NullableListObjectsRequest{value: val, isSet: true} } func (v NullableListObjectsRequest) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableListObjectsRequest) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_list_objects_response.go000066400000000000000000000056551456721040100251710ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ListObjectsResponse struct for ListObjectsResponse type ListObjectsResponse struct { Objects []string `json:"objects"yaml:"objects"` } // NewListObjectsResponse instantiates a new ListObjectsResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewListObjectsResponse(objects []string) *ListObjectsResponse { this := ListObjectsResponse{} this.Objects = objects return &this } // NewListObjectsResponseWithDefaults instantiates a new ListObjectsResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewListObjectsResponseWithDefaults() *ListObjectsResponse { this := ListObjectsResponse{} return &this } // GetObjects returns the Objects field value func (o *ListObjectsResponse) GetObjects() []string { if o == nil { var ret []string return ret } return o.Objects } // GetObjectsOk returns a tuple with the Objects field value // and a boolean to check if the value has been set. func (o *ListObjectsResponse) GetObjectsOk() (*[]string, bool) { if o == nil { return nil, false } return &o.Objects, true } // SetObjects sets field value func (o *ListObjectsResponse) SetObjects(v []string) { o.Objects = v } func (o ListObjectsResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["objects"] = o.Objects var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableListObjectsResponse struct { value *ListObjectsResponse isSet bool } func (v NullableListObjectsResponse) Get() *ListObjectsResponse { return v.value } func (v *NullableListObjectsResponse) Set(val *ListObjectsResponse) { v.value = val v.isSet = true } func (v NullableListObjectsResponse) IsSet() bool { return v.isSet } func (v *NullableListObjectsResponse) Unset() { v.value = nil v.isSet = false } func NewNullableListObjectsResponse(val *ListObjectsResponse) *NullableListObjectsResponse { return &NullableListObjectsResponse{value: val, isSet: true} } func (v NullableListObjectsResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableListObjectsResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_list_stores_response.go000066400000000000000000000073651456721040100250570ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ListStoresResponse struct for ListStoresResponse type ListStoresResponse struct { Stores []Store `json:"stores"yaml:"stores"` // The continuation token will be empty if there are no more stores. ContinuationToken string `json:"continuation_token"yaml:"continuation_token"` } // NewListStoresResponse instantiates a new ListStoresResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewListStoresResponse(stores []Store, continuationToken string) *ListStoresResponse { this := ListStoresResponse{} this.Stores = stores this.ContinuationToken = continuationToken return &this } // NewListStoresResponseWithDefaults instantiates a new ListStoresResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewListStoresResponseWithDefaults() *ListStoresResponse { this := ListStoresResponse{} return &this } // GetStores returns the Stores field value func (o *ListStoresResponse) GetStores() []Store { if o == nil { var ret []Store return ret } return o.Stores } // GetStoresOk returns a tuple with the Stores field value // and a boolean to check if the value has been set. func (o *ListStoresResponse) GetStoresOk() (*[]Store, bool) { if o == nil { return nil, false } return &o.Stores, true } // SetStores sets field value func (o *ListStoresResponse) SetStores(v []Store) { o.Stores = v } // GetContinuationToken returns the ContinuationToken field value func (o *ListStoresResponse) GetContinuationToken() string { if o == nil { var ret string return ret } return o.ContinuationToken } // GetContinuationTokenOk returns a tuple with the ContinuationToken field value // and a boolean to check if the value has been set. func (o *ListStoresResponse) GetContinuationTokenOk() (*string, bool) { if o == nil { return nil, false } return &o.ContinuationToken, true } // SetContinuationToken sets field value func (o *ListStoresResponse) SetContinuationToken(v string) { o.ContinuationToken = v } func (o ListStoresResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["stores"] = o.Stores toSerialize["continuation_token"] = o.ContinuationToken var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableListStoresResponse struct { value *ListStoresResponse isSet bool } func (v NullableListStoresResponse) Get() *ListStoresResponse { return v.value } func (v *NullableListStoresResponse) Set(val *ListStoresResponse) { v.value = val v.isSet = true } func (v NullableListStoresResponse) IsSet() bool { return v.isSet } func (v *NullableListStoresResponse) Unset() { v.value = nil v.isSet = false } func NewNullableListStoresResponse(val *ListStoresResponse) *NullableListStoresResponse { return &NullableListStoresResponse{value: val, isSet: true} } func (v NullableListStoresResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableListStoresResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_metadata.go000066400000000000000000000060751456721040100223440ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Metadata struct for Metadata type Metadata struct { Relations *map[string]RelationMetadata `json:"relations,omitempty"yaml:"relations,omitempty"` } // NewMetadata instantiates a new Metadata object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewMetadata() *Metadata { this := Metadata{} return &this } // NewMetadataWithDefaults instantiates a new Metadata object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewMetadataWithDefaults() *Metadata { this := Metadata{} return &this } // GetRelations returns the Relations field value if set, zero value otherwise. func (o *Metadata) GetRelations() map[string]RelationMetadata { if o == nil || o.Relations == nil { var ret map[string]RelationMetadata return ret } return *o.Relations } // GetRelationsOk returns a tuple with the Relations field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Metadata) GetRelationsOk() (*map[string]RelationMetadata, bool) { if o == nil || o.Relations == nil { return nil, false } return o.Relations, true } // HasRelations returns a boolean if a field has been set. func (o *Metadata) HasRelations() bool { if o != nil && o.Relations != nil { return true } return false } // SetRelations gets a reference to the given map[string]RelationMetadata and assigns it to the Relations field. func (o *Metadata) SetRelations(v map[string]RelationMetadata) { o.Relations = &v } func (o Metadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Relations != nil { toSerialize["relations"] = o.Relations } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableMetadata struct { value *Metadata isSet bool } func (v NullableMetadata) Get() *Metadata { return v.value } func (v *NullableMetadata) Set(val *Metadata) { v.value = val v.isSet = true } func (v NullableMetadata) IsSet() bool { return v.isSet } func (v *NullableMetadata) Unset() { v.value = nil v.isSet = false } func NewNullableMetadata(val *Metadata) *NullableMetadata { return &NullableMetadata{value: val, isSet: true} } func (v NullableMetadata) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableMetadata) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_node.go000066400000000000000000000142601456721040100215040ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Node struct for Node type Node struct { Name string `json:"name"yaml:"name"` Leaf *Leaf `json:"leaf,omitempty"yaml:"leaf,omitempty"` Difference *UsersetTreeDifference `json:"difference,omitempty"yaml:"difference,omitempty"` Union *Nodes `json:"union,omitempty"yaml:"union,omitempty"` Intersection *Nodes `json:"intersection,omitempty"yaml:"intersection,omitempty"` } // NewNode instantiates a new Node object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewNode(name string) *Node { this := Node{} this.Name = name return &this } // NewNodeWithDefaults instantiates a new Node object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewNodeWithDefaults() *Node { this := Node{} return &this } // GetName returns the Name field value func (o *Node) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *Node) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *Node) SetName(v string) { o.Name = v } // GetLeaf returns the Leaf field value if set, zero value otherwise. func (o *Node) GetLeaf() Leaf { if o == nil || o.Leaf == nil { var ret Leaf return ret } return *o.Leaf } // GetLeafOk returns a tuple with the Leaf field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Node) GetLeafOk() (*Leaf, bool) { if o == nil || o.Leaf == nil { return nil, false } return o.Leaf, true } // HasLeaf returns a boolean if a field has been set. func (o *Node) HasLeaf() bool { if o != nil && o.Leaf != nil { return true } return false } // SetLeaf gets a reference to the given Leaf and assigns it to the Leaf field. func (o *Node) SetLeaf(v Leaf) { o.Leaf = &v } // GetDifference returns the Difference field value if set, zero value otherwise. func (o *Node) GetDifference() UsersetTreeDifference { if o == nil || o.Difference == nil { var ret UsersetTreeDifference return ret } return *o.Difference } // GetDifferenceOk returns a tuple with the Difference field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Node) GetDifferenceOk() (*UsersetTreeDifference, bool) { if o == nil || o.Difference == nil { return nil, false } return o.Difference, true } // HasDifference returns a boolean if a field has been set. func (o *Node) HasDifference() bool { if o != nil && o.Difference != nil { return true } return false } // SetDifference gets a reference to the given UsersetTreeDifference and assigns it to the Difference field. func (o *Node) SetDifference(v UsersetTreeDifference) { o.Difference = &v } // GetUnion returns the Union field value if set, zero value otherwise. func (o *Node) GetUnion() Nodes { if o == nil || o.Union == nil { var ret Nodes return ret } return *o.Union } // GetUnionOk returns a tuple with the Union field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Node) GetUnionOk() (*Nodes, bool) { if o == nil || o.Union == nil { return nil, false } return o.Union, true } // HasUnion returns a boolean if a field has been set. func (o *Node) HasUnion() bool { if o != nil && o.Union != nil { return true } return false } // SetUnion gets a reference to the given Nodes and assigns it to the Union field. func (o *Node) SetUnion(v Nodes) { o.Union = &v } // GetIntersection returns the Intersection field value if set, zero value otherwise. func (o *Node) GetIntersection() Nodes { if o == nil || o.Intersection == nil { var ret Nodes return ret } return *o.Intersection } // GetIntersectionOk returns a tuple with the Intersection field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Node) GetIntersectionOk() (*Nodes, bool) { if o == nil || o.Intersection == nil { return nil, false } return o.Intersection, true } // HasIntersection returns a boolean if a field has been set. func (o *Node) HasIntersection() bool { if o != nil && o.Intersection != nil { return true } return false } // SetIntersection gets a reference to the given Nodes and assigns it to the Intersection field. func (o *Node) SetIntersection(v Nodes) { o.Intersection = &v } func (o Node) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["name"] = o.Name if o.Leaf != nil { toSerialize["leaf"] = o.Leaf } if o.Difference != nil { toSerialize["difference"] = o.Difference } if o.Union != nil { toSerialize["union"] = o.Union } if o.Intersection != nil { toSerialize["intersection"] = o.Intersection } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableNode struct { value *Node isSet bool } func (v NullableNode) Get() *Node { return v.value } func (v *NullableNode) Set(val *Node) { v.value = val v.isSet = true } func (v NullableNode) IsSet() bool { return v.isSet } func (v *NullableNode) Unset() { v.value = nil v.isSet = false } func NewNullableNode(val *Node) *NullableNode { return &NullableNode{value: val, isSet: true} } func (v NullableNode) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableNode) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_nodes.go000066400000000000000000000047111456721040100216670ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Nodes struct for Nodes type Nodes struct { Nodes []Node `json:"nodes"yaml:"nodes"` } // NewNodes instantiates a new Nodes object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewNodes(nodes []Node) *Nodes { this := Nodes{} this.Nodes = nodes return &this } // NewNodesWithDefaults instantiates a new Nodes object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewNodesWithDefaults() *Nodes { this := Nodes{} return &this } // GetNodes returns the Nodes field value func (o *Nodes) GetNodes() []Node { if o == nil { var ret []Node return ret } return o.Nodes } // GetNodesOk returns a tuple with the Nodes field value // and a boolean to check if the value has been set. func (o *Nodes) GetNodesOk() (*[]Node, bool) { if o == nil { return nil, false } return &o.Nodes, true } // SetNodes sets field value func (o *Nodes) SetNodes(v []Node) { o.Nodes = v } func (o Nodes) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["nodes"] = o.Nodes var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableNodes struct { value *Nodes isSet bool } func (v NullableNodes) Get() *Nodes { return v.value } func (v *NullableNodes) Set(val *Nodes) { v.value = val v.isSet = true } func (v NullableNodes) IsSet() bool { return v.isSet } func (v *NullableNodes) Unset() { v.value = nil v.isSet = false } func NewNullableNodes(val *Nodes) *NullableNodes { return &NullableNodes{value: val, isSet: true} } func (v NullableNodes) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableNodes) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_not_found_error_code.go000066400000000000000000000055701456721040100247610ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "encoding/json" "fmt" ) // NotFoundErrorCode the model 'NotFoundErrorCode' type NotFoundErrorCode string // List of NotFoundErrorCode const ( NO_NOT_FOUND_ERROR NotFoundErrorCode = "no_not_found_error" UNDEFINED_ENDPOINT NotFoundErrorCode = "undefined_endpoint" STORE_ID_NOT_FOUND NotFoundErrorCode = "store_id_not_found" UNIMPLEMENTED NotFoundErrorCode = "unimplemented" ) var allowedNotFoundErrorCodeEnumValues = []NotFoundErrorCode{ "no_not_found_error", "undefined_endpoint", "store_id_not_found", "unimplemented", } func (v *NotFoundErrorCode) UnmarshalJSON(src []byte) error { var value string err := json.Unmarshal(src, &value) if err != nil { return err } enumTypeValue := NotFoundErrorCode(value) for _, existing := range allowedNotFoundErrorCodeEnumValues { if existing == enumTypeValue { *v = enumTypeValue return nil } } return fmt.Errorf("%+v is not a valid NotFoundErrorCode", value) } // NewNotFoundErrorCodeFromValue returns a pointer to a valid NotFoundErrorCode // for the value passed as argument, or an error if the value passed is not allowed by the enum func NewNotFoundErrorCodeFromValue(v string) (*NotFoundErrorCode, error) { ev := NotFoundErrorCode(v) if ev.IsValid() { return &ev, nil } else { return nil, fmt.Errorf("invalid value '%v' for NotFoundErrorCode: valid values are %v", v, allowedNotFoundErrorCodeEnumValues) } } // IsValid return true if the value is valid for the enum, false otherwise func (v NotFoundErrorCode) IsValid() bool { for _, existing := range allowedNotFoundErrorCodeEnumValues { if existing == v { return true } } return false } // Ptr returns reference to NotFoundErrorCode value func (v NotFoundErrorCode) Ptr() *NotFoundErrorCode { return &v } type NullableNotFoundErrorCode struct { value *NotFoundErrorCode isSet bool } func (v NullableNotFoundErrorCode) Get() *NotFoundErrorCode { return v.value } func (v *NullableNotFoundErrorCode) Set(val *NotFoundErrorCode) { v.value = val v.isSet = true } func (v NullableNotFoundErrorCode) IsSet() bool { return v.isSet } func (v *NullableNotFoundErrorCode) Unset() { v.value = nil v.isSet = false } func NewNullableNotFoundErrorCode(val *NotFoundErrorCode) *NullableNotFoundErrorCode { return &NullableNotFoundErrorCode{value: val, isSet: true} } func (v NullableNotFoundErrorCode) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableNotFoundErrorCode) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_null_value.go000066400000000000000000000047441456721040100227330ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "encoding/json" "fmt" ) // NullValue `NullValue` is a singleton enumeration to represent the null value for the `Value` type union. The JSON representation for `NullValue` is JSON `null`. - NULL_VALUE: Null value. type NullValue string // List of NullValue const ( NULL_VALUE NullValue = "NULL_VALUE" ) var allowedNullValueEnumValues = []NullValue{ "NULL_VALUE", } func (v *NullValue) UnmarshalJSON(src []byte) error { var value string err := json.Unmarshal(src, &value) if err != nil { return err } enumTypeValue := NullValue(value) for _, existing := range allowedNullValueEnumValues { if existing == enumTypeValue { *v = enumTypeValue return nil } } return fmt.Errorf("%+v is not a valid NullValue", value) } // NewNullValueFromValue returns a pointer to a valid NullValue // for the value passed as argument, or an error if the value passed is not allowed by the enum func NewNullValueFromValue(v string) (*NullValue, error) { ev := NullValue(v) if ev.IsValid() { return &ev, nil } else { return nil, fmt.Errorf("invalid value '%v' for NullValue: valid values are %v", v, allowedNullValueEnumValues) } } // IsValid return true if the value is valid for the enum, false otherwise func (v NullValue) IsValid() bool { for _, existing := range allowedNullValueEnumValues { if existing == v { return true } } return false } // Ptr returns reference to NullValue value func (v NullValue) Ptr() *NullValue { return &v } type NullableNullValue struct { value *NullValue isSet bool } func (v NullableNullValue) Get() *NullValue { return v.value } func (v *NullableNullValue) Set(val *NullValue) { v.value = val v.isSet = true } func (v NullableNullValue) IsSet() bool { return v.isSet } func (v *NullableNullValue) Unset() { v.value = nil v.isSet = false } func NewNullableNullValue(val *NullValue) *NullableNullValue { return &NullableNullValue{value: val, isSet: true} } func (v NullableNullValue) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableNullValue) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_object_relation.go000066400000000000000000000100111456721040100237100ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ObjectRelation struct for ObjectRelation type ObjectRelation struct { Object *string `json:"object,omitempty"yaml:"object,omitempty"` Relation *string `json:"relation,omitempty"yaml:"relation,omitempty"` } // NewObjectRelation instantiates a new ObjectRelation object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewObjectRelation() *ObjectRelation { this := ObjectRelation{} return &this } // NewObjectRelationWithDefaults instantiates a new ObjectRelation object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewObjectRelationWithDefaults() *ObjectRelation { this := ObjectRelation{} return &this } // GetObject returns the Object field value if set, zero value otherwise. func (o *ObjectRelation) GetObject() string { if o == nil || o.Object == nil { var ret string return ret } return *o.Object } // GetObjectOk returns a tuple with the Object field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ObjectRelation) GetObjectOk() (*string, bool) { if o == nil || o.Object == nil { return nil, false } return o.Object, true } // HasObject returns a boolean if a field has been set. func (o *ObjectRelation) HasObject() bool { if o != nil && o.Object != nil { return true } return false } // SetObject gets a reference to the given string and assigns it to the Object field. func (o *ObjectRelation) SetObject(v string) { o.Object = &v } // GetRelation returns the Relation field value if set, zero value otherwise. func (o *ObjectRelation) GetRelation() string { if o == nil || o.Relation == nil { var ret string return ret } return *o.Relation } // GetRelationOk returns a tuple with the Relation field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ObjectRelation) GetRelationOk() (*string, bool) { if o == nil || o.Relation == nil { return nil, false } return o.Relation, true } // HasRelation returns a boolean if a field has been set. func (o *ObjectRelation) HasRelation() bool { if o != nil && o.Relation != nil { return true } return false } // SetRelation gets a reference to the given string and assigns it to the Relation field. func (o *ObjectRelation) SetRelation(v string) { o.Relation = &v } func (o ObjectRelation) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Object != nil { toSerialize["object"] = o.Object } if o.Relation != nil { toSerialize["relation"] = o.Relation } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableObjectRelation struct { value *ObjectRelation isSet bool } func (v NullableObjectRelation) Get() *ObjectRelation { return v.value } func (v *NullableObjectRelation) Set(val *ObjectRelation) { v.value = val v.isSet = true } func (v NullableObjectRelation) IsSet() bool { return v.isSet } func (v *NullableObjectRelation) Unset() { v.value = nil v.isSet = false } func NewNullableObjectRelation(val *ObjectRelation) *NullableObjectRelation { return &NullableObjectRelation{value: val, isSet: true} } func (v NullableObjectRelation) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableObjectRelation) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_path_unknown_error_message_response.go000066400000000000000000000113761456721040100301320ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // PathUnknownErrorMessageResponse struct for PathUnknownErrorMessageResponse type PathUnknownErrorMessageResponse struct { Code *NotFoundErrorCode `json:"code,omitempty"yaml:"code,omitempty"` Message *string `json:"message,omitempty"yaml:"message,omitempty"` } // NewPathUnknownErrorMessageResponse instantiates a new PathUnknownErrorMessageResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewPathUnknownErrorMessageResponse() *PathUnknownErrorMessageResponse { this := PathUnknownErrorMessageResponse{} var code NotFoundErrorCode = NO_NOT_FOUND_ERROR this.Code = &code return &this } // NewPathUnknownErrorMessageResponseWithDefaults instantiates a new PathUnknownErrorMessageResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewPathUnknownErrorMessageResponseWithDefaults() *PathUnknownErrorMessageResponse { this := PathUnknownErrorMessageResponse{} var code NotFoundErrorCode = NO_NOT_FOUND_ERROR this.Code = &code return &this } // GetCode returns the Code field value if set, zero value otherwise. func (o *PathUnknownErrorMessageResponse) GetCode() NotFoundErrorCode { if o == nil || o.Code == nil { var ret NotFoundErrorCode return ret } return *o.Code } // GetCodeOk returns a tuple with the Code field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *PathUnknownErrorMessageResponse) GetCodeOk() (*NotFoundErrorCode, bool) { if o == nil || o.Code == nil { return nil, false } return o.Code, true } // HasCode returns a boolean if a field has been set. func (o *PathUnknownErrorMessageResponse) HasCode() bool { if o != nil && o.Code != nil { return true } return false } // SetCode gets a reference to the given NotFoundErrorCode and assigns it to the Code field. func (o *PathUnknownErrorMessageResponse) SetCode(v NotFoundErrorCode) { o.Code = &v } // GetMessage returns the Message field value if set, zero value otherwise. func (o *PathUnknownErrorMessageResponse) GetMessage() string { if o == nil || o.Message == nil { var ret string return ret } return *o.Message } // GetMessageOk returns a tuple with the Message field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *PathUnknownErrorMessageResponse) GetMessageOk() (*string, bool) { if o == nil || o.Message == nil { return nil, false } return o.Message, true } // HasMessage returns a boolean if a field has been set. func (o *PathUnknownErrorMessageResponse) HasMessage() bool { if o != nil && o.Message != nil { return true } return false } // SetMessage gets a reference to the given string and assigns it to the Message field. func (o *PathUnknownErrorMessageResponse) SetMessage(v string) { o.Message = &v } func (o PathUnknownErrorMessageResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Code != nil { toSerialize["code"] = o.Code } if o.Message != nil { toSerialize["message"] = o.Message } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullablePathUnknownErrorMessageResponse struct { value *PathUnknownErrorMessageResponse isSet bool } func (v NullablePathUnknownErrorMessageResponse) Get() *PathUnknownErrorMessageResponse { return v.value } func (v *NullablePathUnknownErrorMessageResponse) Set(val *PathUnknownErrorMessageResponse) { v.value = val v.isSet = true } func (v NullablePathUnknownErrorMessageResponse) IsSet() bool { return v.isSet } func (v *NullablePathUnknownErrorMessageResponse) Unset() { v.value = nil v.isSet = false } func NewNullablePathUnknownErrorMessageResponse(val *PathUnknownErrorMessageResponse) *NullablePathUnknownErrorMessageResponse { return &NullablePathUnknownErrorMessageResponse{value: val, isSet: true} } func (v NullablePathUnknownErrorMessageResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullablePathUnknownErrorMessageResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_read_assertions_response.go000066400000000000000000000105041456721040100256570ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ReadAssertionsResponse struct for ReadAssertionsResponse type ReadAssertionsResponse struct { AuthorizationModelId string `json:"authorization_model_id"yaml:"authorization_model_id"` Assertions *[]Assertion `json:"assertions,omitempty"yaml:"assertions,omitempty"` } // NewReadAssertionsResponse instantiates a new ReadAssertionsResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewReadAssertionsResponse(authorizationModelId string) *ReadAssertionsResponse { this := ReadAssertionsResponse{} this.AuthorizationModelId = authorizationModelId return &this } // NewReadAssertionsResponseWithDefaults instantiates a new ReadAssertionsResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewReadAssertionsResponseWithDefaults() *ReadAssertionsResponse { this := ReadAssertionsResponse{} return &this } // GetAuthorizationModelId returns the AuthorizationModelId field value func (o *ReadAssertionsResponse) GetAuthorizationModelId() string { if o == nil { var ret string return ret } return o.AuthorizationModelId } // GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field value // and a boolean to check if the value has been set. func (o *ReadAssertionsResponse) GetAuthorizationModelIdOk() (*string, bool) { if o == nil { return nil, false } return &o.AuthorizationModelId, true } // SetAuthorizationModelId sets field value func (o *ReadAssertionsResponse) SetAuthorizationModelId(v string) { o.AuthorizationModelId = v } // GetAssertions returns the Assertions field value if set, zero value otherwise. func (o *ReadAssertionsResponse) GetAssertions() []Assertion { if o == nil || o.Assertions == nil { var ret []Assertion return ret } return *o.Assertions } // GetAssertionsOk returns a tuple with the Assertions field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ReadAssertionsResponse) GetAssertionsOk() (*[]Assertion, bool) { if o == nil || o.Assertions == nil { return nil, false } return o.Assertions, true } // HasAssertions returns a boolean if a field has been set. func (o *ReadAssertionsResponse) HasAssertions() bool { if o != nil && o.Assertions != nil { return true } return false } // SetAssertions gets a reference to the given []Assertion and assigns it to the Assertions field. func (o *ReadAssertionsResponse) SetAssertions(v []Assertion) { o.Assertions = &v } func (o ReadAssertionsResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["authorization_model_id"] = o.AuthorizationModelId if o.Assertions != nil { toSerialize["assertions"] = o.Assertions } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableReadAssertionsResponse struct { value *ReadAssertionsResponse isSet bool } func (v NullableReadAssertionsResponse) Get() *ReadAssertionsResponse { return v.value } func (v *NullableReadAssertionsResponse) Set(val *ReadAssertionsResponse) { v.value = val v.isSet = true } func (v NullableReadAssertionsResponse) IsSet() bool { return v.isSet } func (v *NullableReadAssertionsResponse) Unset() { v.value = nil v.isSet = false } func NewNullableReadAssertionsResponse(val *ReadAssertionsResponse) *NullableReadAssertionsResponse { return &NullableReadAssertionsResponse{value: val, isSet: true} } func (v NullableReadAssertionsResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableReadAssertionsResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_read_authorization_model_response.go000066400000000000000000000076311456721040100275540ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ReadAuthorizationModelResponse struct for ReadAuthorizationModelResponse type ReadAuthorizationModelResponse struct { AuthorizationModel *AuthorizationModel `json:"authorization_model,omitempty"yaml:"authorization_model,omitempty"` } // NewReadAuthorizationModelResponse instantiates a new ReadAuthorizationModelResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewReadAuthorizationModelResponse() *ReadAuthorizationModelResponse { this := ReadAuthorizationModelResponse{} return &this } // NewReadAuthorizationModelResponseWithDefaults instantiates a new ReadAuthorizationModelResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewReadAuthorizationModelResponseWithDefaults() *ReadAuthorizationModelResponse { this := ReadAuthorizationModelResponse{} return &this } // GetAuthorizationModel returns the AuthorizationModel field value if set, zero value otherwise. func (o *ReadAuthorizationModelResponse) GetAuthorizationModel() AuthorizationModel { if o == nil || o.AuthorizationModel == nil { var ret AuthorizationModel return ret } return *o.AuthorizationModel } // GetAuthorizationModelOk returns a tuple with the AuthorizationModel field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ReadAuthorizationModelResponse) GetAuthorizationModelOk() (*AuthorizationModel, bool) { if o == nil || o.AuthorizationModel == nil { return nil, false } return o.AuthorizationModel, true } // HasAuthorizationModel returns a boolean if a field has been set. func (o *ReadAuthorizationModelResponse) HasAuthorizationModel() bool { if o != nil && o.AuthorizationModel != nil { return true } return false } // SetAuthorizationModel gets a reference to the given AuthorizationModel and assigns it to the AuthorizationModel field. func (o *ReadAuthorizationModelResponse) SetAuthorizationModel(v AuthorizationModel) { o.AuthorizationModel = &v } func (o ReadAuthorizationModelResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.AuthorizationModel != nil { toSerialize["authorization_model"] = o.AuthorizationModel } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableReadAuthorizationModelResponse struct { value *ReadAuthorizationModelResponse isSet bool } func (v NullableReadAuthorizationModelResponse) Get() *ReadAuthorizationModelResponse { return v.value } func (v *NullableReadAuthorizationModelResponse) Set(val *ReadAuthorizationModelResponse) { v.value = val v.isSet = true } func (v NullableReadAuthorizationModelResponse) IsSet() bool { return v.isSet } func (v *NullableReadAuthorizationModelResponse) Unset() { v.value = nil v.isSet = false } func NewNullableReadAuthorizationModelResponse(val *ReadAuthorizationModelResponse) *NullableReadAuthorizationModelResponse { return &NullableReadAuthorizationModelResponse{value: val, isSet: true} } func (v NullableReadAuthorizationModelResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableReadAuthorizationModelResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_read_authorization_models_response.go000066400000000000000000000115711456721040100277350ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ReadAuthorizationModelsResponse struct for ReadAuthorizationModelsResponse type ReadAuthorizationModelsResponse struct { AuthorizationModels []AuthorizationModel `json:"authorization_models"yaml:"authorization_models"` // The continuation token will be empty if there are no more models. ContinuationToken *string `json:"continuation_token,omitempty"yaml:"continuation_token,omitempty"` } // NewReadAuthorizationModelsResponse instantiates a new ReadAuthorizationModelsResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewReadAuthorizationModelsResponse(authorizationModels []AuthorizationModel) *ReadAuthorizationModelsResponse { this := ReadAuthorizationModelsResponse{} this.AuthorizationModels = authorizationModels return &this } // NewReadAuthorizationModelsResponseWithDefaults instantiates a new ReadAuthorizationModelsResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewReadAuthorizationModelsResponseWithDefaults() *ReadAuthorizationModelsResponse { this := ReadAuthorizationModelsResponse{} return &this } // GetAuthorizationModels returns the AuthorizationModels field value func (o *ReadAuthorizationModelsResponse) GetAuthorizationModels() []AuthorizationModel { if o == nil { var ret []AuthorizationModel return ret } return o.AuthorizationModels } // GetAuthorizationModelsOk returns a tuple with the AuthorizationModels field value // and a boolean to check if the value has been set. func (o *ReadAuthorizationModelsResponse) GetAuthorizationModelsOk() (*[]AuthorizationModel, bool) { if o == nil { return nil, false } return &o.AuthorizationModels, true } // SetAuthorizationModels sets field value func (o *ReadAuthorizationModelsResponse) SetAuthorizationModels(v []AuthorizationModel) { o.AuthorizationModels = v } // GetContinuationToken returns the ContinuationToken field value if set, zero value otherwise. func (o *ReadAuthorizationModelsResponse) GetContinuationToken() string { if o == nil || o.ContinuationToken == nil { var ret string return ret } return *o.ContinuationToken } // GetContinuationTokenOk returns a tuple with the ContinuationToken field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ReadAuthorizationModelsResponse) GetContinuationTokenOk() (*string, bool) { if o == nil || o.ContinuationToken == nil { return nil, false } return o.ContinuationToken, true } // HasContinuationToken returns a boolean if a field has been set. func (o *ReadAuthorizationModelsResponse) HasContinuationToken() bool { if o != nil && o.ContinuationToken != nil { return true } return false } // SetContinuationToken gets a reference to the given string and assigns it to the ContinuationToken field. func (o *ReadAuthorizationModelsResponse) SetContinuationToken(v string) { o.ContinuationToken = &v } func (o ReadAuthorizationModelsResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["authorization_models"] = o.AuthorizationModels if o.ContinuationToken != nil { toSerialize["continuation_token"] = o.ContinuationToken } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableReadAuthorizationModelsResponse struct { value *ReadAuthorizationModelsResponse isSet bool } func (v NullableReadAuthorizationModelsResponse) Get() *ReadAuthorizationModelsResponse { return v.value } func (v *NullableReadAuthorizationModelsResponse) Set(val *ReadAuthorizationModelsResponse) { v.value = val v.isSet = true } func (v NullableReadAuthorizationModelsResponse) IsSet() bool { return v.isSet } func (v *NullableReadAuthorizationModelsResponse) Unset() { v.value = nil v.isSet = false } func NewNullableReadAuthorizationModelsResponse(val *ReadAuthorizationModelsResponse) *NullableReadAuthorizationModelsResponse { return &NullableReadAuthorizationModelsResponse{value: val, isSet: true} } func (v NullableReadAuthorizationModelsResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableReadAuthorizationModelsResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_read_changes_response.go000066400000000000000000000103101456721040100250700ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ReadChangesResponse struct for ReadChangesResponse type ReadChangesResponse struct { Changes []TupleChange `json:"changes"yaml:"changes"` // The continuation token will be identical if there are no new changes. ContinuationToken *string `json:"continuation_token,omitempty"yaml:"continuation_token,omitempty"` } // NewReadChangesResponse instantiates a new ReadChangesResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewReadChangesResponse(changes []TupleChange) *ReadChangesResponse { this := ReadChangesResponse{} this.Changes = changes return &this } // NewReadChangesResponseWithDefaults instantiates a new ReadChangesResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewReadChangesResponseWithDefaults() *ReadChangesResponse { this := ReadChangesResponse{} return &this } // GetChanges returns the Changes field value func (o *ReadChangesResponse) GetChanges() []TupleChange { if o == nil { var ret []TupleChange return ret } return o.Changes } // GetChangesOk returns a tuple with the Changes field value // and a boolean to check if the value has been set. func (o *ReadChangesResponse) GetChangesOk() (*[]TupleChange, bool) { if o == nil { return nil, false } return &o.Changes, true } // SetChanges sets field value func (o *ReadChangesResponse) SetChanges(v []TupleChange) { o.Changes = v } // GetContinuationToken returns the ContinuationToken field value if set, zero value otherwise. func (o *ReadChangesResponse) GetContinuationToken() string { if o == nil || o.ContinuationToken == nil { var ret string return ret } return *o.ContinuationToken } // GetContinuationTokenOk returns a tuple with the ContinuationToken field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ReadChangesResponse) GetContinuationTokenOk() (*string, bool) { if o == nil || o.ContinuationToken == nil { return nil, false } return o.ContinuationToken, true } // HasContinuationToken returns a boolean if a field has been set. func (o *ReadChangesResponse) HasContinuationToken() bool { if o != nil && o.ContinuationToken != nil { return true } return false } // SetContinuationToken gets a reference to the given string and assigns it to the ContinuationToken field. func (o *ReadChangesResponse) SetContinuationToken(v string) { o.ContinuationToken = &v } func (o ReadChangesResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["changes"] = o.Changes if o.ContinuationToken != nil { toSerialize["continuation_token"] = o.ContinuationToken } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableReadChangesResponse struct { value *ReadChangesResponse isSet bool } func (v NullableReadChangesResponse) Get() *ReadChangesResponse { return v.value } func (v *NullableReadChangesResponse) Set(val *ReadChangesResponse) { v.value = val v.isSet = true } func (v NullableReadChangesResponse) IsSet() bool { return v.isSet } func (v *NullableReadChangesResponse) Unset() { v.value = nil v.isSet = false } func NewNullableReadChangesResponse(val *ReadChangesResponse) *NullableReadChangesResponse { return &NullableReadChangesResponse{value: val, isSet: true} } func (v NullableReadChangesResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableReadChangesResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_read_request.go000066400000000000000000000123271456721040100232440ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ReadRequest struct for ReadRequest type ReadRequest struct { TupleKey *ReadRequestTupleKey `json:"tuple_key,omitempty"yaml:"tuple_key,omitempty"` PageSize *int32 `json:"page_size,omitempty"yaml:"page_size,omitempty"` ContinuationToken *string `json:"continuation_token,omitempty"yaml:"continuation_token,omitempty"` } // NewReadRequest instantiates a new ReadRequest object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewReadRequest() *ReadRequest { this := ReadRequest{} return &this } // NewReadRequestWithDefaults instantiates a new ReadRequest object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewReadRequestWithDefaults() *ReadRequest { this := ReadRequest{} return &this } // GetTupleKey returns the TupleKey field value if set, zero value otherwise. func (o *ReadRequest) GetTupleKey() ReadRequestTupleKey { if o == nil || o.TupleKey == nil { var ret ReadRequestTupleKey return ret } return *o.TupleKey } // GetTupleKeyOk returns a tuple with the TupleKey field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ReadRequest) GetTupleKeyOk() (*ReadRequestTupleKey, bool) { if o == nil || o.TupleKey == nil { return nil, false } return o.TupleKey, true } // HasTupleKey returns a boolean if a field has been set. func (o *ReadRequest) HasTupleKey() bool { if o != nil && o.TupleKey != nil { return true } return false } // SetTupleKey gets a reference to the given ReadRequestTupleKey and assigns it to the TupleKey field. func (o *ReadRequest) SetTupleKey(v ReadRequestTupleKey) { o.TupleKey = &v } // GetPageSize returns the PageSize field value if set, zero value otherwise. func (o *ReadRequest) GetPageSize() int32 { if o == nil || o.PageSize == nil { var ret int32 return ret } return *o.PageSize } // GetPageSizeOk returns a tuple with the PageSize field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ReadRequest) GetPageSizeOk() (*int32, bool) { if o == nil || o.PageSize == nil { return nil, false } return o.PageSize, true } // HasPageSize returns a boolean if a field has been set. func (o *ReadRequest) HasPageSize() bool { if o != nil && o.PageSize != nil { return true } return false } // SetPageSize gets a reference to the given int32 and assigns it to the PageSize field. func (o *ReadRequest) SetPageSize(v int32) { o.PageSize = &v } // GetContinuationToken returns the ContinuationToken field value if set, zero value otherwise. func (o *ReadRequest) GetContinuationToken() string { if o == nil || o.ContinuationToken == nil { var ret string return ret } return *o.ContinuationToken } // GetContinuationTokenOk returns a tuple with the ContinuationToken field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ReadRequest) GetContinuationTokenOk() (*string, bool) { if o == nil || o.ContinuationToken == nil { return nil, false } return o.ContinuationToken, true } // HasContinuationToken returns a boolean if a field has been set. func (o *ReadRequest) HasContinuationToken() bool { if o != nil && o.ContinuationToken != nil { return true } return false } // SetContinuationToken gets a reference to the given string and assigns it to the ContinuationToken field. func (o *ReadRequest) SetContinuationToken(v string) { o.ContinuationToken = &v } func (o ReadRequest) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.TupleKey != nil { toSerialize["tuple_key"] = o.TupleKey } if o.PageSize != nil { toSerialize["page_size"] = o.PageSize } if o.ContinuationToken != nil { toSerialize["continuation_token"] = o.ContinuationToken } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableReadRequest struct { value *ReadRequest isSet bool } func (v NullableReadRequest) Get() *ReadRequest { return v.value } func (v *NullableReadRequest) Set(val *ReadRequest) { v.value = val v.isSet = true } func (v NullableReadRequest) IsSet() bool { return v.isSet } func (v *NullableReadRequest) Unset() { v.value = nil v.isSet = false } func NewNullableReadRequest(val *ReadRequest) *NullableReadRequest { return &NullableReadRequest{value: val, isSet: true} } func (v NullableReadRequest) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableReadRequest) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_read_request_tuple_key.go000066400000000000000000000121061456721040100253200ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ReadRequestTupleKey struct for ReadRequestTupleKey type ReadRequestTupleKey struct { User *string `json:"user,omitempty"yaml:"user,omitempty"` Relation *string `json:"relation,omitempty"yaml:"relation,omitempty"` Object *string `json:"object,omitempty"yaml:"object,omitempty"` } // NewReadRequestTupleKey instantiates a new ReadRequestTupleKey object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewReadRequestTupleKey() *ReadRequestTupleKey { this := ReadRequestTupleKey{} return &this } // NewReadRequestTupleKeyWithDefaults instantiates a new ReadRequestTupleKey object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewReadRequestTupleKeyWithDefaults() *ReadRequestTupleKey { this := ReadRequestTupleKey{} return &this } // GetUser returns the User field value if set, zero value otherwise. func (o *ReadRequestTupleKey) GetUser() string { if o == nil || o.User == nil { var ret string return ret } return *o.User } // GetUserOk returns a tuple with the User field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ReadRequestTupleKey) GetUserOk() (*string, bool) { if o == nil || o.User == nil { return nil, false } return o.User, true } // HasUser returns a boolean if a field has been set. func (o *ReadRequestTupleKey) HasUser() bool { if o != nil && o.User != nil { return true } return false } // SetUser gets a reference to the given string and assigns it to the User field. func (o *ReadRequestTupleKey) SetUser(v string) { o.User = &v } // GetRelation returns the Relation field value if set, zero value otherwise. func (o *ReadRequestTupleKey) GetRelation() string { if o == nil || o.Relation == nil { var ret string return ret } return *o.Relation } // GetRelationOk returns a tuple with the Relation field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ReadRequestTupleKey) GetRelationOk() (*string, bool) { if o == nil || o.Relation == nil { return nil, false } return o.Relation, true } // HasRelation returns a boolean if a field has been set. func (o *ReadRequestTupleKey) HasRelation() bool { if o != nil && o.Relation != nil { return true } return false } // SetRelation gets a reference to the given string and assigns it to the Relation field. func (o *ReadRequestTupleKey) SetRelation(v string) { o.Relation = &v } // GetObject returns the Object field value if set, zero value otherwise. func (o *ReadRequestTupleKey) GetObject() string { if o == nil || o.Object == nil { var ret string return ret } return *o.Object } // GetObjectOk returns a tuple with the Object field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ReadRequestTupleKey) GetObjectOk() (*string, bool) { if o == nil || o.Object == nil { return nil, false } return o.Object, true } // HasObject returns a boolean if a field has been set. func (o *ReadRequestTupleKey) HasObject() bool { if o != nil && o.Object != nil { return true } return false } // SetObject gets a reference to the given string and assigns it to the Object field. func (o *ReadRequestTupleKey) SetObject(v string) { o.Object = &v } func (o ReadRequestTupleKey) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.User != nil { toSerialize["user"] = o.User } if o.Relation != nil { toSerialize["relation"] = o.Relation } if o.Object != nil { toSerialize["object"] = o.Object } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableReadRequestTupleKey struct { value *ReadRequestTupleKey isSet bool } func (v NullableReadRequestTupleKey) Get() *ReadRequestTupleKey { return v.value } func (v *NullableReadRequestTupleKey) Set(val *ReadRequestTupleKey) { v.value = val v.isSet = true } func (v NullableReadRequestTupleKey) IsSet() bool { return v.isSet } func (v *NullableReadRequestTupleKey) Unset() { v.value = nil v.isSet = false } func NewNullableReadRequestTupleKey(val *ReadRequestTupleKey) *NullableReadRequestTupleKey { return &NullableReadRequestTupleKey{value: val, isSet: true} } func (v NullableReadRequestTupleKey) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableReadRequestTupleKey) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_read_response.go000066400000000000000000000070511456721040100234100ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ReadResponse struct for ReadResponse type ReadResponse struct { Tuples []Tuple `json:"tuples"yaml:"tuples"` // The continuation token will be empty if there are no more tuples. ContinuationToken string `json:"continuation_token"yaml:"continuation_token"` } // NewReadResponse instantiates a new ReadResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewReadResponse(tuples []Tuple, continuationToken string) *ReadResponse { this := ReadResponse{} this.Tuples = tuples this.ContinuationToken = continuationToken return &this } // NewReadResponseWithDefaults instantiates a new ReadResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewReadResponseWithDefaults() *ReadResponse { this := ReadResponse{} return &this } // GetTuples returns the Tuples field value func (o *ReadResponse) GetTuples() []Tuple { if o == nil { var ret []Tuple return ret } return o.Tuples } // GetTuplesOk returns a tuple with the Tuples field value // and a boolean to check if the value has been set. func (o *ReadResponse) GetTuplesOk() (*[]Tuple, bool) { if o == nil { return nil, false } return &o.Tuples, true } // SetTuples sets field value func (o *ReadResponse) SetTuples(v []Tuple) { o.Tuples = v } // GetContinuationToken returns the ContinuationToken field value func (o *ReadResponse) GetContinuationToken() string { if o == nil { var ret string return ret } return o.ContinuationToken } // GetContinuationTokenOk returns a tuple with the ContinuationToken field value // and a boolean to check if the value has been set. func (o *ReadResponse) GetContinuationTokenOk() (*string, bool) { if o == nil { return nil, false } return &o.ContinuationToken, true } // SetContinuationToken sets field value func (o *ReadResponse) SetContinuationToken(v string) { o.ContinuationToken = v } func (o ReadResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tuples"] = o.Tuples toSerialize["continuation_token"] = o.ContinuationToken var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableReadResponse struct { value *ReadResponse isSet bool } func (v NullableReadResponse) Get() *ReadResponse { return v.value } func (v *NullableReadResponse) Set(val *ReadResponse) { v.value = val v.isSet = true } func (v NullableReadResponse) IsSet() bool { return v.isSet } func (v *NullableReadResponse) Unset() { v.value = nil v.isSet = false } func NewNullableReadResponse(val *ReadResponse) *NullableReadResponse { return &NullableReadResponse{value: val, isSet: true} } func (v NullableReadResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableReadResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_relation_metadata.go000066400000000000000000000071571456721040100242430ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // RelationMetadata struct for RelationMetadata type RelationMetadata struct { DirectlyRelatedUserTypes *[]RelationReference `json:"directly_related_user_types,omitempty"yaml:"directly_related_user_types,omitempty"` } // NewRelationMetadata instantiates a new RelationMetadata object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewRelationMetadata() *RelationMetadata { this := RelationMetadata{} return &this } // NewRelationMetadataWithDefaults instantiates a new RelationMetadata object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewRelationMetadataWithDefaults() *RelationMetadata { this := RelationMetadata{} return &this } // GetDirectlyRelatedUserTypes returns the DirectlyRelatedUserTypes field value if set, zero value otherwise. func (o *RelationMetadata) GetDirectlyRelatedUserTypes() []RelationReference { if o == nil || o.DirectlyRelatedUserTypes == nil { var ret []RelationReference return ret } return *o.DirectlyRelatedUserTypes } // GetDirectlyRelatedUserTypesOk returns a tuple with the DirectlyRelatedUserTypes field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RelationMetadata) GetDirectlyRelatedUserTypesOk() (*[]RelationReference, bool) { if o == nil || o.DirectlyRelatedUserTypes == nil { return nil, false } return o.DirectlyRelatedUserTypes, true } // HasDirectlyRelatedUserTypes returns a boolean if a field has been set. func (o *RelationMetadata) HasDirectlyRelatedUserTypes() bool { if o != nil && o.DirectlyRelatedUserTypes != nil { return true } return false } // SetDirectlyRelatedUserTypes gets a reference to the given []RelationReference and assigns it to the DirectlyRelatedUserTypes field. func (o *RelationMetadata) SetDirectlyRelatedUserTypes(v []RelationReference) { o.DirectlyRelatedUserTypes = &v } func (o RelationMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.DirectlyRelatedUserTypes != nil { toSerialize["directly_related_user_types"] = o.DirectlyRelatedUserTypes } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableRelationMetadata struct { value *RelationMetadata isSet bool } func (v NullableRelationMetadata) Get() *RelationMetadata { return v.value } func (v *NullableRelationMetadata) Set(val *RelationMetadata) { v.value = val v.isSet = true } func (v NullableRelationMetadata) IsSet() bool { return v.isSet } func (v *NullableRelationMetadata) Unset() { v.value = nil v.isSet = false } func NewNullableRelationMetadata(val *RelationMetadata) *NullableRelationMetadata { return &NullableRelationMetadata{value: val, isSet: true} } func (v NullableRelationMetadata) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableRelationMetadata) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_relation_reference.go000066400000000000000000000137341456721040100244170ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // RelationReference RelationReference represents a relation of a particular object type (e.g. 'document#viewer'). type RelationReference struct { Type string `json:"type"yaml:"type"` Relation *string `json:"relation,omitempty"yaml:"relation,omitempty"` Wildcard *map[string]interface{} `json:"wildcard,omitempty"yaml:"wildcard,omitempty"` // The name of a condition that is enforced over the allowed relation. Condition *string `json:"condition,omitempty"yaml:"condition,omitempty"` } // NewRelationReference instantiates a new RelationReference object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewRelationReference(type_ string) *RelationReference { this := RelationReference{} this.Type = type_ return &this } // NewRelationReferenceWithDefaults instantiates a new RelationReference object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewRelationReferenceWithDefaults() *RelationReference { this := RelationReference{} return &this } // GetType returns the Type field value func (o *RelationReference) GetType() string { if o == nil { var ret string return ret } return o.Type } // GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. func (o *RelationReference) GetTypeOk() (*string, bool) { if o == nil { return nil, false } return &o.Type, true } // SetType sets field value func (o *RelationReference) SetType(v string) { o.Type = v } // GetRelation returns the Relation field value if set, zero value otherwise. func (o *RelationReference) GetRelation() string { if o == nil || o.Relation == nil { var ret string return ret } return *o.Relation } // GetRelationOk returns a tuple with the Relation field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RelationReference) GetRelationOk() (*string, bool) { if o == nil || o.Relation == nil { return nil, false } return o.Relation, true } // HasRelation returns a boolean if a field has been set. func (o *RelationReference) HasRelation() bool { if o != nil && o.Relation != nil { return true } return false } // SetRelation gets a reference to the given string and assigns it to the Relation field. func (o *RelationReference) SetRelation(v string) { o.Relation = &v } // GetWildcard returns the Wildcard field value if set, zero value otherwise. func (o *RelationReference) GetWildcard() map[string]interface{} { if o == nil || o.Wildcard == nil { var ret map[string]interface{} return ret } return *o.Wildcard } // GetWildcardOk returns a tuple with the Wildcard field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RelationReference) GetWildcardOk() (*map[string]interface{}, bool) { if o == nil || o.Wildcard == nil { return nil, false } return o.Wildcard, true } // HasWildcard returns a boolean if a field has been set. func (o *RelationReference) HasWildcard() bool { if o != nil && o.Wildcard != nil { return true } return false } // SetWildcard gets a reference to the given map[string]interface{} and assigns it to the Wildcard field. func (o *RelationReference) SetWildcard(v map[string]interface{}) { o.Wildcard = &v } // GetCondition returns the Condition field value if set, zero value otherwise. func (o *RelationReference) GetCondition() string { if o == nil || o.Condition == nil { var ret string return ret } return *o.Condition } // GetConditionOk returns a tuple with the Condition field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RelationReference) GetConditionOk() (*string, bool) { if o == nil || o.Condition == nil { return nil, false } return o.Condition, true } // HasCondition returns a boolean if a field has been set. func (o *RelationReference) HasCondition() bool { if o != nil && o.Condition != nil { return true } return false } // SetCondition gets a reference to the given string and assigns it to the Condition field. func (o *RelationReference) SetCondition(v string) { o.Condition = &v } func (o RelationReference) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["type"] = o.Type if o.Relation != nil { toSerialize["relation"] = o.Relation } if o.Wildcard != nil { toSerialize["wildcard"] = o.Wildcard } if o.Condition != nil { toSerialize["condition"] = o.Condition } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableRelationReference struct { value *RelationReference isSet bool } func (v NullableRelationReference) Get() *RelationReference { return v.value } func (v *NullableRelationReference) Set(val *RelationReference) { v.value = val v.isSet = true } func (v NullableRelationReference) IsSet() bool { return v.isSet } func (v *NullableRelationReference) Unset() { v.value = nil v.isSet = false } func NewNullableRelationReference(val *RelationReference) *NullableRelationReference { return &NullableRelationReference{value: val, isSet: true} } func (v NullableRelationReference) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableRelationReference) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_relationship_condition.go000066400000000000000000000103611456721040100253240ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // RelationshipCondition struct for RelationshipCondition type RelationshipCondition struct { // A reference (by name) of the relationship condition defined in the authorization model. Name string `json:"name"yaml:"name"` // Additional context/data to persist along with the condition. The keys must match the parameters defined by the condition, and the value types must match the parameter type definitions. Context *map[string]interface{} `json:"context,omitempty"yaml:"context,omitempty"` } // NewRelationshipCondition instantiates a new RelationshipCondition object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewRelationshipCondition(name string) *RelationshipCondition { this := RelationshipCondition{} this.Name = name return &this } // NewRelationshipConditionWithDefaults instantiates a new RelationshipCondition object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewRelationshipConditionWithDefaults() *RelationshipCondition { this := RelationshipCondition{} return &this } // GetName returns the Name field value func (o *RelationshipCondition) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *RelationshipCondition) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *RelationshipCondition) SetName(v string) { o.Name = v } // GetContext returns the Context field value if set, zero value otherwise. func (o *RelationshipCondition) GetContext() map[string]interface{} { if o == nil || o.Context == nil { var ret map[string]interface{} return ret } return *o.Context } // GetContextOk returns a tuple with the Context field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RelationshipCondition) GetContextOk() (*map[string]interface{}, bool) { if o == nil || o.Context == nil { return nil, false } return o.Context, true } // HasContext returns a boolean if a field has been set. func (o *RelationshipCondition) HasContext() bool { if o != nil && o.Context != nil { return true } return false } // SetContext gets a reference to the given map[string]interface{} and assigns it to the Context field. func (o *RelationshipCondition) SetContext(v map[string]interface{}) { o.Context = &v } func (o RelationshipCondition) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["name"] = o.Name if o.Context != nil { toSerialize["context"] = o.Context } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableRelationshipCondition struct { value *RelationshipCondition isSet bool } func (v NullableRelationshipCondition) Get() *RelationshipCondition { return v.value } func (v *NullableRelationshipCondition) Set(val *RelationshipCondition) { v.value = val v.isSet = true } func (v NullableRelationshipCondition) IsSet() bool { return v.isSet } func (v *NullableRelationshipCondition) Unset() { v.value = nil v.isSet = false } func NewNullableRelationshipCondition(val *RelationshipCondition) *NullableRelationshipCondition { return &NullableRelationshipCondition{value: val, isSet: true} } func (v NullableRelationshipCondition) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableRelationshipCondition) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_status.go000066400000000000000000000110611456721040100220760ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Status struct for Status type Status struct { Code *int32 `json:"code,omitempty"yaml:"code,omitempty"` Message *string `json:"message,omitempty"yaml:"message,omitempty"` Details *[]Any `json:"details,omitempty"yaml:"details,omitempty"` } // NewStatus instantiates a new Status object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewStatus() *Status { this := Status{} return &this } // NewStatusWithDefaults instantiates a new Status object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewStatusWithDefaults() *Status { this := Status{} return &this } // GetCode returns the Code field value if set, zero value otherwise. func (o *Status) GetCode() int32 { if o == nil || o.Code == nil { var ret int32 return ret } return *o.Code } // GetCodeOk returns a tuple with the Code field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Status) GetCodeOk() (*int32, bool) { if o == nil || o.Code == nil { return nil, false } return o.Code, true } // HasCode returns a boolean if a field has been set. func (o *Status) HasCode() bool { if o != nil && o.Code != nil { return true } return false } // SetCode gets a reference to the given int32 and assigns it to the Code field. func (o *Status) SetCode(v int32) { o.Code = &v } // GetMessage returns the Message field value if set, zero value otherwise. func (o *Status) GetMessage() string { if o == nil || o.Message == nil { var ret string return ret } return *o.Message } // GetMessageOk returns a tuple with the Message field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Status) GetMessageOk() (*string, bool) { if o == nil || o.Message == nil { return nil, false } return o.Message, true } // HasMessage returns a boolean if a field has been set. func (o *Status) HasMessage() bool { if o != nil && o.Message != nil { return true } return false } // SetMessage gets a reference to the given string and assigns it to the Message field. func (o *Status) SetMessage(v string) { o.Message = &v } // GetDetails returns the Details field value if set, zero value otherwise. func (o *Status) GetDetails() []Any { if o == nil || o.Details == nil { var ret []Any return ret } return *o.Details } // GetDetailsOk returns a tuple with the Details field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Status) GetDetailsOk() (*[]Any, bool) { if o == nil || o.Details == nil { return nil, false } return o.Details, true } // HasDetails returns a boolean if a field has been set. func (o *Status) HasDetails() bool { if o != nil && o.Details != nil { return true } return false } // SetDetails gets a reference to the given []Any and assigns it to the Details field. func (o *Status) SetDetails(v []Any) { o.Details = &v } func (o Status) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Code != nil { toSerialize["code"] = o.Code } if o.Message != nil { toSerialize["message"] = o.Message } if o.Details != nil { toSerialize["details"] = o.Details } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableStatus struct { value *Status isSet bool } func (v NullableStatus) Get() *Status { return v.value } func (v *NullableStatus) Set(val *Status) { v.value = val v.isSet = true } func (v NullableStatus) IsSet() bool { return v.isSet } func (v *NullableStatus) Unset() { v.value = nil v.isSet = false } func NewNullableStatus(val *Status) *NullableStatus { return &NullableStatus{value: val, isSet: true} } func (v NullableStatus) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableStatus) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_store.go000066400000000000000000000122661456721040100217170ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" "time" ) // Store struct for Store type Store struct { Id string `json:"id"yaml:"id"` Name string `json:"name"yaml:"name"` CreatedAt time.Time `json:"created_at"yaml:"created_at"` UpdatedAt time.Time `json:"updated_at"yaml:"updated_at"` DeletedAt *time.Time `json:"deleted_at,omitempty"yaml:"deleted_at,omitempty"` } // NewStore instantiates a new Store object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewStore(id string, name string, createdAt time.Time, updatedAt time.Time) *Store { this := Store{} this.Id = id this.Name = name this.CreatedAt = createdAt this.UpdatedAt = updatedAt return &this } // NewStoreWithDefaults instantiates a new Store object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewStoreWithDefaults() *Store { this := Store{} return &this } // GetId returns the Id field value func (o *Store) GetId() string { if o == nil { var ret string return ret } return o.Id } // GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. func (o *Store) GetIdOk() (*string, bool) { if o == nil { return nil, false } return &o.Id, true } // SetId sets field value func (o *Store) SetId(v string) { o.Id = v } // GetName returns the Name field value func (o *Store) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *Store) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *Store) SetName(v string) { o.Name = v } // GetCreatedAt returns the CreatedAt field value func (o *Store) GetCreatedAt() time.Time { if o == nil { var ret time.Time return ret } return o.CreatedAt } // GetCreatedAtOk returns a tuple with the CreatedAt field value // and a boolean to check if the value has been set. func (o *Store) GetCreatedAtOk() (*time.Time, bool) { if o == nil { return nil, false } return &o.CreatedAt, true } // SetCreatedAt sets field value func (o *Store) SetCreatedAt(v time.Time) { o.CreatedAt = v } // GetUpdatedAt returns the UpdatedAt field value func (o *Store) GetUpdatedAt() time.Time { if o == nil { var ret time.Time return ret } return o.UpdatedAt } // GetUpdatedAtOk returns a tuple with the UpdatedAt field value // and a boolean to check if the value has been set. func (o *Store) GetUpdatedAtOk() (*time.Time, bool) { if o == nil { return nil, false } return &o.UpdatedAt, true } // SetUpdatedAt sets field value func (o *Store) SetUpdatedAt(v time.Time) { o.UpdatedAt = v } // GetDeletedAt returns the DeletedAt field value if set, zero value otherwise. func (o *Store) GetDeletedAt() time.Time { if o == nil || o.DeletedAt == nil { var ret time.Time return ret } return *o.DeletedAt } // GetDeletedAtOk returns a tuple with the DeletedAt field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Store) GetDeletedAtOk() (*time.Time, bool) { if o == nil || o.DeletedAt == nil { return nil, false } return o.DeletedAt, true } // HasDeletedAt returns a boolean if a field has been set. func (o *Store) HasDeletedAt() bool { if o != nil && o.DeletedAt != nil { return true } return false } // SetDeletedAt gets a reference to the given time.Time and assigns it to the DeletedAt field. func (o *Store) SetDeletedAt(v time.Time) { o.DeletedAt = &v } func (o Store) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["id"] = o.Id toSerialize["name"] = o.Name toSerialize["created_at"] = o.CreatedAt toSerialize["updated_at"] = o.UpdatedAt if o.DeletedAt != nil { toSerialize["deleted_at"] = o.DeletedAt } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableStore struct { value *Store isSet bool } func (v NullableStore) Get() *Store { return v.value } func (v *NullableStore) Set(val *Store) { v.value = val v.isSet = true } func (v NullableStore) IsSet() bool { return v.isSet } func (v *NullableStore) Unset() { v.value = nil v.isSet = false } func NewNullableStore(val *Store) *NullableStore { return &NullableStore{value: val, isSet: true} } func (v NullableStore) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableStore) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_tuple.go000066400000000000000000000061101456721040100217030ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" "time" ) // Tuple struct for Tuple type Tuple struct { Key TupleKey `json:"key"yaml:"key"` Timestamp time.Time `json:"timestamp"yaml:"timestamp"` } // NewTuple instantiates a new Tuple object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewTuple(key TupleKey, timestamp time.Time) *Tuple { this := Tuple{} this.Key = key this.Timestamp = timestamp return &this } // NewTupleWithDefaults instantiates a new Tuple object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewTupleWithDefaults() *Tuple { this := Tuple{} return &this } // GetKey returns the Key field value func (o *Tuple) GetKey() TupleKey { if o == nil { var ret TupleKey return ret } return o.Key } // GetKeyOk returns a tuple with the Key field value // and a boolean to check if the value has been set. func (o *Tuple) GetKeyOk() (*TupleKey, bool) { if o == nil { return nil, false } return &o.Key, true } // SetKey sets field value func (o *Tuple) SetKey(v TupleKey) { o.Key = v } // GetTimestamp returns the Timestamp field value func (o *Tuple) GetTimestamp() time.Time { if o == nil { var ret time.Time return ret } return o.Timestamp } // GetTimestampOk returns a tuple with the Timestamp field value // and a boolean to check if the value has been set. func (o *Tuple) GetTimestampOk() (*time.Time, bool) { if o == nil { return nil, false } return &o.Timestamp, true } // SetTimestamp sets field value func (o *Tuple) SetTimestamp(v time.Time) { o.Timestamp = v } func (o Tuple) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["key"] = o.Key toSerialize["timestamp"] = o.Timestamp var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableTuple struct { value *Tuple isSet bool } func (v NullableTuple) Get() *Tuple { return v.value } func (v *NullableTuple) Set(val *Tuple) { v.value = val v.isSet = true } func (v NullableTuple) IsSet() bool { return v.isSet } func (v *NullableTuple) Unset() { v.value = nil v.isSet = false } func NewNullableTuple(val *Tuple) *NullableTuple { return &NullableTuple{value: val, isSet: true} } func (v NullableTuple) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTuple) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_tuple_change.go000066400000000000000000000101671456721040100232170ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" "time" ) // TupleChange struct for TupleChange type TupleChange struct { TupleKey TupleKey `json:"tuple_key"yaml:"tuple_key"` Operation TupleOperation `json:"operation"yaml:"operation"` Timestamp time.Time `json:"timestamp"yaml:"timestamp"` } // NewTupleChange instantiates a new TupleChange object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewTupleChange(tupleKey TupleKey, operation TupleOperation, timestamp time.Time) *TupleChange { this := TupleChange{} this.TupleKey = tupleKey this.Operation = operation this.Timestamp = timestamp return &this } // NewTupleChangeWithDefaults instantiates a new TupleChange object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewTupleChangeWithDefaults() *TupleChange { this := TupleChange{} var operation TupleOperation = WRITE this.Operation = operation return &this } // GetTupleKey returns the TupleKey field value func (o *TupleChange) GetTupleKey() TupleKey { if o == nil { var ret TupleKey return ret } return o.TupleKey } // GetTupleKeyOk returns a tuple with the TupleKey field value // and a boolean to check if the value has been set. func (o *TupleChange) GetTupleKeyOk() (*TupleKey, bool) { if o == nil { return nil, false } return &o.TupleKey, true } // SetTupleKey sets field value func (o *TupleChange) SetTupleKey(v TupleKey) { o.TupleKey = v } // GetOperation returns the Operation field value func (o *TupleChange) GetOperation() TupleOperation { if o == nil { var ret TupleOperation return ret } return o.Operation } // GetOperationOk returns a tuple with the Operation field value // and a boolean to check if the value has been set. func (o *TupleChange) GetOperationOk() (*TupleOperation, bool) { if o == nil { return nil, false } return &o.Operation, true } // SetOperation sets field value func (o *TupleChange) SetOperation(v TupleOperation) { o.Operation = v } // GetTimestamp returns the Timestamp field value func (o *TupleChange) GetTimestamp() time.Time { if o == nil { var ret time.Time return ret } return o.Timestamp } // GetTimestampOk returns a tuple with the Timestamp field value // and a boolean to check if the value has been set. func (o *TupleChange) GetTimestampOk() (*time.Time, bool) { if o == nil { return nil, false } return &o.Timestamp, true } // SetTimestamp sets field value func (o *TupleChange) SetTimestamp(v time.Time) { o.Timestamp = v } func (o TupleChange) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tuple_key"] = o.TupleKey toSerialize["operation"] = o.Operation toSerialize["timestamp"] = o.Timestamp var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableTupleChange struct { value *TupleChange isSet bool } func (v NullableTupleChange) Get() *TupleChange { return v.value } func (v *NullableTupleChange) Set(val *TupleChange) { v.value = val v.isSet = true } func (v NullableTupleChange) IsSet() bool { return v.isSet } func (v *NullableTupleChange) Unset() { v.value = nil v.isSet = false } func NewNullableTupleChange(val *TupleChange) *NullableTupleChange { return &NullableTupleChange{value: val, isSet: true} } func (v NullableTupleChange) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTupleChange) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_tuple_key.go000066400000000000000000000114501456721040100225560ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // TupleKey struct for TupleKey type TupleKey struct { User string `json:"user"yaml:"user"` Relation string `json:"relation"yaml:"relation"` Object string `json:"object"yaml:"object"` Condition *RelationshipCondition `json:"condition,omitempty"yaml:"condition,omitempty"` } // NewTupleKey instantiates a new TupleKey object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewTupleKey(user string, relation string, object string) *TupleKey { this := TupleKey{} this.User = user this.Relation = relation this.Object = object return &this } // NewTupleKeyWithDefaults instantiates a new TupleKey object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewTupleKeyWithDefaults() *TupleKey { this := TupleKey{} return &this } // GetUser returns the User field value func (o *TupleKey) GetUser() string { if o == nil { var ret string return ret } return o.User } // GetUserOk returns a tuple with the User field value // and a boolean to check if the value has been set. func (o *TupleKey) GetUserOk() (*string, bool) { if o == nil { return nil, false } return &o.User, true } // SetUser sets field value func (o *TupleKey) SetUser(v string) { o.User = v } // GetRelation returns the Relation field value func (o *TupleKey) GetRelation() string { if o == nil { var ret string return ret } return o.Relation } // GetRelationOk returns a tuple with the Relation field value // and a boolean to check if the value has been set. func (o *TupleKey) GetRelationOk() (*string, bool) { if o == nil { return nil, false } return &o.Relation, true } // SetRelation sets field value func (o *TupleKey) SetRelation(v string) { o.Relation = v } // GetObject returns the Object field value func (o *TupleKey) GetObject() string { if o == nil { var ret string return ret } return o.Object } // GetObjectOk returns a tuple with the Object field value // and a boolean to check if the value has been set. func (o *TupleKey) GetObjectOk() (*string, bool) { if o == nil { return nil, false } return &o.Object, true } // SetObject sets field value func (o *TupleKey) SetObject(v string) { o.Object = v } // GetCondition returns the Condition field value if set, zero value otherwise. func (o *TupleKey) GetCondition() RelationshipCondition { if o == nil || o.Condition == nil { var ret RelationshipCondition return ret } return *o.Condition } // GetConditionOk returns a tuple with the Condition field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TupleKey) GetConditionOk() (*RelationshipCondition, bool) { if o == nil || o.Condition == nil { return nil, false } return o.Condition, true } // HasCondition returns a boolean if a field has been set. func (o *TupleKey) HasCondition() bool { if o != nil && o.Condition != nil { return true } return false } // SetCondition gets a reference to the given RelationshipCondition and assigns it to the Condition field. func (o *TupleKey) SetCondition(v RelationshipCondition) { o.Condition = &v } func (o TupleKey) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["user"] = o.User toSerialize["relation"] = o.Relation toSerialize["object"] = o.Object if o.Condition != nil { toSerialize["condition"] = o.Condition } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableTupleKey struct { value *TupleKey isSet bool } func (v NullableTupleKey) Get() *TupleKey { return v.value } func (v *NullableTupleKey) Set(val *TupleKey) { v.value = val v.isSet = true } func (v NullableTupleKey) IsSet() bool { return v.isSet } func (v *NullableTupleKey) Unset() { v.value = nil v.isSet = false } func NewNullableTupleKey(val *TupleKey) *NullableTupleKey { return &NullableTupleKey{value: val, isSet: true} } func (v NullableTupleKey) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTupleKey) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_tuple_key_without_condition.go000066400000000000000000000104371456721040100264130ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // TupleKeyWithoutCondition struct for TupleKeyWithoutCondition type TupleKeyWithoutCondition struct { User string `json:"user"yaml:"user"` Relation string `json:"relation"yaml:"relation"` Object string `json:"object"yaml:"object"` } // NewTupleKeyWithoutCondition instantiates a new TupleKeyWithoutCondition object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewTupleKeyWithoutCondition(user string, relation string, object string) *TupleKeyWithoutCondition { this := TupleKeyWithoutCondition{} this.User = user this.Relation = relation this.Object = object return &this } // NewTupleKeyWithoutConditionWithDefaults instantiates a new TupleKeyWithoutCondition object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewTupleKeyWithoutConditionWithDefaults() *TupleKeyWithoutCondition { this := TupleKeyWithoutCondition{} return &this } // GetUser returns the User field value func (o *TupleKeyWithoutCondition) GetUser() string { if o == nil { var ret string return ret } return o.User } // GetUserOk returns a tuple with the User field value // and a boolean to check if the value has been set. func (o *TupleKeyWithoutCondition) GetUserOk() (*string, bool) { if o == nil { return nil, false } return &o.User, true } // SetUser sets field value func (o *TupleKeyWithoutCondition) SetUser(v string) { o.User = v } // GetRelation returns the Relation field value func (o *TupleKeyWithoutCondition) GetRelation() string { if o == nil { var ret string return ret } return o.Relation } // GetRelationOk returns a tuple with the Relation field value // and a boolean to check if the value has been set. func (o *TupleKeyWithoutCondition) GetRelationOk() (*string, bool) { if o == nil { return nil, false } return &o.Relation, true } // SetRelation sets field value func (o *TupleKeyWithoutCondition) SetRelation(v string) { o.Relation = v } // GetObject returns the Object field value func (o *TupleKeyWithoutCondition) GetObject() string { if o == nil { var ret string return ret } return o.Object } // GetObjectOk returns a tuple with the Object field value // and a boolean to check if the value has been set. func (o *TupleKeyWithoutCondition) GetObjectOk() (*string, bool) { if o == nil { return nil, false } return &o.Object, true } // SetObject sets field value func (o *TupleKeyWithoutCondition) SetObject(v string) { o.Object = v } func (o TupleKeyWithoutCondition) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["user"] = o.User toSerialize["relation"] = o.Relation toSerialize["object"] = o.Object var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableTupleKeyWithoutCondition struct { value *TupleKeyWithoutCondition isSet bool } func (v NullableTupleKeyWithoutCondition) Get() *TupleKeyWithoutCondition { return v.value } func (v *NullableTupleKeyWithoutCondition) Set(val *TupleKeyWithoutCondition) { v.value = val v.isSet = true } func (v NullableTupleKeyWithoutCondition) IsSet() bool { return v.isSet } func (v *NullableTupleKeyWithoutCondition) Unset() { v.value = nil v.isSet = false } func NewNullableTupleKeyWithoutCondition(val *TupleKeyWithoutCondition) *NullableTupleKeyWithoutCondition { return &NullableTupleKeyWithoutCondition{value: val, isSet: true} } func (v NullableTupleKeyWithoutCondition) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTupleKeyWithoutCondition) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_tuple_operation.go000066400000000000000000000051361456721040100237720ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "encoding/json" "fmt" ) // TupleOperation the model 'TupleOperation' type TupleOperation string // List of TupleOperation const ( WRITE TupleOperation = "TUPLE_OPERATION_WRITE" DELETE TupleOperation = "TUPLE_OPERATION_DELETE" ) var allowedTupleOperationEnumValues = []TupleOperation{ "TUPLE_OPERATION_WRITE", "TUPLE_OPERATION_DELETE", } func (v *TupleOperation) UnmarshalJSON(src []byte) error { var value string err := json.Unmarshal(src, &value) if err != nil { return err } enumTypeValue := TupleOperation(value) for _, existing := range allowedTupleOperationEnumValues { if existing == enumTypeValue { *v = enumTypeValue return nil } } return fmt.Errorf("%+v is not a valid TupleOperation", value) } // NewTupleOperationFromValue returns a pointer to a valid TupleOperation // for the value passed as argument, or an error if the value passed is not allowed by the enum func NewTupleOperationFromValue(v string) (*TupleOperation, error) { ev := TupleOperation(v) if ev.IsValid() { return &ev, nil } else { return nil, fmt.Errorf("invalid value '%v' for TupleOperation: valid values are %v", v, allowedTupleOperationEnumValues) } } // IsValid return true if the value is valid for the enum, false otherwise func (v TupleOperation) IsValid() bool { for _, existing := range allowedTupleOperationEnumValues { if existing == v { return true } } return false } // Ptr returns reference to TupleOperation value func (v TupleOperation) Ptr() *TupleOperation { return &v } type NullableTupleOperation struct { value *TupleOperation isSet bool } func (v NullableTupleOperation) Get() *TupleOperation { return v.value } func (v *NullableTupleOperation) Set(val *TupleOperation) { v.value = val v.isSet = true } func (v NullableTupleOperation) IsSet() bool { return v.isSet } func (v *NullableTupleOperation) Unset() { v.value = nil v.isSet = false } func NewNullableTupleOperation(val *TupleOperation) *NullableTupleOperation { return &NullableTupleOperation{value: val, isSet: true} } func (v NullableTupleOperation) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTupleOperation) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_tuple_to_userset.go000066400000000000000000000072051456721040100241650ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // TupleToUserset struct for TupleToUserset type TupleToUserset struct { Tupleset ObjectRelation `json:"tupleset"yaml:"tupleset"` ComputedUserset ObjectRelation `json:"computedUserset"yaml:"computedUserset"` } // NewTupleToUserset instantiates a new TupleToUserset object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewTupleToUserset(tupleset ObjectRelation, computedUserset ObjectRelation) *TupleToUserset { this := TupleToUserset{} this.Tupleset = tupleset this.ComputedUserset = computedUserset return &this } // NewTupleToUsersetWithDefaults instantiates a new TupleToUserset object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewTupleToUsersetWithDefaults() *TupleToUserset { this := TupleToUserset{} return &this } // GetTupleset returns the Tupleset field value func (o *TupleToUserset) GetTupleset() ObjectRelation { if o == nil { var ret ObjectRelation return ret } return o.Tupleset } // GetTuplesetOk returns a tuple with the Tupleset field value // and a boolean to check if the value has been set. func (o *TupleToUserset) GetTuplesetOk() (*ObjectRelation, bool) { if o == nil { return nil, false } return &o.Tupleset, true } // SetTupleset sets field value func (o *TupleToUserset) SetTupleset(v ObjectRelation) { o.Tupleset = v } // GetComputedUserset returns the ComputedUserset field value func (o *TupleToUserset) GetComputedUserset() ObjectRelation { if o == nil { var ret ObjectRelation return ret } return o.ComputedUserset } // GetComputedUsersetOk returns a tuple with the ComputedUserset field value // and a boolean to check if the value has been set. func (o *TupleToUserset) GetComputedUsersetOk() (*ObjectRelation, bool) { if o == nil { return nil, false } return &o.ComputedUserset, true } // SetComputedUserset sets field value func (o *TupleToUserset) SetComputedUserset(v ObjectRelation) { o.ComputedUserset = v } func (o TupleToUserset) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tupleset"] = o.Tupleset toSerialize["computedUserset"] = o.ComputedUserset var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableTupleToUserset struct { value *TupleToUserset isSet bool } func (v NullableTupleToUserset) Get() *TupleToUserset { return v.value } func (v *NullableTupleToUserset) Set(val *TupleToUserset) { v.value = val v.isSet = true } func (v NullableTupleToUserset) IsSet() bool { return v.isSet } func (v *NullableTupleToUserset) Unset() { v.value = nil v.isSet = false } func NewNullableTupleToUserset(val *TupleToUserset) *NullableTupleToUserset { return &NullableTupleToUserset{value: val, isSet: true} } func (v NullableTupleToUserset) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTupleToUserset) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_type_definition.go000066400000000000000000000113611456721040100237470ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // TypeDefinition struct for TypeDefinition type TypeDefinition struct { Type string `json:"type"yaml:"type"` Relations *map[string]Userset `json:"relations,omitempty"yaml:"relations,omitempty"` Metadata *Metadata `json:"metadata,omitempty"yaml:"metadata,omitempty"` } // NewTypeDefinition instantiates a new TypeDefinition object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewTypeDefinition(type_ string) *TypeDefinition { this := TypeDefinition{} this.Type = type_ return &this } // NewTypeDefinitionWithDefaults instantiates a new TypeDefinition object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewTypeDefinitionWithDefaults() *TypeDefinition { this := TypeDefinition{} return &this } // GetType returns the Type field value func (o *TypeDefinition) GetType() string { if o == nil { var ret string return ret } return o.Type } // GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. func (o *TypeDefinition) GetTypeOk() (*string, bool) { if o == nil { return nil, false } return &o.Type, true } // SetType sets field value func (o *TypeDefinition) SetType(v string) { o.Type = v } // GetRelations returns the Relations field value if set, zero value otherwise. func (o *TypeDefinition) GetRelations() map[string]Userset { if o == nil || o.Relations == nil { var ret map[string]Userset return ret } return *o.Relations } // GetRelationsOk returns a tuple with the Relations field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TypeDefinition) GetRelationsOk() (*map[string]Userset, bool) { if o == nil || o.Relations == nil { return nil, false } return o.Relations, true } // HasRelations returns a boolean if a field has been set. func (o *TypeDefinition) HasRelations() bool { if o != nil && o.Relations != nil { return true } return false } // SetRelations gets a reference to the given map[string]Userset and assigns it to the Relations field. func (o *TypeDefinition) SetRelations(v map[string]Userset) { o.Relations = &v } // GetMetadata returns the Metadata field value if set, zero value otherwise. func (o *TypeDefinition) GetMetadata() Metadata { if o == nil || o.Metadata == nil { var ret Metadata return ret } return *o.Metadata } // GetMetadataOk returns a tuple with the Metadata field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TypeDefinition) GetMetadataOk() (*Metadata, bool) { if o == nil || o.Metadata == nil { return nil, false } return o.Metadata, true } // HasMetadata returns a boolean if a field has been set. func (o *TypeDefinition) HasMetadata() bool { if o != nil && o.Metadata != nil { return true } return false } // SetMetadata gets a reference to the given Metadata and assigns it to the Metadata field. func (o *TypeDefinition) SetMetadata(v Metadata) { o.Metadata = &v } func (o TypeDefinition) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["type"] = o.Type if o.Relations != nil { toSerialize["relations"] = o.Relations } if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableTypeDefinition struct { value *TypeDefinition isSet bool } func (v NullableTypeDefinition) Get() *TypeDefinition { return v.value } func (v *NullableTypeDefinition) Set(val *TypeDefinition) { v.value = val v.isSet = true } func (v NullableTypeDefinition) IsSet() bool { return v.isSet } func (v *NullableTypeDefinition) Unset() { v.value = nil v.isSet = false } func NewNullableTypeDefinition(val *TypeDefinition) *NullableTypeDefinition { return &NullableTypeDefinition{value: val, isSet: true} } func (v NullableTypeDefinition) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTypeDefinition) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_type_name.go000066400000000000000000000057521456721040100225460ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "encoding/json" "fmt" ) // TypeName the model 'TypeName' type TypeName string // List of TypeName const ( UNSPECIFIED TypeName = "TYPE_NAME_UNSPECIFIED" ANY TypeName = "TYPE_NAME_ANY" BOOL TypeName = "TYPE_NAME_BOOL" STRING TypeName = "TYPE_NAME_STRING" INT TypeName = "TYPE_NAME_INT" UINT TypeName = "TYPE_NAME_UINT" DOUBLE TypeName = "TYPE_NAME_DOUBLE" DURATION TypeName = "TYPE_NAME_DURATION" TIMESTAMP TypeName = "TYPE_NAME_TIMESTAMP" MAP TypeName = "TYPE_NAME_MAP" LIST TypeName = "TYPE_NAME_LIST" IPADDRESS TypeName = "TYPE_NAME_IPADDRESS" ) var allowedTypeNameEnumValues = []TypeName{ "TYPE_NAME_UNSPECIFIED", "TYPE_NAME_ANY", "TYPE_NAME_BOOL", "TYPE_NAME_STRING", "TYPE_NAME_INT", "TYPE_NAME_UINT", "TYPE_NAME_DOUBLE", "TYPE_NAME_DURATION", "TYPE_NAME_TIMESTAMP", "TYPE_NAME_MAP", "TYPE_NAME_LIST", "TYPE_NAME_IPADDRESS", } func (v *TypeName) UnmarshalJSON(src []byte) error { var value string err := json.Unmarshal(src, &value) if err != nil { return err } enumTypeValue := TypeName(value) for _, existing := range allowedTypeNameEnumValues { if existing == enumTypeValue { *v = enumTypeValue return nil } } return fmt.Errorf("%+v is not a valid TypeName", value) } // NewTypeNameFromValue returns a pointer to a valid TypeName // for the value passed as argument, or an error if the value passed is not allowed by the enum func NewTypeNameFromValue(v string) (*TypeName, error) { ev := TypeName(v) if ev.IsValid() { return &ev, nil } else { return nil, fmt.Errorf("invalid value '%v' for TypeName: valid values are %v", v, allowedTypeNameEnumValues) } } // IsValid return true if the value is valid for the enum, false otherwise func (v TypeName) IsValid() bool { for _, existing := range allowedTypeNameEnumValues { if existing == v { return true } } return false } // Ptr returns reference to TypeName value func (v TypeName) Ptr() *TypeName { return &v } type NullableTypeName struct { value *TypeName isSet bool } func (v NullableTypeName) Get() *TypeName { return v.value } func (v *NullableTypeName) Set(val *TypeName) { v.value = val v.isSet = true } func (v NullableTypeName) IsSet() bool { return v.isSet } func (v *NullableTypeName) Unset() { v.value = nil v.isSet = false } func NewNullableTypeName(val *TypeName) *NullableTypeName { return &NullableTypeName{value: val, isSet: true} } func (v NullableTypeName) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTypeName) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_users.go000066400000000000000000000047251456721040100217250ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Users struct for Users type Users struct { Users []string `json:"users"yaml:"users"` } // NewUsers instantiates a new Users object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewUsers(users []string) *Users { this := Users{} this.Users = users return &this } // NewUsersWithDefaults instantiates a new Users object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewUsersWithDefaults() *Users { this := Users{} return &this } // GetUsers returns the Users field value func (o *Users) GetUsers() []string { if o == nil { var ret []string return ret } return o.Users } // GetUsersOk returns a tuple with the Users field value // and a boolean to check if the value has been set. func (o *Users) GetUsersOk() (*[]string, bool) { if o == nil { return nil, false } return &o.Users, true } // SetUsers sets field value func (o *Users) SetUsers(v []string) { o.Users = v } func (o Users) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["users"] = o.Users var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableUsers struct { value *Users isSet bool } func (v NullableUsers) Get() *Users { return v.value } func (v *NullableUsers) Set(val *Users) { v.value = val v.isSet = true } func (v NullableUsers) IsSet() bool { return v.isSet } func (v *NullableUsers) Unset() { v.value = nil v.isSet = false } func NewNullableUsers(val *Users) *NullableUsers { return &NullableUsers{value: val, isSet: true} } func (v NullableUsers) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableUsers) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_userset.go000066400000000000000000000203151456721040100222470ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Userset struct for Userset type Userset struct { // A DirectUserset is a sentinel message for referencing the direct members specified by an object/relation mapping. This *map[string]interface{} `json:"this,omitempty"yaml:"this,omitempty"` ComputedUserset *ObjectRelation `json:"computedUserset,omitempty"yaml:"computedUserset,omitempty"` TupleToUserset *TupleToUserset `json:"tupleToUserset,omitempty"yaml:"tupleToUserset,omitempty"` Union *Usersets `json:"union,omitempty"yaml:"union,omitempty"` Intersection *Usersets `json:"intersection,omitempty"yaml:"intersection,omitempty"` Difference *Difference `json:"difference,omitempty"yaml:"difference,omitempty"` } // NewUserset instantiates a new Userset object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewUserset() *Userset { this := Userset{} return &this } // NewUsersetWithDefaults instantiates a new Userset object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewUsersetWithDefaults() *Userset { this := Userset{} return &this } // GetThis returns the This field value if set, zero value otherwise. func (o *Userset) GetThis() map[string]interface{} { if o == nil || o.This == nil { var ret map[string]interface{} return ret } return *o.This } // GetThisOk returns a tuple with the This field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Userset) GetThisOk() (*map[string]interface{}, bool) { if o == nil || o.This == nil { return nil, false } return o.This, true } // HasThis returns a boolean if a field has been set. func (o *Userset) HasThis() bool { if o != nil && o.This != nil { return true } return false } // SetThis gets a reference to the given map[string]interface{} and assigns it to the This field. func (o *Userset) SetThis(v map[string]interface{}) { o.This = &v } // GetComputedUserset returns the ComputedUserset field value if set, zero value otherwise. func (o *Userset) GetComputedUserset() ObjectRelation { if o == nil || o.ComputedUserset == nil { var ret ObjectRelation return ret } return *o.ComputedUserset } // GetComputedUsersetOk returns a tuple with the ComputedUserset field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Userset) GetComputedUsersetOk() (*ObjectRelation, bool) { if o == nil || o.ComputedUserset == nil { return nil, false } return o.ComputedUserset, true } // HasComputedUserset returns a boolean if a field has been set. func (o *Userset) HasComputedUserset() bool { if o != nil && o.ComputedUserset != nil { return true } return false } // SetComputedUserset gets a reference to the given ObjectRelation and assigns it to the ComputedUserset field. func (o *Userset) SetComputedUserset(v ObjectRelation) { o.ComputedUserset = &v } // GetTupleToUserset returns the TupleToUserset field value if set, zero value otherwise. func (o *Userset) GetTupleToUserset() TupleToUserset { if o == nil || o.TupleToUserset == nil { var ret TupleToUserset return ret } return *o.TupleToUserset } // GetTupleToUsersetOk returns a tuple with the TupleToUserset field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Userset) GetTupleToUsersetOk() (*TupleToUserset, bool) { if o == nil || o.TupleToUserset == nil { return nil, false } return o.TupleToUserset, true } // HasTupleToUserset returns a boolean if a field has been set. func (o *Userset) HasTupleToUserset() bool { if o != nil && o.TupleToUserset != nil { return true } return false } // SetTupleToUserset gets a reference to the given TupleToUserset and assigns it to the TupleToUserset field. func (o *Userset) SetTupleToUserset(v TupleToUserset) { o.TupleToUserset = &v } // GetUnion returns the Union field value if set, zero value otherwise. func (o *Userset) GetUnion() Usersets { if o == nil || o.Union == nil { var ret Usersets return ret } return *o.Union } // GetUnionOk returns a tuple with the Union field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Userset) GetUnionOk() (*Usersets, bool) { if o == nil || o.Union == nil { return nil, false } return o.Union, true } // HasUnion returns a boolean if a field has been set. func (o *Userset) HasUnion() bool { if o != nil && o.Union != nil { return true } return false } // SetUnion gets a reference to the given Usersets and assigns it to the Union field. func (o *Userset) SetUnion(v Usersets) { o.Union = &v } // GetIntersection returns the Intersection field value if set, zero value otherwise. func (o *Userset) GetIntersection() Usersets { if o == nil || o.Intersection == nil { var ret Usersets return ret } return *o.Intersection } // GetIntersectionOk returns a tuple with the Intersection field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Userset) GetIntersectionOk() (*Usersets, bool) { if o == nil || o.Intersection == nil { return nil, false } return o.Intersection, true } // HasIntersection returns a boolean if a field has been set. func (o *Userset) HasIntersection() bool { if o != nil && o.Intersection != nil { return true } return false } // SetIntersection gets a reference to the given Usersets and assigns it to the Intersection field. func (o *Userset) SetIntersection(v Usersets) { o.Intersection = &v } // GetDifference returns the Difference field value if set, zero value otherwise. func (o *Userset) GetDifference() Difference { if o == nil || o.Difference == nil { var ret Difference return ret } return *o.Difference } // GetDifferenceOk returns a tuple with the Difference field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Userset) GetDifferenceOk() (*Difference, bool) { if o == nil || o.Difference == nil { return nil, false } return o.Difference, true } // HasDifference returns a boolean if a field has been set. func (o *Userset) HasDifference() bool { if o != nil && o.Difference != nil { return true } return false } // SetDifference gets a reference to the given Difference and assigns it to the Difference field. func (o *Userset) SetDifference(v Difference) { o.Difference = &v } func (o Userset) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.This != nil { toSerialize["this"] = o.This } if o.ComputedUserset != nil { toSerialize["computedUserset"] = o.ComputedUserset } if o.TupleToUserset != nil { toSerialize["tupleToUserset"] = o.TupleToUserset } if o.Union != nil { toSerialize["union"] = o.Union } if o.Intersection != nil { toSerialize["intersection"] = o.Intersection } if o.Difference != nil { toSerialize["difference"] = o.Difference } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableUserset struct { value *Userset isSet bool } func (v NullableUserset) Get() *Userset { return v.value } func (v *NullableUserset) Set(val *Userset) { v.value = val v.isSet = true } func (v NullableUserset) IsSet() bool { return v.isSet } func (v *NullableUserset) Unset() { v.value = nil v.isSet = false } func NewNullableUserset(val *Userset) *NullableUserset { return &NullableUserset{value: val, isSet: true} } func (v NullableUserset) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableUserset) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_userset_tree.go000066400000000000000000000056741456721040100233010ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // UsersetTree A UsersetTree contains the result of an Expansion. type UsersetTree struct { Root *Node `json:"root,omitempty"yaml:"root,omitempty"` } // NewUsersetTree instantiates a new UsersetTree object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewUsersetTree() *UsersetTree { this := UsersetTree{} return &this } // NewUsersetTreeWithDefaults instantiates a new UsersetTree object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewUsersetTreeWithDefaults() *UsersetTree { this := UsersetTree{} return &this } // GetRoot returns the Root field value if set, zero value otherwise. func (o *UsersetTree) GetRoot() Node { if o == nil || o.Root == nil { var ret Node return ret } return *o.Root } // GetRootOk returns a tuple with the Root field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *UsersetTree) GetRootOk() (*Node, bool) { if o == nil || o.Root == nil { return nil, false } return o.Root, true } // HasRoot returns a boolean if a field has been set. func (o *UsersetTree) HasRoot() bool { if o != nil && o.Root != nil { return true } return false } // SetRoot gets a reference to the given Node and assigns it to the Root field. func (o *UsersetTree) SetRoot(v Node) { o.Root = &v } func (o UsersetTree) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Root != nil { toSerialize["root"] = o.Root } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableUsersetTree struct { value *UsersetTree isSet bool } func (v NullableUsersetTree) Get() *UsersetTree { return v.value } func (v *NullableUsersetTree) Set(val *UsersetTree) { v.value = val v.isSet = true } func (v NullableUsersetTree) IsSet() bool { return v.isSet } func (v *NullableUsersetTree) Unset() { v.value = nil v.isSet = false } func NewNullableUsersetTree(val *UsersetTree) *NullableUsersetTree { return &NullableUsersetTree{value: val, isSet: true} } func (v NullableUsersetTree) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableUsersetTree) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_userset_tree_difference.go000066400000000000000000000070471456721040100254470ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // UsersetTreeDifference struct for UsersetTreeDifference type UsersetTreeDifference struct { Base Node `json:"base"yaml:"base"` Subtract Node `json:"subtract"yaml:"subtract"` } // NewUsersetTreeDifference instantiates a new UsersetTreeDifference object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewUsersetTreeDifference(base Node, subtract Node) *UsersetTreeDifference { this := UsersetTreeDifference{} this.Base = base this.Subtract = subtract return &this } // NewUsersetTreeDifferenceWithDefaults instantiates a new UsersetTreeDifference object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewUsersetTreeDifferenceWithDefaults() *UsersetTreeDifference { this := UsersetTreeDifference{} return &this } // GetBase returns the Base field value func (o *UsersetTreeDifference) GetBase() Node { if o == nil { var ret Node return ret } return o.Base } // GetBaseOk returns a tuple with the Base field value // and a boolean to check if the value has been set. func (o *UsersetTreeDifference) GetBaseOk() (*Node, bool) { if o == nil { return nil, false } return &o.Base, true } // SetBase sets field value func (o *UsersetTreeDifference) SetBase(v Node) { o.Base = v } // GetSubtract returns the Subtract field value func (o *UsersetTreeDifference) GetSubtract() Node { if o == nil { var ret Node return ret } return o.Subtract } // GetSubtractOk returns a tuple with the Subtract field value // and a boolean to check if the value has been set. func (o *UsersetTreeDifference) GetSubtractOk() (*Node, bool) { if o == nil { return nil, false } return &o.Subtract, true } // SetSubtract sets field value func (o *UsersetTreeDifference) SetSubtract(v Node) { o.Subtract = v } func (o UsersetTreeDifference) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["base"] = o.Base toSerialize["subtract"] = o.Subtract var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableUsersetTreeDifference struct { value *UsersetTreeDifference isSet bool } func (v NullableUsersetTreeDifference) Get() *UsersetTreeDifference { return v.value } func (v *NullableUsersetTreeDifference) Set(val *UsersetTreeDifference) { v.value = val v.isSet = true } func (v NullableUsersetTreeDifference) IsSet() bool { return v.isSet } func (v *NullableUsersetTreeDifference) Unset() { v.value = nil v.isSet = false } func NewNullableUsersetTreeDifference(val *UsersetTreeDifference) *NullableUsersetTreeDifference { return &NullableUsersetTreeDifference{value: val, isSet: true} } func (v NullableUsersetTreeDifference) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableUsersetTreeDifference) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_userset_tree_tuple_to_userset.go000066400000000000000000000074531456721040100267630ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // UsersetTreeTupleToUserset struct for UsersetTreeTupleToUserset type UsersetTreeTupleToUserset struct { Tupleset string `json:"tupleset"yaml:"tupleset"` Computed []Computed `json:"computed"yaml:"computed"` } // NewUsersetTreeTupleToUserset instantiates a new UsersetTreeTupleToUserset object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewUsersetTreeTupleToUserset(tupleset string, computed []Computed) *UsersetTreeTupleToUserset { this := UsersetTreeTupleToUserset{} this.Tupleset = tupleset this.Computed = computed return &this } // NewUsersetTreeTupleToUsersetWithDefaults instantiates a new UsersetTreeTupleToUserset object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewUsersetTreeTupleToUsersetWithDefaults() *UsersetTreeTupleToUserset { this := UsersetTreeTupleToUserset{} return &this } // GetTupleset returns the Tupleset field value func (o *UsersetTreeTupleToUserset) GetTupleset() string { if o == nil { var ret string return ret } return o.Tupleset } // GetTuplesetOk returns a tuple with the Tupleset field value // and a boolean to check if the value has been set. func (o *UsersetTreeTupleToUserset) GetTuplesetOk() (*string, bool) { if o == nil { return nil, false } return &o.Tupleset, true } // SetTupleset sets field value func (o *UsersetTreeTupleToUserset) SetTupleset(v string) { o.Tupleset = v } // GetComputed returns the Computed field value func (o *UsersetTreeTupleToUserset) GetComputed() []Computed { if o == nil { var ret []Computed return ret } return o.Computed } // GetComputedOk returns a tuple with the Computed field value // and a boolean to check if the value has been set. func (o *UsersetTreeTupleToUserset) GetComputedOk() (*[]Computed, bool) { if o == nil { return nil, false } return &o.Computed, true } // SetComputed sets field value func (o *UsersetTreeTupleToUserset) SetComputed(v []Computed) { o.Computed = v } func (o UsersetTreeTupleToUserset) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tupleset"] = o.Tupleset toSerialize["computed"] = o.Computed var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableUsersetTreeTupleToUserset struct { value *UsersetTreeTupleToUserset isSet bool } func (v NullableUsersetTreeTupleToUserset) Get() *UsersetTreeTupleToUserset { return v.value } func (v *NullableUsersetTreeTupleToUserset) Set(val *UsersetTreeTupleToUserset) { v.value = val v.isSet = true } func (v NullableUsersetTreeTupleToUserset) IsSet() bool { return v.isSet } func (v *NullableUsersetTreeTupleToUserset) Unset() { v.value = nil v.isSet = false } func NewNullableUsersetTreeTupleToUserset(val *UsersetTreeTupleToUserset) *NullableUsersetTreeTupleToUserset { return &NullableUsersetTreeTupleToUserset{value: val, isSet: true} } func (v NullableUsersetTreeTupleToUserset) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableUsersetTreeTupleToUserset) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_usersets.go000066400000000000000000000050701456721040100224330ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // Usersets struct for Usersets type Usersets struct { Child []Userset `json:"child"yaml:"child"` } // NewUsersets instantiates a new Usersets object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewUsersets(child []Userset) *Usersets { this := Usersets{} this.Child = child return &this } // NewUsersetsWithDefaults instantiates a new Usersets object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewUsersetsWithDefaults() *Usersets { this := Usersets{} return &this } // GetChild returns the Child field value func (o *Usersets) GetChild() []Userset { if o == nil { var ret []Userset return ret } return o.Child } // GetChildOk returns a tuple with the Child field value // and a boolean to check if the value has been set. func (o *Usersets) GetChildOk() (*[]Userset, bool) { if o == nil { return nil, false } return &o.Child, true } // SetChild sets field value func (o *Usersets) SetChild(v []Userset) { o.Child = v } func (o Usersets) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["child"] = o.Child var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableUsersets struct { value *Usersets isSet bool } func (v NullableUsersets) Get() *Usersets { return v.value } func (v *NullableUsersets) Set(val *Usersets) { v.value = val v.isSet = true } func (v NullableUsersets) IsSet() bool { return v.isSet } func (v *NullableUsersets) Unset() { v.value = nil v.isSet = false } func NewNullableUsersets(val *Usersets) *NullableUsersets { return &NullableUsersets{value: val, isSet: true} } func (v NullableUsersets) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableUsersets) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_validation_error_message_response.go000066400000000000000000000111761456721040100275470ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // ValidationErrorMessageResponse struct for ValidationErrorMessageResponse type ValidationErrorMessageResponse struct { Code *ErrorCode `json:"code,omitempty"yaml:"code,omitempty"` Message *string `json:"message,omitempty"yaml:"message,omitempty"` } // NewValidationErrorMessageResponse instantiates a new ValidationErrorMessageResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewValidationErrorMessageResponse() *ValidationErrorMessageResponse { this := ValidationErrorMessageResponse{} var code ErrorCode = NO_ERROR this.Code = &code return &this } // NewValidationErrorMessageResponseWithDefaults instantiates a new ValidationErrorMessageResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewValidationErrorMessageResponseWithDefaults() *ValidationErrorMessageResponse { this := ValidationErrorMessageResponse{} var code ErrorCode = NO_ERROR this.Code = &code return &this } // GetCode returns the Code field value if set, zero value otherwise. func (o *ValidationErrorMessageResponse) GetCode() ErrorCode { if o == nil || o.Code == nil { var ret ErrorCode return ret } return *o.Code } // GetCodeOk returns a tuple with the Code field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ValidationErrorMessageResponse) GetCodeOk() (*ErrorCode, bool) { if o == nil || o.Code == nil { return nil, false } return o.Code, true } // HasCode returns a boolean if a field has been set. func (o *ValidationErrorMessageResponse) HasCode() bool { if o != nil && o.Code != nil { return true } return false } // SetCode gets a reference to the given ErrorCode and assigns it to the Code field. func (o *ValidationErrorMessageResponse) SetCode(v ErrorCode) { o.Code = &v } // GetMessage returns the Message field value if set, zero value otherwise. func (o *ValidationErrorMessageResponse) GetMessage() string { if o == nil || o.Message == nil { var ret string return ret } return *o.Message } // GetMessageOk returns a tuple with the Message field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ValidationErrorMessageResponse) GetMessageOk() (*string, bool) { if o == nil || o.Message == nil { return nil, false } return o.Message, true } // HasMessage returns a boolean if a field has been set. func (o *ValidationErrorMessageResponse) HasMessage() bool { if o != nil && o.Message != nil { return true } return false } // SetMessage gets a reference to the given string and assigns it to the Message field. func (o *ValidationErrorMessageResponse) SetMessage(v string) { o.Message = &v } func (o ValidationErrorMessageResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Code != nil { toSerialize["code"] = o.Code } if o.Message != nil { toSerialize["message"] = o.Message } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableValidationErrorMessageResponse struct { value *ValidationErrorMessageResponse isSet bool } func (v NullableValidationErrorMessageResponse) Get() *ValidationErrorMessageResponse { return v.value } func (v *NullableValidationErrorMessageResponse) Set(val *ValidationErrorMessageResponse) { v.value = val v.isSet = true } func (v NullableValidationErrorMessageResponse) IsSet() bool { return v.isSet } func (v *NullableValidationErrorMessageResponse) Unset() { v.value = nil v.isSet = false } func NewNullableValidationErrorMessageResponse(val *ValidationErrorMessageResponse) *NullableValidationErrorMessageResponse { return &NullableValidationErrorMessageResponse{value: val, isSet: true} } func (v NullableValidationErrorMessageResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableValidationErrorMessageResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_write_assertions_request.go000066400000000000000000000061251456721040100257340ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // WriteAssertionsRequest struct for WriteAssertionsRequest type WriteAssertionsRequest struct { Assertions []Assertion `json:"assertions"yaml:"assertions"` } // NewWriteAssertionsRequest instantiates a new WriteAssertionsRequest object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewWriteAssertionsRequest(assertions []Assertion) *WriteAssertionsRequest { this := WriteAssertionsRequest{} this.Assertions = assertions return &this } // NewWriteAssertionsRequestWithDefaults instantiates a new WriteAssertionsRequest object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewWriteAssertionsRequestWithDefaults() *WriteAssertionsRequest { this := WriteAssertionsRequest{} return &this } // GetAssertions returns the Assertions field value func (o *WriteAssertionsRequest) GetAssertions() []Assertion { if o == nil { var ret []Assertion return ret } return o.Assertions } // GetAssertionsOk returns a tuple with the Assertions field value // and a boolean to check if the value has been set. func (o *WriteAssertionsRequest) GetAssertionsOk() (*[]Assertion, bool) { if o == nil { return nil, false } return &o.Assertions, true } // SetAssertions sets field value func (o *WriteAssertionsRequest) SetAssertions(v []Assertion) { o.Assertions = v } func (o WriteAssertionsRequest) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["assertions"] = o.Assertions var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableWriteAssertionsRequest struct { value *WriteAssertionsRequest isSet bool } func (v NullableWriteAssertionsRequest) Get() *WriteAssertionsRequest { return v.value } func (v *NullableWriteAssertionsRequest) Set(val *WriteAssertionsRequest) { v.value = val v.isSet = true } func (v NullableWriteAssertionsRequest) IsSet() bool { return v.isSet } func (v *NullableWriteAssertionsRequest) Unset() { v.value = nil v.isSet = false } func NewNullableWriteAssertionsRequest(val *WriteAssertionsRequest) *NullableWriteAssertionsRequest { return &NullableWriteAssertionsRequest{value: val, isSet: true} } func (v NullableWriteAssertionsRequest) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableWriteAssertionsRequest) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_write_authorization_model_request.go000066400000000000000000000126111456721040100276170ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // WriteAuthorizationModelRequest struct for WriteAuthorizationModelRequest type WriteAuthorizationModelRequest struct { TypeDefinitions []TypeDefinition `json:"type_definitions"yaml:"type_definitions"` SchemaVersion string `json:"schema_version"yaml:"schema_version"` Conditions *map[string]Condition `json:"conditions,omitempty"yaml:"conditions,omitempty"` } // NewWriteAuthorizationModelRequest instantiates a new WriteAuthorizationModelRequest object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewWriteAuthorizationModelRequest(typeDefinitions []TypeDefinition, schemaVersion string) *WriteAuthorizationModelRequest { this := WriteAuthorizationModelRequest{} this.TypeDefinitions = typeDefinitions this.SchemaVersion = schemaVersion return &this } // NewWriteAuthorizationModelRequestWithDefaults instantiates a new WriteAuthorizationModelRequest object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewWriteAuthorizationModelRequestWithDefaults() *WriteAuthorizationModelRequest { this := WriteAuthorizationModelRequest{} return &this } // GetTypeDefinitions returns the TypeDefinitions field value func (o *WriteAuthorizationModelRequest) GetTypeDefinitions() []TypeDefinition { if o == nil { var ret []TypeDefinition return ret } return o.TypeDefinitions } // GetTypeDefinitionsOk returns a tuple with the TypeDefinitions field value // and a boolean to check if the value has been set. func (o *WriteAuthorizationModelRequest) GetTypeDefinitionsOk() (*[]TypeDefinition, bool) { if o == nil { return nil, false } return &o.TypeDefinitions, true } // SetTypeDefinitions sets field value func (o *WriteAuthorizationModelRequest) SetTypeDefinitions(v []TypeDefinition) { o.TypeDefinitions = v } // GetSchemaVersion returns the SchemaVersion field value func (o *WriteAuthorizationModelRequest) GetSchemaVersion() string { if o == nil { var ret string return ret } return o.SchemaVersion } // GetSchemaVersionOk returns a tuple with the SchemaVersion field value // and a boolean to check if the value has been set. func (o *WriteAuthorizationModelRequest) GetSchemaVersionOk() (*string, bool) { if o == nil { return nil, false } return &o.SchemaVersion, true } // SetSchemaVersion sets field value func (o *WriteAuthorizationModelRequest) SetSchemaVersion(v string) { o.SchemaVersion = v } // GetConditions returns the Conditions field value if set, zero value otherwise. func (o *WriteAuthorizationModelRequest) GetConditions() map[string]Condition { if o == nil || o.Conditions == nil { var ret map[string]Condition return ret } return *o.Conditions } // GetConditionsOk returns a tuple with the Conditions field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *WriteAuthorizationModelRequest) GetConditionsOk() (*map[string]Condition, bool) { if o == nil || o.Conditions == nil { return nil, false } return o.Conditions, true } // HasConditions returns a boolean if a field has been set. func (o *WriteAuthorizationModelRequest) HasConditions() bool { if o != nil && o.Conditions != nil { return true } return false } // SetConditions gets a reference to the given map[string]Condition and assigns it to the Conditions field. func (o *WriteAuthorizationModelRequest) SetConditions(v map[string]Condition) { o.Conditions = &v } func (o WriteAuthorizationModelRequest) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["type_definitions"] = o.TypeDefinitions toSerialize["schema_version"] = o.SchemaVersion if o.Conditions != nil { toSerialize["conditions"] = o.Conditions } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableWriteAuthorizationModelRequest struct { value *WriteAuthorizationModelRequest isSet bool } func (v NullableWriteAuthorizationModelRequest) Get() *WriteAuthorizationModelRequest { return v.value } func (v *NullableWriteAuthorizationModelRequest) Set(val *WriteAuthorizationModelRequest) { v.value = val v.isSet = true } func (v NullableWriteAuthorizationModelRequest) IsSet() bool { return v.isSet } func (v *NullableWriteAuthorizationModelRequest) Unset() { v.value = nil v.isSet = false } func NewNullableWriteAuthorizationModelRequest(val *WriteAuthorizationModelRequest) *NullableWriteAuthorizationModelRequest { return &NullableWriteAuthorizationModelRequest{value: val, isSet: true} } func (v NullableWriteAuthorizationModelRequest) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableWriteAuthorizationModelRequest) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_write_authorization_model_response.go000066400000000000000000000070221456721040100277650ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // WriteAuthorizationModelResponse struct for WriteAuthorizationModelResponse type WriteAuthorizationModelResponse struct { AuthorizationModelId string `json:"authorization_model_id"yaml:"authorization_model_id"` } // NewWriteAuthorizationModelResponse instantiates a new WriteAuthorizationModelResponse object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewWriteAuthorizationModelResponse(authorizationModelId string) *WriteAuthorizationModelResponse { this := WriteAuthorizationModelResponse{} this.AuthorizationModelId = authorizationModelId return &this } // NewWriteAuthorizationModelResponseWithDefaults instantiates a new WriteAuthorizationModelResponse object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewWriteAuthorizationModelResponseWithDefaults() *WriteAuthorizationModelResponse { this := WriteAuthorizationModelResponse{} return &this } // GetAuthorizationModelId returns the AuthorizationModelId field value func (o *WriteAuthorizationModelResponse) GetAuthorizationModelId() string { if o == nil { var ret string return ret } return o.AuthorizationModelId } // GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field value // and a boolean to check if the value has been set. func (o *WriteAuthorizationModelResponse) GetAuthorizationModelIdOk() (*string, bool) { if o == nil { return nil, false } return &o.AuthorizationModelId, true } // SetAuthorizationModelId sets field value func (o *WriteAuthorizationModelResponse) SetAuthorizationModelId(v string) { o.AuthorizationModelId = v } func (o WriteAuthorizationModelResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["authorization_model_id"] = o.AuthorizationModelId var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableWriteAuthorizationModelResponse struct { value *WriteAuthorizationModelResponse isSet bool } func (v NullableWriteAuthorizationModelResponse) Get() *WriteAuthorizationModelResponse { return v.value } func (v *NullableWriteAuthorizationModelResponse) Set(val *WriteAuthorizationModelResponse) { v.value = val v.isSet = true } func (v NullableWriteAuthorizationModelResponse) IsSet() bool { return v.isSet } func (v *NullableWriteAuthorizationModelResponse) Unset() { v.value = nil v.isSet = false } func NewNullableWriteAuthorizationModelResponse(val *WriteAuthorizationModelResponse) *NullableWriteAuthorizationModelResponse { return &NullableWriteAuthorizationModelResponse{value: val, isSet: true} } func (v NullableWriteAuthorizationModelResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableWriteAuthorizationModelResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_write_request.go000066400000000000000000000125061456721040100234620ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // WriteRequest struct for WriteRequest type WriteRequest struct { Writes *WriteRequestWrites `json:"writes,omitempty"yaml:"writes,omitempty"` Deletes *WriteRequestDeletes `json:"deletes,omitempty"yaml:"deletes,omitempty"` AuthorizationModelId *string `json:"authorization_model_id,omitempty"yaml:"authorization_model_id,omitempty"` } // NewWriteRequest instantiates a new WriteRequest object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewWriteRequest() *WriteRequest { this := WriteRequest{} return &this } // NewWriteRequestWithDefaults instantiates a new WriteRequest object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewWriteRequestWithDefaults() *WriteRequest { this := WriteRequest{} return &this } // GetWrites returns the Writes field value if set, zero value otherwise. func (o *WriteRequest) GetWrites() WriteRequestWrites { if o == nil || o.Writes == nil { var ret WriteRequestWrites return ret } return *o.Writes } // GetWritesOk returns a tuple with the Writes field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *WriteRequest) GetWritesOk() (*WriteRequestWrites, bool) { if o == nil || o.Writes == nil { return nil, false } return o.Writes, true } // HasWrites returns a boolean if a field has been set. func (o *WriteRequest) HasWrites() bool { if o != nil && o.Writes != nil { return true } return false } // SetWrites gets a reference to the given WriteRequestWrites and assigns it to the Writes field. func (o *WriteRequest) SetWrites(v WriteRequestWrites) { o.Writes = &v } // GetDeletes returns the Deletes field value if set, zero value otherwise. func (o *WriteRequest) GetDeletes() WriteRequestDeletes { if o == nil || o.Deletes == nil { var ret WriteRequestDeletes return ret } return *o.Deletes } // GetDeletesOk returns a tuple with the Deletes field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *WriteRequest) GetDeletesOk() (*WriteRequestDeletes, bool) { if o == nil || o.Deletes == nil { return nil, false } return o.Deletes, true } // HasDeletes returns a boolean if a field has been set. func (o *WriteRequest) HasDeletes() bool { if o != nil && o.Deletes != nil { return true } return false } // SetDeletes gets a reference to the given WriteRequestDeletes and assigns it to the Deletes field. func (o *WriteRequest) SetDeletes(v WriteRequestDeletes) { o.Deletes = &v } // GetAuthorizationModelId returns the AuthorizationModelId field value if set, zero value otherwise. func (o *WriteRequest) GetAuthorizationModelId() string { if o == nil || o.AuthorizationModelId == nil { var ret string return ret } return *o.AuthorizationModelId } // GetAuthorizationModelIdOk returns a tuple with the AuthorizationModelId field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *WriteRequest) GetAuthorizationModelIdOk() (*string, bool) { if o == nil || o.AuthorizationModelId == nil { return nil, false } return o.AuthorizationModelId, true } // HasAuthorizationModelId returns a boolean if a field has been set. func (o *WriteRequest) HasAuthorizationModelId() bool { if o != nil && o.AuthorizationModelId != nil { return true } return false } // SetAuthorizationModelId gets a reference to the given string and assigns it to the AuthorizationModelId field. func (o *WriteRequest) SetAuthorizationModelId(v string) { o.AuthorizationModelId = &v } func (o WriteRequest) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Writes != nil { toSerialize["writes"] = o.Writes } if o.Deletes != nil { toSerialize["deletes"] = o.Deletes } if o.AuthorizationModelId != nil { toSerialize["authorization_model_id"] = o.AuthorizationModelId } var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableWriteRequest struct { value *WriteRequest isSet bool } func (v NullableWriteRequest) Get() *WriteRequest { return v.value } func (v *NullableWriteRequest) Set(val *WriteRequest) { v.value = val v.isSet = true } func (v NullableWriteRequest) IsSet() bool { return v.isSet } func (v *NullableWriteRequest) Unset() { v.value = nil v.isSet = false } func NewNullableWriteRequest(val *WriteRequest) *NullableWriteRequest { return &NullableWriteRequest{value: val, isSet: true} } func (v NullableWriteRequest) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableWriteRequest) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_write_request_deletes.go000066400000000000000000000061021456721040100251620ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // WriteRequestDeletes struct for WriteRequestDeletes type WriteRequestDeletes struct { TupleKeys []TupleKeyWithoutCondition `json:"tuple_keys"yaml:"tuple_keys"` } // NewWriteRequestDeletes instantiates a new WriteRequestDeletes object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewWriteRequestDeletes(tupleKeys []TupleKeyWithoutCondition) *WriteRequestDeletes { this := WriteRequestDeletes{} this.TupleKeys = tupleKeys return &this } // NewWriteRequestDeletesWithDefaults instantiates a new WriteRequestDeletes object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewWriteRequestDeletesWithDefaults() *WriteRequestDeletes { this := WriteRequestDeletes{} return &this } // GetTupleKeys returns the TupleKeys field value func (o *WriteRequestDeletes) GetTupleKeys() []TupleKeyWithoutCondition { if o == nil { var ret []TupleKeyWithoutCondition return ret } return o.TupleKeys } // GetTupleKeysOk returns a tuple with the TupleKeys field value // and a boolean to check if the value has been set. func (o *WriteRequestDeletes) GetTupleKeysOk() (*[]TupleKeyWithoutCondition, bool) { if o == nil { return nil, false } return &o.TupleKeys, true } // SetTupleKeys sets field value func (o *WriteRequestDeletes) SetTupleKeys(v []TupleKeyWithoutCondition) { o.TupleKeys = v } func (o WriteRequestDeletes) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tuple_keys"] = o.TupleKeys var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableWriteRequestDeletes struct { value *WriteRequestDeletes isSet bool } func (v NullableWriteRequestDeletes) Get() *WriteRequestDeletes { return v.value } func (v *NullableWriteRequestDeletes) Set(val *WriteRequestDeletes) { v.value = val v.isSet = true } func (v NullableWriteRequestDeletes) IsSet() bool { return v.isSet } func (v *NullableWriteRequestDeletes) Unset() { v.value = nil v.isSet = false } func NewNullableWriteRequestDeletes(val *WriteRequestDeletes) *NullableWriteRequestDeletes { return &NullableWriteRequestDeletes{value: val, isSet: true} } func (v NullableWriteRequestDeletes) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableWriteRequestDeletes) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/model_write_request_writes.go000066400000000000000000000057031456721040100250600ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "bytes" "encoding/json" ) // WriteRequestWrites struct for WriteRequestWrites type WriteRequestWrites struct { TupleKeys []TupleKey `json:"tuple_keys"yaml:"tuple_keys"` } // NewWriteRequestWrites instantiates a new WriteRequestWrites object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewWriteRequestWrites(tupleKeys []TupleKey) *WriteRequestWrites { this := WriteRequestWrites{} this.TupleKeys = tupleKeys return &this } // NewWriteRequestWritesWithDefaults instantiates a new WriteRequestWrites object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewWriteRequestWritesWithDefaults() *WriteRequestWrites { this := WriteRequestWrites{} return &this } // GetTupleKeys returns the TupleKeys field value func (o *WriteRequestWrites) GetTupleKeys() []TupleKey { if o == nil { var ret []TupleKey return ret } return o.TupleKeys } // GetTupleKeysOk returns a tuple with the TupleKeys field value // and a boolean to check if the value has been set. func (o *WriteRequestWrites) GetTupleKeysOk() (*[]TupleKey, bool) { if o == nil { return nil, false } return &o.TupleKeys, true } // SetTupleKeys sets field value func (o *WriteRequestWrites) SetTupleKeys(v []TupleKey) { o.TupleKeys = v } func (o WriteRequestWrites) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} toSerialize["tuple_keys"] = o.TupleKeys var b bytes.Buffer enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) err := enc.Encode(toSerialize) if err != nil { return nil, err } return b.Bytes(), nil } type NullableWriteRequestWrites struct { value *WriteRequestWrites isSet bool } func (v NullableWriteRequestWrites) Get() *WriteRequestWrites { return v.value } func (v *NullableWriteRequestWrites) Set(val *WriteRequestWrites) { v.value = val v.isSet = true } func (v NullableWriteRequestWrites) IsSet() bool { return v.isSet } func (v *NullableWriteRequestWrites) Unset() { v.value = nil v.isSet = false } func NewNullableWriteRequestWrites(val *WriteRequestWrites) *NullableWriteRequestWrites { return &NullableWriteRequestWrites{value: val, isSet: true} } func (v NullableWriteRequestWrites) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableWriteRequestWrites) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } golang-github-openfga-go-sdk-0.3.5/oauth2/000077500000000000000000000000001456721040100202475ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/oauth2/LICENSE000066400000000000000000000027071456721040100212620ustar00rootroot00000000000000Copyright (c) 2009 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. golang-github-openfga-go-sdk-0.3.5/oauth2/ORIGINAL_AUTHORS000066400000000000000000000002551456721040100226050ustar00rootroot00000000000000# This source code refers to The Go Authors for copyright purposes. # The master list of authors is in the main Go distribution, # visible at http://tip.golang.org/AUTHORS. golang-github-openfga-go-sdk-0.3.5/oauth2/ORIGINAL_CONTRIBUTORS000066400000000000000000000002521456721040100234120ustar00rootroot00000000000000# This source code was written by the Go contributors. # The master list of contributors is in the main Go distribution, # visible at http://tip.golang.org/CONTRIBUTORS. golang-github-openfga-go-sdk-0.3.5/oauth2/README.md000066400000000000000000000016131456721040100215270ustar00rootroot00000000000000This oauth2 folder contains a oauth2 package with a partial client OAuth2 implementation. It has been copied over from the original for our use. A lot of the original code and dependencies have been deleted, and the rest reshuffled. Original Project: Go OAuth2 - [pkg.go.dev/golang.org/x/oauth2](https://pkg.go.dev/golang.org/x/oauth2) * Commit hash at the time of cloning [d3ed0bb246c8d3c75b63937d9a5eecff9c74d7fe](https://github.com/golang/oauth2/blob/d3ed0bb246c8d3c75b63937d9a5eecff9c74d7fe/) * Original Project's Repo on GitHub: [golang/oauth2](https://github.com/golang/oauth2/) * Original Project's Repo on Google Open Source: https://cs.opensource.google/go/x/oauth2 * License: [BSD 3-Clause](https://github.com/golang/oauth2/blob/d3ed0bb246c8d3c75b63937d9a5eecff9c74d7fe/LICENSE) - [Local copy](./LICENSE) Note: The original authors are not aware of this fork, and do not endorse it in any way. golang-github-openfga-go-sdk-0.3.5/oauth2/clientcredentials/000077500000000000000000000000001456721040100237435ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/oauth2/clientcredentials/clientcredentials.go000066400000000000000000000072401456721040100277710ustar00rootroot00000000000000// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package clientcredentials implements the OAuth2.0 "client credentials" token flow, // also known as the "two-legged OAuth 2.0". // // This should be used when the client is acting on its own behalf or when the client // is the resource owner. It may also be used when requesting access to protected // resources based on an authorization previously arranged with the authorization // server. // // See https://tools.ietf.org/html/rfc6749#section-4.4 package clientcredentials import ( "context" "fmt" "github.com/openfga/go-sdk/oauth2" "github.com/openfga/go-sdk/oauth2/internal" "net/http" "net/url" "strings" ) // Config describes a 2-legged OAuth2 flow, with both the // client application information and the server's endpoint URLs. type Config struct { // ClientID is the application's ID. ClientID string // ClientSecret is the application's secret. ClientSecret string // TokenURL is the resource server's token endpoint // URL. This is a constant specific to each server. TokenURL string // Scope specifies optional requested permissions. Scopes []string // EndpointParams specifies additional parameters for requests to the token endpoint. EndpointParams url.Values // AuthStyle optionally specifies how the endpoint wants the // client ID & client secret sent. The zero value means to // auto-detect. AuthStyle oauth2.AuthStyle } // Token uses client credentials to retrieve a token. // // The provided context optionally controls which HTTP client is used. See the oauth2.HTTPClient variable. func (c *Config) Token(ctx context.Context) (*oauth2.Token, error) { return c.TokenSource(ctx).Token() } // Client returns an HTTP client using the provided token. // The token will auto-refresh as necessary. // // The provided context optionally controls which HTTP client // is returned. See the oauth2.HTTPClient variable. // // The returned Client and its Transport should not be modified. func (c *Config) Client(ctx context.Context) *http.Client { return oauth2.NewClient(ctx, c.TokenSource(ctx)) } // TokenSource returns a TokenSource that returns t until t expires, // automatically refreshing it as necessary using the provided context and the // client ID and client secret. // // Most users will use Config.Client instead. func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource { source := &tokenSource{ ctx: ctx, conf: c, } return oauth2.ReuseTokenSource(nil, source) } type tokenSource struct { ctx context.Context conf *Config } // Token refreshes the token by using a new client credentials request. // tokens received this way do not include a refresh token func (c *tokenSource) Token() (*oauth2.Token, error) { v := url.Values{ "grant_type": {"client_credentials"}, } if len(c.conf.Scopes) > 0 { v.Set("scope", strings.Join(c.conf.Scopes, " ")) } for k, p := range c.conf.EndpointParams { // Allow grant_type to be overridden to allow interoperability with // non-compliant implementations. if _, ok := v[k]; ok && k != "grant_type" { return nil, fmt.Errorf("oauth2: cannot overwrite parameter %q", k) } v[k] = p } tk, err := internal.RetrieveToken(c.ctx, c.conf.ClientID, c.conf.ClientSecret, c.conf.TokenURL, v, internal.AuthStyle(c.conf.AuthStyle)) if err != nil { if rErr, ok := err.(*internal.RetrieveError); ok { return nil, (*oauth2.RetrieveError)(rErr) } return nil, err } t := &oauth2.Token{ AccessToken: tk.AccessToken, TokenType: tk.TokenType, RefreshToken: tk.RefreshToken, Expiry: tk.Expiry, } return t.WithExtra(tk.Raw), nil } golang-github-openfga-go-sdk-0.3.5/oauth2/clientcredentials/clientcredentials_test.go000066400000000000000000000111041456721040100310220ustar00rootroot00000000000000// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package clientcredentials import ( "context" "github.com/openfga/go-sdk/oauth2/internal" "io" "io/ioutil" "net/http" "net/http/httptest" "net/url" "testing" ) func newConf(serverURL string) *Config { return &Config{ ClientID: "CLIENT_ID", ClientSecret: "CLIENT_SECRET", Scopes: []string{"scope1", "scope2"}, TokenURL: serverURL + "/token", EndpointParams: url.Values{"audience": {"audience1"}}, } } type mockTransport struct { rt func(req *http.Request) (resp *http.Response, err error) } func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { return t.rt(req) } func TestTokenSourceGrantTypeOverride(t *testing.T) { wantGrantType := "password" var gotGrantType string ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("ioutil.ReadAll(r.Body) == %v, %v, want _, ", body, err) } if err := r.Body.Close(); err != nil { t.Errorf("r.Body.Close() == %v, want ", err) } values, err := url.ParseQuery(string(body)) if err != nil { t.Errorf("url.ParseQuery(%q) == %v, %v, want _, ", body, values, err) } gotGrantType = values.Get("grant_type") w.Header().Set("Content-Type", "application/x-www-form-urlencoded") w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&token_type=bearer")) })) config := &Config{ ClientID: "CLIENT_ID", ClientSecret: "CLIENT_SECRET", Scopes: []string{"scope"}, TokenURL: ts.URL + "/token", EndpointParams: url.Values{ "grant_type": {wantGrantType}, }, } token, err := config.TokenSource(context.Background()).Token() if err != nil { t.Errorf("config.TokenSource(_).Token() == %v, %v, want !, ", token, err) } if gotGrantType != wantGrantType { t.Errorf("grant_type == %q, want %q", gotGrantType, wantGrantType) } } func TestTokenRequest(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.String() != "/token" { t.Errorf("authenticate client request URL = %q; want %q", r.URL, "/token") } headerAuth := r.Header.Get("Authorization") if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { t.Errorf("Unexpected authorization header, %v is found.", headerAuth) } if got, want := r.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; got != want { t.Errorf("Content-Type header = %q; want %q", got, want) } body, err := ioutil.ReadAll(r.Body) if err != nil { r.Body.Close() } if err != nil { t.Errorf("failed reading request body: %s.", err) } if string(body) != "audience=audience1&grant_type=client_credentials&scope=scope1+scope2" { t.Errorf("payload = %q; want %q", string(body), "grant_type=client_credentials&scope=scope1+scope2") } w.Header().Set("Content-Type", "application/x-www-form-urlencoded") w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&token_type=bearer")) })) defer ts.Close() conf := newConf(ts.URL) tok, err := conf.Token(context.Background()) if err != nil { t.Error(err) } if !tok.Valid() { t.Fatalf("token invalid. got: %#v", tok) } if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { t.Errorf("Access token = %q; want %q", tok.AccessToken, "90d64460d14870c08c81352a05dedd3465940a7c") } if tok.TokenType != "bearer" { t.Errorf("token type = %q; want %q", tok.TokenType, "bearer") } } func TestTokenRefreshRequest(t *testing.T) { internal.ResetAuthCache() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.String() == "/somethingelse" { return } if r.URL.String() != "/token" { t.Errorf("Unexpected token refresh request URL: %q", r.URL) } headerContentType := r.Header.Get("Content-Type") if got, want := headerContentType, "application/x-www-form-urlencoded"; got != want { t.Errorf("Content-Type = %q; want %q", got, want) } body, _ := ioutil.ReadAll(r.Body) const want = "audience=audience1&grant_type=client_credentials&scope=scope1+scope2" if string(body) != want { t.Errorf("Unexpected refresh token payload.\n got: %s\nwant: %s\n", body, want) } w.Header().Set("Content-Type", "application/json") io.WriteString(w, `{"access_token": "foo", "refresh_token": "bar"}`) })) defer ts.Close() conf := newConf(ts.URL) c := conf.Client(context.Background()) c.Get(ts.URL + "/somethingelse") } golang-github-openfga-go-sdk-0.3.5/oauth2/internal/000077500000000000000000000000001456721040100220635ustar00rootroot00000000000000golang-github-openfga-go-sdk-0.3.5/oauth2/internal/doc.go000066400000000000000000000003631456721040100231610ustar00rootroot00000000000000// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package internal contains support packages for oauth2 package. package internal golang-github-openfga-go-sdk-0.3.5/oauth2/internal/token.go000066400000000000000000000217661456721040100235460ustar00rootroot00000000000000// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package internal import ( "context" "encoding/json" "errors" "fmt" "io" "io/ioutil" "math" "mime" "net/http" "net/url" "strconv" "strings" "sync" "time" internalutils "github.com/openfga/go-sdk/internal/utils" ) const cMaxRetry = 3 const cMinWaitInMs = 50 // Token represents the credentials used to authorize // the requests to access protected resources on the OAuth 2.0 // provider's backend. // // This type is a mirror of oauth2.Token and exists to break // an otherwise-circular dependency. Other internal packages // should convert this Token into an oauth2.Token before use. type Token struct { // AccessToken is the token that authorizes and authenticates // the requests. AccessToken string // TokenType is the type of token. // The Type method returns either this or "Bearer", the default. TokenType string // RefreshToken is a token that's used by the application // (as opposed to the user) to refresh the access token // if it expires. RefreshToken string // Expiry is the optional expiration time of the access token. // // If zero, TokenSource implementations will reuse the same // token forever and RefreshToken or equivalent // mechanisms for that TokenSource will not be used. Expiry time.Time // Raw optionally contains extra metadata from the server // when updating a token. Raw interface{} } // tokenJSON is the struct representing the HTTP response from OAuth2 // providers returning a token in JSON form. type tokenJSON struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` RefreshToken string `json:"refresh_token"` ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number } func (e *tokenJSON) expiry() (t time.Time) { if v := e.ExpiresIn; v != 0 { return time.Now().Add(time.Duration(v) * time.Second) } return } type expirationTime int32 func (e *expirationTime) UnmarshalJSON(b []byte) error { if len(b) == 0 || string(b) == "null" { return nil } var n json.Number err := json.Unmarshal(b, &n) if err != nil { return err } i, err := n.Int64() if err != nil { return err } if i > math.MaxInt32 { i = math.MaxInt32 } *e = expirationTime(i) return nil } // RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op. // // Deprecated: this function no longer does anything. Caller code that // wants to avoid potential extra HTTP requests made during // auto-probing of the provider's auth style should set // Endpoint.AuthStyle. func RegisterBrokenAuthHeaderProvider(tokenURL string) {} // AuthStyle is a copy of the golang.org/x/oauth2 package's AuthStyle type. type AuthStyle int const ( AuthStyleUnknown AuthStyle = 0 AuthStyleInParams AuthStyle = 1 AuthStyleInHeader AuthStyle = 2 ) // authStyleCache is the set of tokenURLs we've successfully used via // RetrieveToken and which style auth we ended up using. // It's called a cache, but it doesn't (yet?) shrink. It's expected that // the set of OAuth2 servers a program contacts over time is fixed and // small. var authStyleCache struct { sync.Mutex m map[string]AuthStyle // keyed by tokenURL } // ResetAuthCache resets the global authentication style cache used // for AuthStyleUnknown token requests. func ResetAuthCache() { authStyleCache.Lock() defer authStyleCache.Unlock() authStyleCache.m = nil } // lookupAuthStyle reports which auth style we last used with tokenURL // when calling RetrieveToken and whether we have ever done so. func lookupAuthStyle(tokenURL string) (style AuthStyle, ok bool) { authStyleCache.Lock() defer authStyleCache.Unlock() style, ok = authStyleCache.m[tokenURL] return } // setAuthStyle adds an entry to authStyleCache, documented above. func setAuthStyle(tokenURL string, v AuthStyle) { authStyleCache.Lock() defer authStyleCache.Unlock() if authStyleCache.m == nil { authStyleCache.m = make(map[string]AuthStyle) } authStyleCache.m[tokenURL] = v } // newTokenRequest returns a new *http.Request to retrieve a new token // from tokenURL using the provided clientID, clientSecret, and POST // body parameters. // // inParams is whether the clientID & clientSecret should be encoded // as the POST body. An 'inParams' value of true means to send it in // the POST body (along with any values in v); false means to send it // in the Authorization header. func newTokenRequest(tokenURL, clientID, clientSecret string, v url.Values, authStyle AuthStyle) (*http.Request, error) { if authStyle == AuthStyleInParams { v = cloneURLValues(v) if clientID != "" { v.Set("client_id", clientID) } if clientSecret != "" { v.Set("client_secret", clientSecret) } } req, err := http.NewRequest("POST", tokenURL, strings.NewReader(v.Encode())) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") if authStyle == AuthStyleInHeader { req.SetBasicAuth(url.QueryEscape(clientID), url.QueryEscape(clientSecret)) } return req, nil } func cloneURLValues(v url.Values) url.Values { v2 := make(url.Values, len(v)) for k, vv := range v { v2[k] = append([]string(nil), vv...) } return v2 } func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values, authStyle AuthStyle) (*Token, error) { needsAuthStyleProbe := authStyle == 0 if needsAuthStyleProbe { if style, ok := lookupAuthStyle(tokenURL); ok { authStyle = style needsAuthStyleProbe = false } else { authStyle = AuthStyleInHeader // the first way we'll try } } req, err := newTokenRequest(tokenURL, clientID, clientSecret, v, authStyle) if err != nil { return nil, err } token, err := doTokenRoundTrip(ctx, req) if err != nil && needsAuthStyleProbe { // If we get an error, assume the server wants the // clientID & clientSecret in a different form. // See https://code.google.com/p/goauth2/issues/detail?id=31 for background. // In summary: // - Reddit only accepts client secret in the Authorization header // - Dropbox accepts either it in URL param or Auth header, but not both. // - Google only accepts URL param (not spec compliant?), not Auth header // - Stripe only accepts client secret in Auth header with Bearer method, not Basic // // We used to maintain a big table in this code of all the sites and which way // they went, but maintaining it didn't scale & got annoying. // So just try both ways. authStyle = AuthStyleInParams // the second way we'll try req, _ = newTokenRequest(tokenURL, clientID, clientSecret, v, authStyle) token, err = doTokenRoundTrip(ctx, req) } if needsAuthStyleProbe && err == nil { setAuthStyle(tokenURL, authStyle) } // Don't overwrite `RefreshToken` with an empty value // if this was a token refreshing request. if token != nil && token.RefreshToken == "" { token.RefreshToken = v.Get("refresh_token") } return token, err } func singleTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) { r, err := ContextClient(ctx).Do(req.WithContext(ctx)) if err != nil { return nil, err } body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20)) r.Body.Close() if err != nil { return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) } if code := r.StatusCode; code < 200 || code > 299 { return nil, &RetrieveError{ Response: r, Body: body, } } var token *Token content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) switch content { case "application/x-www-form-urlencoded", "text/plain": vals, err := url.ParseQuery(string(body)) if err != nil { return nil, err } token = &Token{ AccessToken: vals.Get("access_token"), TokenType: vals.Get("token_type"), RefreshToken: vals.Get("refresh_token"), Raw: vals, } e := vals.Get("expires_in") expires, _ := strconv.Atoi(e) if expires != 0 { token.Expiry = time.Now().Add(time.Duration(expires) * time.Second) } default: var tj tokenJSON if err = json.Unmarshal(body, &tj); err != nil { return nil, err } token = &Token{ AccessToken: tj.AccessToken, TokenType: tj.TokenType, RefreshToken: tj.RefreshToken, Expiry: tj.expiry(), Raw: make(map[string]interface{}), } json.Unmarshal(body, &token.Raw) // no error checks for optional fields } if token.AccessToken == "" { return nil, errors.New("oauth2: server response missing access_token") } return token, nil } func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) { var token *Token var err error for i := 0; i < cMaxRetry; i++ { token, err = singleTokenRoundTrip(ctx, req) if err == nil { return token, err } time.Sleep(time.Duration(internalutils.RandomTime(i, cMinWaitInMs)) * time.Millisecond) } return nil, err } type RetrieveError struct { Response *http.Response Body []byte } func (r *RetrieveError) Error() string { return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body) } golang-github-openfga-go-sdk-0.3.5/oauth2/internal/token_test.go000066400000000000000000000074731456721040100246040ustar00rootroot00000000000000// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package internal import ( "context" "fmt" "io" "math" "net/http" "net/http/httptest" "net/url" "testing" "github.com/jarcoal/httpmock" ) func TestRetrieveToken_InParams(t *testing.T) { ResetAuthCache() const clientID = "client-id" ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if got, want := r.FormValue("client_id"), clientID; got != want { t.Errorf("client_id = %q; want %q", got, want) } if got, want := r.FormValue("client_secret"), ""; got != want { t.Errorf("client_secret = %q; want empty", got) } w.Header().Set("Content-Type", "application/json") io.WriteString(w, `{"access_token": "ACCESS_TOKEN", "token_type": "bearer"}`) })) defer ts.Close() _, err := RetrieveToken(context.Background(), clientID, "", ts.URL, url.Values{}, AuthStyleInParams) if err != nil { t.Errorf("RetrieveToken = %v; want no error", err) } } func TestRetrieveTokenWithContexts(t *testing.T) { ResetAuthCache() const clientID = "client-id" ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") io.WriteString(w, `{"access_token": "ACCESS_TOKEN", "token_type": "bearer"}`) })) defer ts.Close() _, err := RetrieveToken(context.Background(), clientID, "", ts.URL, url.Values{}, AuthStyleUnknown) if err != nil { t.Errorf("RetrieveToken (with background context) = %v; want no error", err) } retrieved := make(chan struct{}) cancellingts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-retrieved })) defer cancellingts.Close() ctx, cancel := context.WithCancel(context.Background()) cancel() _, err = RetrieveToken(ctx, clientID, "", cancellingts.URL, url.Values{}, AuthStyleUnknown) close(retrieved) if err == nil { t.Errorf("RetrieveToken (with cancelled context) = nil; want error") } } // Test the retry logic where request is successful at the end func TestRetrieveTokenWithContextsRetry(t *testing.T) { ResetAuthCache() const clientID = "client-id" type JSONResponse struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` } expectedResponse := JSONResponse{ AccessToken: "ACCESS_TOKEN", TokenType: "bearer", } httpmock.Activate() defer httpmock.DeactivateAndReset() firstMock := httpmock.NewStringResponder(429, "") secondMock, _ := httpmock.NewJsonResponder(200, expectedResponse) const testURL = "http://testserver.com" httpmock.RegisterResponder("POST", testURL, firstMock.Then(firstMock).Then(firstMock).Then(secondMock), ) _, err := RetrieveToken(context.Background(), clientID, "", testURL, url.Values{}, AuthStyleUnknown) if err != nil { t.Errorf("RetrieveToken (with background context) = %v; want no error", err) } } func TestRetrieveTokenWithContextsFailure(t *testing.T) { ResetAuthCache() const clientID = "client-id" type JSONResponse struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` } httpmock.Activate() defer httpmock.DeactivateAndReset() firstMock := httpmock.NewStringResponder(429, "") const testURL = "http://testserver.com" httpmock.RegisterResponder("POST", testURL, firstMock, ) _, err := RetrieveToken(context.Background(), clientID, "", testURL, url.Values{}, AuthStyleUnknown) if err == nil { t.Errorf("Expect error to be returned when oauth server fails consistently") } } func TestExpiresInUpperBound(t *testing.T) { var e expirationTime if err := e.UnmarshalJSON([]byte(fmt.Sprint(int64(math.MaxInt32) + 1))); err != nil { t.Fatal(err) } const want = math.MaxInt32 if e != want { t.Errorf("expiration time = %v; want %v", e, want) } } golang-github-openfga-go-sdk-0.3.5/oauth2/internal/transport.go000066400000000000000000000016331456721040100244510ustar00rootroot00000000000000// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package internal import ( "context" "net/http" ) // HTTPClient is the context key to use with golang.org/x/net/context's // WithValue function to associate an *http.Client value with a context. var HTTPClient ContextKey // ContextKey is just an empty struct. It exists so HTTPClient can be // an immutable public variable with a unique type. It's immutable // because nobody else can create a ContextKey, being unexported. type ContextKey struct{} var appengineClientHook func(context.Context) *http.Client func ContextClient(ctx context.Context) *http.Client { if ctx != nil { if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok { return hc } } if appengineClientHook != nil { return appengineClientHook(ctx) } return http.DefaultClient } golang-github-openfga-go-sdk-0.3.5/oauth2/oauth2.go000066400000000000000000000303231456721040100220010ustar00rootroot00000000000000// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package oauth2 provides support for making // OAuth2 authorized and authenticated HTTP requests, // as specified in RFC 6749. // It can additionally grant authorization with Bearer JWT. package oauth2 import ( "bytes" "context" "errors" "github.com/openfga/go-sdk/oauth2/internal" "net/http" "net/url" "strings" "sync" ) // NoContext is the default context you should supply if not using // your own context.Context (see https://golang.org/x/net/context). // // Deprecated: Use context.Background() or context.TODO() instead. var NoContext = context.TODO() // RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op. // // Deprecated: this function no longer does anything. Caller code that // wants to avoid potential extra HTTP requests made during // auto-probing of the provider's auth style should set // Endpoint.AuthStyle. func RegisterBrokenAuthHeaderProvider(tokenURL string) {} // Config describes a typical 3-legged OAuth2 flow, with both the // client application information and the server's endpoint URLs. // For the client credentials 2-legged OAuth2 flow, see the clientcredentials // package (https://golang.org/x/oauth2/clientcredentials). type Config struct { // ClientID is the application's ID. ClientID string // ClientSecret is the application's secret. ClientSecret string // Endpoint contains the resource server's token endpoint // URLs. These are constants specific to each server and are // often available via site-specific packages, such as // google.Endpoint or github.Endpoint. Endpoint Endpoint // RedirectURL is the URL to redirect users going through // the OAuth flow, after the resource owner's URLs. RedirectURL string // Scope specifies optional requested permissions. Scopes []string } // A TokenSource is anything that can return a token. type TokenSource interface { // Token returns a token or an error. // Token must be safe for concurrent use by multiple goroutines. // The returned Token must not be modified. Token() (*Token, error) } // Endpoint represents an OAuth 2.0 provider's authorization and token // endpoint URLs. type Endpoint struct { AuthURL string TokenURL string // AuthStyle optionally specifies how the endpoint wants the // client ID & client secret sent. The zero value means to // auto-detect. AuthStyle AuthStyle } // AuthStyle represents how requests for tokens are authenticated // to the server. type AuthStyle int const ( // AuthStyleAutoDetect means to auto-detect which authentication // style the provider wants by trying both ways and caching // the successful way for the future. AuthStyleAutoDetect AuthStyle = 0 // AuthStyleInParams sends the "client_id" and "client_secret" // in the POST body as application/x-www-form-urlencoded parameters. AuthStyleInParams AuthStyle = 1 // AuthStyleInHeader sends the client_id and client_password // using HTTP Basic Authorization. This is an optional style // described in the OAuth2 RFC 6749 section 2.3.1. AuthStyleInHeader AuthStyle = 2 ) var ( // AccessTypeOnline and AccessTypeOffline are options passed // to the Options.AuthCodeURL method. They modify the // "access_type" field that gets sent in the URL returned by // AuthCodeURL. // // Online is the default if neither is specified. If your // application needs to refresh access tokens when the user // is not present at the browser, then use offline. This will // result in your application obtaining a refresh token the // first time your application exchanges an authorization // code for a user. AccessTypeOnline AuthCodeOption = SetAuthURLParam("access_type", "online") AccessTypeOffline AuthCodeOption = SetAuthURLParam("access_type", "offline") // ApprovalForce forces the users to view the consent dialog // and confirm the permissions request at the URL returned // from AuthCodeURL, even if they've already done so. ApprovalForce AuthCodeOption = SetAuthURLParam("prompt", "consent") ) // An AuthCodeOption is passed to Config.AuthCodeURL. type AuthCodeOption interface { setValue(url.Values) } type setParam struct{ k, v string } func (p setParam) setValue(m url.Values) { m.Set(p.k, p.v) } // SetAuthURLParam builds an AuthCodeOption which passes key/value parameters // to a provider's authorization endpoint. func SetAuthURLParam(key, value string) AuthCodeOption { return setParam{key, value} } // AuthCodeURL returns a URL to OAuth 2.0 provider's consent page // that asks for permissions for the required scopes explicitly. // // State is a token to protect the user from CSRF attacks. You must // always provide a non-empty string and validate that it matches the // the state query parameter on your redirect callback. // See http://tools.ietf.org/html/rfc6749#section-10.12 for more info. // // Opts may include AccessTypeOnline or AccessTypeOffline, as well // as ApprovalForce. // It can also be used to pass the PKCE challenge. // See https://www.oauth.com/oauth2-servers/pkce/ for more info. func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string { var buf bytes.Buffer buf.WriteString(c.Endpoint.AuthURL) v := url.Values{ "response_type": {"code"}, "client_id": {c.ClientID}, } if c.RedirectURL != "" { v.Set("redirect_uri", c.RedirectURL) } if len(c.Scopes) > 0 { v.Set("scope", strings.Join(c.Scopes, " ")) } if state != "" { // TODO(light): Docs say never to omit state; don't allow empty. v.Set("state", state) } for _, opt := range opts { opt.setValue(v) } if strings.Contains(c.Endpoint.AuthURL, "?") { buf.WriteByte('&') } else { buf.WriteByte('?') } buf.WriteString(v.Encode()) return buf.String() } // PasswordCredentialsToken converts a resource owner username and password // pair into a token. // // Per the RFC, this grant type should only be used "when there is a high // degree of trust between the resource owner and the client (e.g., the client // is part of the device operating system or a highly privileged application), // and when other authorization grant types are not available." // See https://tools.ietf.org/html/rfc6749#section-4.3 for more info. // // The provided context optionally controls which HTTP client is used. See the HTTPClient variable. func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) { v := url.Values{ "grant_type": {"password"}, "username": {username}, "password": {password}, } if len(c.Scopes) > 0 { v.Set("scope", strings.Join(c.Scopes, " ")) } return retrieveToken(ctx, c, v) } // Exchange converts an authorization code into a token. // // It is used after a resource provider redirects the user back // to the Redirect URI (the URL obtained from AuthCodeURL). // // The provided context optionally controls which HTTP client is used. See the HTTPClient variable. // // The code will be in the *http.Request.FormValue("code"). Before // calling Exchange, be sure to validate FormValue("state"). // // Opts may include the PKCE verifier code if previously used in AuthCodeURL. // See https://www.oauth.com/oauth2-servers/pkce/ for more info. func (c *Config) Exchange(ctx context.Context, code string, opts ...AuthCodeOption) (*Token, error) { v := url.Values{ "grant_type": {"authorization_code"}, "code": {code}, } if c.RedirectURL != "" { v.Set("redirect_uri", c.RedirectURL) } for _, opt := range opts { opt.setValue(v) } return retrieveToken(ctx, c, v) } // Client returns an HTTP client using the provided token. // The token will auto-refresh as necessary. The underlying // HTTP transport will be obtained using the provided context. // The returned client and its Transport should not be modified. func (c *Config) Client(ctx context.Context, t *Token) *http.Client { return NewClient(ctx, c.TokenSource(ctx, t)) } // TokenSource returns a TokenSource that returns t until t expires, // automatically refreshing it as necessary using the provided context. // // Most users will use Config.Client instead. func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource { tkr := &tokenRefresher{ ctx: ctx, conf: c, } if t != nil { tkr.refreshToken = t.RefreshToken } return &reuseTokenSource{ t: t, new: tkr, } } // tokenRefresher is a TokenSource that makes "grant_type"=="refresh_token" // HTTP requests to renew a token using a RefreshToken. type tokenRefresher struct { ctx context.Context // used to get HTTP requests conf *Config refreshToken string } // WARNING: Token is not safe for concurrent access, as it // updates the tokenRefresher's refreshToken field. // Within this package, it is used by reuseTokenSource which // synchronizes calls to this method with its own mutex. func (tf *tokenRefresher) Token() (*Token, error) { if tf.refreshToken == "" { return nil, errors.New("oauth2: token expired and refresh token is not set") } tk, err := retrieveToken(tf.ctx, tf.conf, url.Values{ "grant_type": {"refresh_token"}, "refresh_token": {tf.refreshToken}, }) if err != nil { return nil, err } if tf.refreshToken != tk.RefreshToken { tf.refreshToken = tk.RefreshToken } return tk, err } // reuseTokenSource is a TokenSource that holds a single token in memory // and validates its expiry before each call to retrieve it with // Token. If it's expired, it will be auto-refreshed using the // new TokenSource. type reuseTokenSource struct { new TokenSource // called when t is expired. mu sync.Mutex // guards t t *Token } // Token returns the current token if it's still valid, else will // refresh the current token (using r.Context for HTTP client // information) and return the new one. func (s *reuseTokenSource) Token() (*Token, error) { s.mu.Lock() defer s.mu.Unlock() if s.t.Valid() { return s.t, nil } t, err := s.new.Token() if err != nil { return nil, err } s.t = t return t, nil } // StaticTokenSource returns a TokenSource that always returns the same token. // Because the provided token t is never refreshed, StaticTokenSource is only // useful for tokens that never expire. func StaticTokenSource(t *Token) TokenSource { return staticTokenSource{t} } // staticTokenSource is a TokenSource that always returns the same Token. type staticTokenSource struct { t *Token } func (s staticTokenSource) Token() (*Token, error) { return s.t, nil } // HTTPClient is the context key to use with golang.org/x/net/context's // WithValue function to associate an *http.Client value with a context. var HTTPClient internal.ContextKey // NewClient creates an *http.Client from a Context and TokenSource. // The returned client is not valid beyond the lifetime of the context. // // Note that if a custom *http.Client is provided via the Context it // is used only for token acquisition and is not used to configure the // *http.Client returned from NewClient. // // As a special case, if src is nil, a non-OAuth2 client is returned // using the provided context. This exists to support related OAuth2 // packages. func NewClient(ctx context.Context, src TokenSource) *http.Client { if src == nil { return internal.ContextClient(ctx) } return &http.Client{ Transport: &Transport{ Base: internal.ContextClient(ctx).Transport, Source: ReuseTokenSource(nil, src), }, } } // ReuseTokenSource returns a TokenSource which repeatedly returns the // same token as long as it's valid, starting with t. // When its cached token is invalid, a new token is obtained from src. // // ReuseTokenSource is typically used to reuse tokens from a cache // (such as a file on disk) between runs of a program, rather than // obtaining new tokens unnecessarily. // // The initial token t may be nil, in which case the TokenSource is // wrapped in a caching version if it isn't one already. This also // means it's always safe to wrap ReuseTokenSource around any other // TokenSource without adverse effects. func ReuseTokenSource(t *Token, src TokenSource) TokenSource { // Don't wrap a reuseTokenSource in itself. That would work, // but cause an unnecessary number of mutex operations. // Just build the equivalent one. if rt, ok := src.(*reuseTokenSource); ok { if t == nil { // Just use it directly. return rt } src = rt.new } return &reuseTokenSource{ t: t, new: src, } } golang-github-openfga-go-sdk-0.3.5/oauth2/oauth2_test.go000066400000000000000000000450621456721040100230460ustar00rootroot00000000000000// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package oauth2 import ( "context" "errors" "fmt" "github.com/openfga/go-sdk/oauth2/internal" "io" "io/ioutil" "net/http" "net/http/httptest" "net/url" "testing" "time" ) type mockTransport struct { rt func(req *http.Request) (resp *http.Response, err error) } func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { return t.rt(req) } func newConf(url string) *Config { return &Config{ ClientID: "CLIENT_ID", ClientSecret: "CLIENT_SECRET", RedirectURL: "REDIRECT_URL", Scopes: []string{"scope1", "scope2"}, Endpoint: Endpoint{ AuthURL: url + "/auth", TokenURL: url + "/token", }, } } func TestAuthCodeURL(t *testing.T) { conf := newConf("server") url := conf.AuthCodeURL("foo", AccessTypeOffline, ApprovalForce) const want = "server/auth?access_type=offline&client_id=CLIENT_ID&prompt=consent&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=foo" if got := url; got != want { t.Errorf("got auth code URL = %q; want %q", got, want) } } func TestAuthCodeURL_CustomParam(t *testing.T) { conf := newConf("server") param := SetAuthURLParam("foo", "bar") url := conf.AuthCodeURL("baz", param) const want = "server/auth?client_id=CLIENT_ID&foo=bar&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=baz" if got := url; got != want { t.Errorf("got auth code = %q; want %q", got, want) } } func TestAuthCodeURL_Optional(t *testing.T) { conf := &Config{ ClientID: "CLIENT_ID", Endpoint: Endpoint{ AuthURL: "/auth-url", TokenURL: "/token-url", }, } url := conf.AuthCodeURL("") const want = "/auth-url?client_id=CLIENT_ID&response_type=code" if got := url; got != want { t.Fatalf("got auth code = %q; want %q", got, want) } } func TestURLUnsafeClientConfig(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if got, want := r.Header.Get("Authorization"), "Basic Q0xJRU5UX0lEJTNGJTNGOkNMSUVOVF9TRUNSRVQlM0YlM0Y="; got != want { t.Errorf("Authorization header = %q; want %q", got, want) } w.Header().Set("Content-Type", "application/x-www-form-urlencoded") w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) })) defer ts.Close() conf := newConf(ts.URL) conf.ClientID = "CLIENT_ID??" conf.ClientSecret = "CLIENT_SECRET??" _, err := conf.Exchange(context.Background(), "exchange-code") if err != nil { t.Error(err) } } func TestExchangeRequest(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.String() != "/token" { t.Errorf("Unexpected exchange request URL %q", r.URL) } headerAuth := r.Header.Get("Authorization") if want := "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ="; headerAuth != want { t.Errorf("Unexpected authorization header %q, want %q", headerAuth, want) } headerContentType := r.Header.Get("Content-Type") if headerContentType != "application/x-www-form-urlencoded" { t.Errorf("Unexpected Content-Type header %q", headerContentType) } body, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("Failed reading request body: %s.", err) } if string(body) != "code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL" { t.Errorf("Unexpected exchange payload; got %q", body) } w.Header().Set("Content-Type", "application/x-www-form-urlencoded") w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) })) defer ts.Close() conf := newConf(ts.URL) tok, err := conf.Exchange(context.Background(), "exchange-code") if err != nil { t.Error(err) } if !tok.Valid() { t.Fatalf("Token invalid. Got: %#v", tok) } if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { t.Errorf("Unexpected access token, %#v.", tok.AccessToken) } if tok.TokenType != "bearer" { t.Errorf("Unexpected token type, %#v.", tok.TokenType) } scope := tok.Extra("scope") if scope != "user" { t.Errorf("Unexpected value for scope: %v", scope) } } func TestExchangeRequest_CustomParam(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.String() != "/token" { t.Errorf("Unexpected exchange request URL, %v is found.", r.URL) } headerAuth := r.Header.Get("Authorization") if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { t.Errorf("Unexpected authorization header, %v is found.", headerAuth) } headerContentType := r.Header.Get("Content-Type") if headerContentType != "application/x-www-form-urlencoded" { t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) } body, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("Failed reading request body: %s.", err) } if string(body) != "code=exchange-code&foo=bar&grant_type=authorization_code&redirect_uri=REDIRECT_URL" { t.Errorf("Unexpected exchange payload, %v is found.", string(body)) } w.Header().Set("Content-Type", "application/x-www-form-urlencoded") w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) })) defer ts.Close() conf := newConf(ts.URL) param := SetAuthURLParam("foo", "bar") tok, err := conf.Exchange(context.Background(), "exchange-code", param) if err != nil { t.Error(err) } if !tok.Valid() { t.Fatalf("Token invalid. Got: %#v", tok) } if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { t.Errorf("Unexpected access token, %#v.", tok.AccessToken) } if tok.TokenType != "bearer" { t.Errorf("Unexpected token type, %#v.", tok.TokenType) } scope := tok.Extra("scope") if scope != "user" { t.Errorf("Unexpected value for scope: %v", scope) } } func TestExchangeRequest_JSONResponse(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.String() != "/token" { t.Errorf("Unexpected exchange request URL, %v is found.", r.URL) } headerAuth := r.Header.Get("Authorization") if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { t.Errorf("Unexpected authorization header, %v is found.", headerAuth) } headerContentType := r.Header.Get("Content-Type") if headerContentType != "application/x-www-form-urlencoded" { t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) } body, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("Failed reading request body: %s.", err) } if string(body) != "code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL" { t.Errorf("Unexpected exchange payload, %v is found.", string(body)) } w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 86400}`)) })) defer ts.Close() conf := newConf(ts.URL) tok, err := conf.Exchange(context.Background(), "exchange-code") if err != nil { t.Error(err) } if !tok.Valid() { t.Fatalf("Token invalid. Got: %#v", tok) } if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { t.Errorf("Unexpected access token, %#v.", tok.AccessToken) } if tok.TokenType != "bearer" { t.Errorf("Unexpected token type, %#v.", tok.TokenType) } scope := tok.Extra("scope") if scope != "user" { t.Errorf("Unexpected value for scope: %v", scope) } expiresIn := tok.Extra("expires_in") if expiresIn != float64(86400) { t.Errorf("Unexpected non-numeric value for expires_in: %v", expiresIn) } } func TestExtraValueRetrieval(t *testing.T) { values := url.Values{} kvmap := map[string]string{ "scope": "user", "token_type": "bearer", "expires_in": "86400.92", "server_time": "1443571905.5606415", "referer_ip": "10.0.0.1", "etag": "\"afZYj912P4alikMz_P11982\"", "request_id": "86400", "untrimmed": " untrimmed ", } for key, value := range kvmap { values.Set(key, value) } tok := Token{raw: values} scope := tok.Extra("scope") if got, want := scope, "user"; got != want { t.Errorf("got scope = %q; want %q", got, want) } serverTime := tok.Extra("server_time") if got, want := serverTime, 1443571905.5606415; got != want { t.Errorf("got server_time value = %v; want %v", got, want) } refererIP := tok.Extra("referer_ip") if got, want := refererIP, "10.0.0.1"; got != want { t.Errorf("got referer_ip value = %v, want %v", got, want) } expiresIn := tok.Extra("expires_in") if got, want := expiresIn, 86400.92; got != want { t.Errorf("got expires_in value = %v, want %v", got, want) } requestID := tok.Extra("request_id") if got, want := requestID, int64(86400); got != want { t.Errorf("got request_id value = %v, want %v", got, want) } untrimmed := tok.Extra("untrimmed") if got, want := untrimmed, " untrimmed "; got != want { t.Errorf("got untrimmed = %q; want %q", got, want) } } const day = 24 * time.Hour func TestExchangeRequest_JSONResponse_Expiry(t *testing.T) { seconds := int32(day.Seconds()) for _, c := range []struct { name string expires string want bool nullExpires bool }{ {"normal", fmt.Sprintf(`"expires_in": %d`, seconds), true, false}, {"paypal", fmt.Sprintf(`"expires_in": "%d"`, seconds), true, false}, {"issue_239", fmt.Sprintf(`"expires_in": null`), true, true}, {"wrong_type", `"expires_in": false`, false, false}, {"wrong_type2", `"expires_in": {}`, false, false}, {"wrong_value", `"expires_in": "zzz"`, false, false}, } { t.Run(c.name, func(t *testing.T) { testExchangeRequest_JSONResponse_expiry(t, c.expires, c.want, c.nullExpires) }) } } func testExchangeRequest_JSONResponse_expiry(t *testing.T, exp string, want, nullExpires bool) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(fmt.Sprintf(`{"access_token": "90d", "scope": "user", "token_type": "bearer", %s}`, exp))) })) defer ts.Close() conf := newConf(ts.URL) t1 := time.Now().Add(day) tok, err := conf.Exchange(context.Background(), "exchange-code") t2 := t1.Add(day) if got := (err == nil); got != want { if want { t.Errorf("unexpected error: got %v", err) } else { t.Errorf("unexpected success") } } if !want { return } if !tok.Valid() { t.Fatalf("Token invalid. Got: %#v", tok) } expiry := tok.Expiry if nullExpires && expiry.IsZero() { return } if expiry.Before(t1) || expiry.After(t2) { t.Errorf("Unexpected value for Expiry: %v (should be between %v and %v)", expiry, t1, t2) } } func TestExchangeRequest_BadResponse(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`)) })) defer ts.Close() conf := newConf(ts.URL) _, err := conf.Exchange(context.Background(), "code") if err == nil { t.Error("expected error from missing access_token") } } func TestExchangeRequest_BadResponseType(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`)) })) defer ts.Close() conf := newConf(ts.URL) _, err := conf.Exchange(context.Background(), "exchange-code") if err == nil { t.Error("expected error from non-string access_token") } } func TestExchangeRequest_NonBasicAuth(t *testing.T) { internal.ResetAuthCache() tr := &mockTransport{ rt: func(r *http.Request) (w *http.Response, err error) { headerAuth := r.Header.Get("Authorization") if headerAuth != "" { t.Errorf("Unexpected authorization header %q", headerAuth) } return nil, errors.New("no response") }, } c := &http.Client{Transport: tr} conf := &Config{ ClientID: "CLIENT_ID", Endpoint: Endpoint{ AuthURL: "https://accounts.google.com/auth", TokenURL: "https://accounts.google.com/token", AuthStyle: AuthStyleInParams, }, } ctx := context.WithValue(context.Background(), HTTPClient, c) conf.Exchange(ctx, "code") } func TestPasswordCredentialsTokenRequest(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() expected := "/token" if r.URL.String() != expected { t.Errorf("URL = %q; want %q", r.URL, expected) } headerAuth := r.Header.Get("Authorization") expected = "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" if headerAuth != expected { t.Errorf("Authorization header = %q; want %q", headerAuth, expected) } headerContentType := r.Header.Get("Content-Type") expected = "application/x-www-form-urlencoded" if headerContentType != expected { t.Errorf("Content-Type header = %q; want %q", headerContentType, expected) } body, err := ioutil.ReadAll(r.Body) if err != nil { t.Errorf("Failed reading request body: %s.", err) } expected = "grant_type=password&password=password1&scope=scope1+scope2&username=user1" if string(body) != expected { t.Errorf("res.Body = %q; want %q", string(body), expected) } w.Header().Set("Content-Type", "application/x-www-form-urlencoded") w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) })) defer ts.Close() conf := newConf(ts.URL) tok, err := conf.PasswordCredentialsToken(context.Background(), "user1", "password1") if err != nil { t.Error(err) } if !tok.Valid() { t.Fatalf("Token invalid. Got: %#v", tok) } expected := "90d64460d14870c08c81352a05dedd3465940a7c" if tok.AccessToken != expected { t.Errorf("AccessToken = %q; want %q", tok.AccessToken, expected) } expected = "bearer" if tok.TokenType != expected { t.Errorf("TokenType = %q; want %q", tok.TokenType, expected) } } func TestTokenRefreshRequest(t *testing.T) { internal.ResetAuthCache() ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.String() == "/somethingelse" { return } if r.URL.String() != "/token" { t.Errorf("Unexpected token refresh request URL %q", r.URL) } headerContentType := r.Header.Get("Content-Type") if headerContentType != "application/x-www-form-urlencoded" { t.Errorf("Unexpected Content-Type header %q", headerContentType) } body, _ := ioutil.ReadAll(r.Body) if string(body) != "grant_type=refresh_token&refresh_token=REFRESH_TOKEN" { t.Errorf("Unexpected refresh token payload %q", body) } w.Header().Set("Content-Type", "application/json") io.WriteString(w, `{"access_token": "foo", "refresh_token": "bar"}`) })) defer ts.Close() conf := newConf(ts.URL) c := conf.Client(context.Background(), &Token{RefreshToken: "REFRESH_TOKEN"}) c.Get(ts.URL + "/somethingelse") } func TestFetchWithNoRefreshToken(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.String() == "/somethingelse" { return } if r.URL.String() != "/token" { t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) } headerContentType := r.Header.Get("Content-Type") if headerContentType != "application/x-www-form-urlencoded" { t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) } body, _ := ioutil.ReadAll(r.Body) if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" { t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) } })) defer ts.Close() conf := newConf(ts.URL) c := conf.Client(context.Background(), nil) _, err := c.Get(ts.URL + "/somethingelse") if err == nil { t.Errorf("Fetch should return an error if no refresh token is set") } } func TestTokenRetrieveError(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.String() != "/token" { t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) } w.Header().Set("Content-type", "application/json") w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`{"error": "invalid_grant"}`)) })) defer ts.Close() conf := newConf(ts.URL) _, err := conf.Exchange(context.Background(), "exchange-code") if err == nil { t.Fatalf("got no error, expected one") } _, ok := err.(*RetrieveError) if !ok { t.Fatalf("got %T error, expected *RetrieveError; error was: %v", err, err) } // Test error string for backwards compatibility expected := fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", "400 Bad Request", `{"error": "invalid_grant"}`) if errStr := err.Error(); errStr != expected { t.Fatalf("got %#v, expected %#v", errStr, expected) } } func TestRefreshToken_RefreshTokenReplacement(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"access_token":"ACCESS_TOKEN", "scope": "user", "token_type": "bearer", "refresh_token": "NEW_REFRESH_TOKEN"}`)) return })) defer ts.Close() conf := newConf(ts.URL) tkr := conf.TokenSource(context.Background(), &Token{RefreshToken: "OLD_REFRESH_TOKEN"}) tk, err := tkr.Token() if err != nil { t.Errorf("got err = %v; want none", err) return } if want := "NEW_REFRESH_TOKEN"; tk.RefreshToken != want { t.Errorf("RefreshToken = %q; want %q", tk.RefreshToken, want) } } func TestRefreshToken_RefreshTokenPreservation(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(`{"access_token":"ACCESS_TOKEN", "scope": "user", "token_type": "bearer"}`)) return })) defer ts.Close() conf := newConf(ts.URL) const oldRefreshToken = "OLD_REFRESH_TOKEN" tkr := conf.TokenSource(context.Background(), &Token{RefreshToken: oldRefreshToken}) tk, err := tkr.Token() if err != nil { t.Fatalf("got err = %v; want none", err) } if tk.RefreshToken != oldRefreshToken { t.Errorf("RefreshToken = %q; want %q", tk.RefreshToken, oldRefreshToken) } } func TestConfigClientWithToken(t *testing.T) { tok := &Token{ AccessToken: "abc123", } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if got, want := r.Header.Get("Authorization"), fmt.Sprintf("Bearer %s", tok.AccessToken); got != want { t.Errorf("Authorization header = %q; want %q", got, want) } return })) defer ts.Close() conf := newConf(ts.URL) c := conf.Client(context.Background(), tok) req, err := http.NewRequest("GET", ts.URL, nil) if err != nil { t.Error(err) } _, err = c.Do(req) if err != nil { t.Error(err) } } golang-github-openfga-go-sdk-0.3.5/oauth2/token.go000066400000000000000000000117361456721040100217260ustar00rootroot00000000000000// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package oauth2 import ( "context" "fmt" "github.com/openfga/go-sdk/oauth2/internal" "net/http" "net/url" "strconv" "strings" "time" ) // expiryDelta determines how earlier a token should be considered // expired than its actual expiration time. It is used to avoid late // expirations due to client-server time mismatches. const expiryDelta = 10 * time.Second // Token represents the credentials used to authorize // the requests to access protected resources on the OAuth 2.0 // provider's backend. // // Most users of this package should not access fields of Token // directly. They're exported mostly for use by related packages // implementing derivative OAuth2 flows. type Token struct { // AccessToken is the token that authorizes and authenticates // the requests. AccessToken string `json:"access_token"` // TokenType is the type of token. // The Type method returns either this or "Bearer", the default. TokenType string `json:"token_type,omitempty"` // RefreshToken is a token that's used by the application // (as opposed to the user) to refresh the access token // if it expires. RefreshToken string `json:"refresh_token,omitempty"` // Expiry is the optional expiration time of the access token. // // If zero, TokenSource implementations will reuse the same // token forever and RefreshToken or equivalent // mechanisms for that TokenSource will not be used. Expiry time.Time `json:"expiry,omitempty"` // raw optionally contains extra metadata from the server // when updating a token. raw interface{} } // Type returns t.TokenType if non-empty, else "Bearer". func (t *Token) Type() string { if strings.EqualFold(t.TokenType, "bearer") { return "Bearer" } if strings.EqualFold(t.TokenType, "mac") { return "MAC" } if strings.EqualFold(t.TokenType, "basic") { return "Basic" } if t.TokenType != "" { return t.TokenType } return "Bearer" } // SetAuthHeader sets the Authorization header to r using the access // token in t. // // This method is unnecessary when using Transport or an HTTP Client // returned by this package. func (t *Token) SetAuthHeader(r *http.Request) { r.Header.Set("Authorization", t.Type()+" "+t.AccessToken) } // WithExtra returns a new Token that's a clone of t, but using the // provided raw extra map. This is only intended for use by packages // implementing derivative OAuth2 flows. func (t *Token) WithExtra(extra interface{}) *Token { t2 := new(Token) *t2 = *t t2.raw = extra return t2 } // Extra returns an extra field. // Extra fields are key-value pairs returned by the server as a // part of the token retrieval response. func (t *Token) Extra(key string) interface{} { if raw, ok := t.raw.(map[string]interface{}); ok { return raw[key] } vals, ok := t.raw.(url.Values) if !ok { return nil } v := vals.Get(key) switch s := strings.TrimSpace(v); strings.Count(s, ".") { case 0: // Contains no "."; try to parse as int if i, err := strconv.ParseInt(s, 10, 64); err == nil { return i } case 1: // Contains a single "."; try to parse as float if f, err := strconv.ParseFloat(s, 64); err == nil { return f } } return v } // timeNow is time.Now but pulled out as a variable for tests. var timeNow = time.Now // expired reports whether the token is expired. // t must be non-nil. func (t *Token) expired() bool { if t.Expiry.IsZero() { return false } return t.Expiry.Round(0).Add(-expiryDelta).Before(timeNow()) } // Valid reports whether t is non-nil, has an AccessToken, and is not expired. func (t *Token) Valid() bool { return t != nil && t.AccessToken != "" && !t.expired() } // tokenFromInternal maps an *internal.Token struct into // a *Token struct. func tokenFromInternal(t *internal.Token) *Token { if t == nil { return nil } return &Token{ AccessToken: t.AccessToken, TokenType: t.TokenType, RefreshToken: t.RefreshToken, Expiry: t.Expiry, raw: t.Raw, } } // retrieveToken takes a *Config and uses that to retrieve an *internal.Token. // This token is then mapped from *internal.Token into an *oauth2.Token which is returned along // with an error.. func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) { tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v, internal.AuthStyle(c.Endpoint.AuthStyle)) if err != nil { if rErr, ok := err.(*internal.RetrieveError); ok { return nil, (*RetrieveError)(rErr) } return nil, err } return tokenFromInternal(tk), nil } // RetrieveError is the error returned when the token endpoint returns a // non-2XX HTTP status code. type RetrieveError struct { Response *http.Response // Body is the body that was consumed by reading Response.Body. // It may be truncated. Body []byte } func (r *RetrieveError) Error() string { return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body) } golang-github-openfga-go-sdk-0.3.5/oauth2/token_test.go000066400000000000000000000042701456721040100227600ustar00rootroot00000000000000// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package oauth2 import ( "testing" "time" ) func TestTokenExtra(t *testing.T) { type testCase struct { key string val interface{} want interface{} } const key = "extra-key" cases := []testCase{ {key: key, val: "abc", want: "abc"}, {key: key, val: 123, want: 123}, {key: key, val: "", want: ""}, {key: "other-key", val: "def", want: nil}, } for _, tc := range cases { extra := make(map[string]interface{}) extra[tc.key] = tc.val tok := &Token{raw: extra} if got, want := tok.Extra(key), tc.want; got != want { t.Errorf("Extra(%q) = %q; want %q", key, got, want) } } } func TestTokenExpiry(t *testing.T) { now := time.Now() timeNow = func() time.Time { return now } defer func() { timeNow = time.Now }() cases := []struct { name string tok *Token want bool }{ {name: "12 seconds", tok: &Token{Expiry: now.Add(12 * time.Second)}, want: false}, {name: "10 seconds", tok: &Token{Expiry: now.Add(expiryDelta)}, want: false}, {name: "10 seconds-1ns", tok: &Token{Expiry: now.Add(expiryDelta - 1*time.Nanosecond)}, want: true}, {name: "-1 hour", tok: &Token{Expiry: now.Add(-1 * time.Hour)}, want: true}, } for _, tc := range cases { if got, want := tc.tok.expired(), tc.want; got != want { t.Errorf("expired (%q) = %v; want %v", tc.name, got, want) } } } func TestTokenTypeMethod(t *testing.T) { cases := []struct { name string tok *Token want string }{ {name: "bearer-mixed_case", tok: &Token{TokenType: "beAREr"}, want: "Bearer"}, {name: "default-bearer", tok: &Token{}, want: "Bearer"}, {name: "basic", tok: &Token{TokenType: "basic"}, want: "Basic"}, {name: "basic-capitalized", tok: &Token{TokenType: "Basic"}, want: "Basic"}, {name: "mac", tok: &Token{TokenType: "mac"}, want: "MAC"}, {name: "mac-caps", tok: &Token{TokenType: "MAC"}, want: "MAC"}, {name: "mac-mixed_case", tok: &Token{TokenType: "mAc"}, want: "MAC"}, } for _, tc := range cases { if got, want := tc.tok.Type(), tc.want; got != want { t.Errorf("TokenType(%q) = %v; want %v", tc.name, got, want) } } } golang-github-openfga-go-sdk-0.3.5/oauth2/transport.go000066400000000000000000000036471456721040100226440ustar00rootroot00000000000000// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package oauth2 import ( "errors" "net/http" ) // Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests, // wrapping a base RoundTripper and adding an Authorization header // with a token from the supplied Sources. // // Transport is a low-level mechanism. Most code will use the // higher-level Config.Client method instead. type Transport struct { // Source supplies the token to add to outgoing requests' // Authorization headers. Source TokenSource // Base is the base RoundTripper used to make HTTP requests. // If nil, http.DefaultTransport is used. Base http.RoundTripper } // RoundTrip authorizes and authenticates the request with an // access token from Transport's Source. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { reqBodyClosed := false if req.Body != nil { defer func() { if !reqBodyClosed { req.Body.Close() } }() } if t.Source == nil { return nil, errors.New("oauth2: Transport's Source is nil") } token, err := t.Source.Token() if err != nil { return nil, err } req2 := cloneRequest(req) // per RoundTripper contract token.SetAuthHeader(req2) // req.Body is assumed to be closed by the base RoundTripper. reqBodyClosed = true return t.base().RoundTrip(req2) } func (t *Transport) base() http.RoundTripper { if t.Base != nil { return t.Base } return http.DefaultTransport } // cloneRequest returns a clone of the provided *http.Request. // The clone is a shallow copy of the struct and its Header map. func cloneRequest(r *http.Request) *http.Request { // shallow copy of the struct r2 := new(http.Request) *r2 = *r // deep copy of the Header r2.Header = make(http.Header, len(r.Header)) for k, s := range r.Header { r2.Header[k] = append([]string(nil), s...) } return r2 } golang-github-openfga-go-sdk-0.3.5/oauth2/transport_test.go000066400000000000000000000077541456721040100237060ustar00rootroot00000000000000package oauth2 import ( "errors" "io" "net/http" "net/http/httptest" "testing" "time" ) type tokenSource struct{ token *Token } func (t *tokenSource) Token() (*Token, error) { return t.token, nil } func TestTransportNilTokenSource(t *testing.T) { tr := &Transport{} server := newMockServer(func(w http.ResponseWriter, r *http.Request) {}) defer server.Close() client := &http.Client{Transport: tr} resp, err := client.Get(server.URL) if err == nil { t.Errorf("got no errors, want an error with nil token source") } if resp != nil { t.Errorf("Response = %v; want nil", resp) } } type readCloseCounter struct { CloseCount int ReadErr error } func (r *readCloseCounter) Read(b []byte) (int, error) { return 0, r.ReadErr } func (r *readCloseCounter) Close() error { r.CloseCount++ return nil } func TestTransportCloseRequestBody(t *testing.T) { tr := &Transport{} server := newMockServer(func(w http.ResponseWriter, r *http.Request) {}) defer server.Close() client := &http.Client{Transport: tr} body := &readCloseCounter{ ReadErr: errors.New("readCloseCounter.Read not implemented"), } resp, err := client.Post(server.URL, "application/json", body) if err == nil { t.Errorf("got no errors, want an error with nil token source") } if resp != nil { t.Errorf("Response = %v; want nil", resp) } if expected := 1; body.CloseCount != expected { t.Errorf("Body was closed %d times, expected %d", body.CloseCount, expected) } } func TestTransportCloseRequestBodySuccess(t *testing.T) { tr := &Transport{ Source: StaticTokenSource(&Token{ AccessToken: "abc", }), } server := newMockServer(func(w http.ResponseWriter, r *http.Request) {}) defer server.Close() client := &http.Client{Transport: tr} body := &readCloseCounter{ ReadErr: io.EOF, } resp, err := client.Post(server.URL, "application/json", body) if err != nil { t.Errorf("got error %v; expected none", err) } if resp == nil { t.Errorf("Response is nil; expected non-nil") } if expected := 1; body.CloseCount != expected { t.Errorf("Body was closed %d times, expected %d", body.CloseCount, expected) } } func TestTransportTokenSource(t *testing.T) { ts := &tokenSource{ token: &Token{ AccessToken: "abc", }, } tr := &Transport{ Source: ts, } server := newMockServer(func(w http.ResponseWriter, r *http.Request) { if got, want := r.Header.Get("Authorization"), "Bearer abc"; got != want { t.Errorf("Authorization header = %q; want %q", got, want) } }) defer server.Close() client := &http.Client{Transport: tr} res, err := client.Get(server.URL) if err != nil { t.Fatal(err) } res.Body.Close() } // Test for case-sensitive token types, per https://github.com/golang/oauth2/issues/113 func TestTransportTokenSourceTypes(t *testing.T) { const val = "abc" tests := []struct { key string val string want string }{ {key: "bearer", val: val, want: "Bearer abc"}, {key: "mac", val: val, want: "MAC abc"}, {key: "basic", val: val, want: "Basic abc"}, } for _, tc := range tests { ts := &tokenSource{ token: &Token{ AccessToken: tc.val, TokenType: tc.key, }, } tr := &Transport{ Source: ts, } server := newMockServer(func(w http.ResponseWriter, r *http.Request) { if got, want := r.Header.Get("Authorization"), tc.want; got != want { t.Errorf("Authorization header (%q) = %q; want %q", val, got, want) } }) defer server.Close() client := &http.Client{Transport: tr} res, err := client.Get(server.URL) if err != nil { t.Fatal(err) } res.Body.Close() } } func TestTokenValidNoAccessToken(t *testing.T) { token := &Token{} if token.Valid() { t.Errorf("got valid with no access token; want invalid") } } func TestExpiredWithExpiry(t *testing.T) { token := &Token{ Expiry: time.Now().Add(-5 * time.Hour), } if token.Valid() { t.Errorf("got valid with expired token; want invalid") } } func newMockServer(handler func(w http.ResponseWriter, r *http.Request)) *httptest.Server { return httptest.NewServer(http.HandlerFunc(handler)) } golang-github-openfga-go-sdk-0.3.5/response.go000066400000000000000000000030721456721040100212340ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "net/http" ) // APIResponse stores the API response returned by the server. type APIResponse struct { *http.Response `json:"-"` Message string `json:"message,omitempty"` // Operation is the name of the OpenAPI operation. Operation string `json:"operation,omitempty"` // RequestURL is the request URL. This value is always available, even if the // embedded *http.Response is nil. RequestURL string `json:"url,omitempty"` // Method is the HTTP method used for the request. This value is always // available, even if the embedded *http.Response is nil. Method string `json:"method,omitempty"` // Payload holds the contents of the response body (which may be nil or empty). // This is provided here as the raw response.Body() reader will have already // been drained. Payload []byte `json:"-"` } // NewAPIResponse returns a new APIResponse object. func NewAPIResponse(r *http.Response) *APIResponse { response := &APIResponse{Response: r} return response } // NewAPIResponseWithError returns a new APIResponse object with the provided error message. func NewAPIResponseWithError(errorMessage string) *APIResponse { response := &APIResponse{Message: errorMessage} return response } golang-github-openfga-go-sdk-0.3.5/utils.go000066400000000000000000000151241456721040100205370ustar00rootroot00000000000000/** * Go SDK for OpenFGA * * API version: 0.1 * Website: https://openfga.dev * Documentation: https://openfga.dev/docs * Support: https://discord.gg/8naAwJfWN6 * License: [Apache-2.0](https://github.com/openfga/go-sdk/blob/main/LICENSE) * * NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT. */ package openfga import ( "encoding/json" "net/url" "time" ) // PtrBool is a helper routine that returns a pointer to given boolean value. func PtrBool(v bool) *bool { return &v } // PtrInt is a helper routine that returns a pointer to given integer value. func PtrInt(v int) *int { return &v } // PtrInt32 is a helper routine that returns a pointer to given integer value. func PtrInt32(v int32) *int32 { return &v } // PtrInt64 is a helper routine that returns a pointer to given integer value. func PtrInt64(v int64) *int64 { return &v } // PtrFloat32 is a helper routine that returns a pointer to given float value. func PtrFloat32(v float32) *float32 { return &v } // PtrFloat64 is a helper routine that returns a pointer to given float value. func PtrFloat64(v float64) *float64 { return &v } // PtrString is a helper routine that returns a pointer to given string value. func PtrString(v string) *string { return &v } // PtrTime is helper routine that returns a pointer to given Time value. func PtrTime(v time.Time) *time.Time { return &v } type NullableBool struct { value *bool isSet bool } func (v NullableBool) Get() *bool { return v.value } func (v *NullableBool) Set(val *bool) { v.value = val v.isSet = true } func (v NullableBool) IsSet() bool { return v.isSet } func (v *NullableBool) Unset() { v.value = nil v.isSet = false } func NewNullableBool(val *bool) *NullableBool { return &NullableBool{value: val, isSet: true} } func (v NullableBool) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableBool) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableInt struct { value *int isSet bool } func (v NullableInt) Get() *int { return v.value } func (v *NullableInt) Set(val *int) { v.value = val v.isSet = true } func (v NullableInt) IsSet() bool { return v.isSet } func (v *NullableInt) Unset() { v.value = nil v.isSet = false } func NewNullableInt(val *int) *NullableInt { return &NullableInt{value: val, isSet: true} } func (v NullableInt) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableInt) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableInt32 struct { value *int32 isSet bool } func (v NullableInt32) Get() *int32 { return v.value } func (v *NullableInt32) Set(val *int32) { v.value = val v.isSet = true } func (v NullableInt32) IsSet() bool { return v.isSet } func (v *NullableInt32) Unset() { v.value = nil v.isSet = false } func NewNullableInt32(val *int32) *NullableInt32 { return &NullableInt32{value: val, isSet: true} } func (v NullableInt32) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableInt32) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableInt64 struct { value *int64 isSet bool } func (v NullableInt64) Get() *int64 { return v.value } func (v *NullableInt64) Set(val *int64) { v.value = val v.isSet = true } func (v NullableInt64) IsSet() bool { return v.isSet } func (v *NullableInt64) Unset() { v.value = nil v.isSet = false } func NewNullableInt64(val *int64) *NullableInt64 { return &NullableInt64{value: val, isSet: true} } func (v NullableInt64) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableInt64) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableFloat32 struct { value *float32 isSet bool } func (v NullableFloat32) Get() *float32 { return v.value } func (v *NullableFloat32) Set(val *float32) { v.value = val v.isSet = true } func (v NullableFloat32) IsSet() bool { return v.isSet } func (v *NullableFloat32) Unset() { v.value = nil v.isSet = false } func NewNullableFloat32(val *float32) *NullableFloat32 { return &NullableFloat32{value: val, isSet: true} } func (v NullableFloat32) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableFloat32) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableFloat64 struct { value *float64 isSet bool } func (v NullableFloat64) Get() *float64 { return v.value } func (v *NullableFloat64) Set(val *float64) { v.value = val v.isSet = true } func (v NullableFloat64) IsSet() bool { return v.isSet } func (v *NullableFloat64) Unset() { v.value = nil v.isSet = false } func NewNullableFloat64(val *float64) *NullableFloat64 { return &NullableFloat64{value: val, isSet: true} } func (v NullableFloat64) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableFloat64) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableString struct { value *string isSet bool } func (v NullableString) Get() *string { return v.value } func (v *NullableString) Set(val *string) { v.value = val v.isSet = true } func (v NullableString) IsSet() bool { return v.isSet } func (v *NullableString) Unset() { v.value = nil v.isSet = false } func NewNullableString(val *string) *NullableString { return &NullableString{value: val, isSet: true} } func (v NullableString) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableString) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } type NullableTime struct { value *time.Time isSet bool } func (v NullableTime) Get() *time.Time { return v.value } func (v *NullableTime) Set(val *time.Time) { v.value = val v.isSet = true } func (v NullableTime) IsSet() bool { return v.isSet } func (v *NullableTime) Unset() { v.value = nil v.isSet = false } func NewNullableTime(val *time.Time) *NullableTime { return &NullableTime{value: val, isSet: true} } func (v NullableTime) MarshalJSON() ([]byte, error) { return v.value.MarshalJSON() } func (v *NullableTime) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } func IsWellFormedUri(uriString string) bool { uri, err := url.Parse(uriString) if err != nil || uri.String() != uriString || uri.Host == "" || uri.Host == "http:" || uri.Host == "https:" || // an indicator of a misconfiguration (uri.Scheme != "http" && uri.Scheme != "https") { return false } return true }