diff --git a/.buildkite/pipeline.yaml b/.buildkite/pipeline.yaml new file mode 100644 index 0000000..e4d8669 --- /dev/null +++ b/.buildkite/pipeline.yaml @@ -0,0 +1,89 @@ +env: + APP_NAME: ${BUILDKITE_PIPELINE_SLUG} + SONAR_HOST: "https://sonarcloud.io" +steps: + - group: ":knife: Pre-check" + key: "precheck" + steps: + - label: ":golang: go generate" + key: "generate" + plugins: + - docker#v5.11.0: + image: "ghcr.io/theopenlane/build-image:v0.1.2" + command: ["task", "ci"] + environment: + - "GOTOOLCHAIN=auto" + - group: ":test_tube: Tests" + key: "tests" + depends_on: "precheck" + steps: + - label: ":golangci-lint: lint :lint-roller:" + key: "lint" + plugins: + - docker#v5.11.0: + image: "registry.hub.docker.com/golangci/golangci-lint:latest-alpine" + cancel_on_build_failing: true + command: ["golangci-lint", "run", "-v"] + always-pull: true + environment: + - "GOTOOLCHAIN=auto" + - label: ":golang: go test" + key: "go_test" + plugins: + - docker#v5.11.0: + image: golang:1.23.0 + command: ["go", "test", "-coverprofile=coverage.out", "./..."] + artifact_paths: ["coverage.out"] + - label: ":test_tube: generate example" + key: "example_generate" + plugins: + - docker#v5.11.0: + image: "ghcr.io/theopenlane/build-image:v0.1.2" + workdir: "/fgax" + command: ["task", "example:generate"] + environment: + - "GOTOOLCHAIN=auto" + - group: ":closed_lock_with_key: Security Checks" + depends_on: "tests" + key: "security" + steps: + - label: ":closed_lock_with_key: gosec" + key: "gosec" + plugins: + - docker#v5.11.0: + image: "registry.hub.docker.com/securego/gosec:2.20.0" + command: ["-no-fail", "-exclude-generated", "-fmt sonarqube", "-out", "results.txt", "./..."] + environment: + - "GOTOOLCHAIN=auto" + artifact_paths: ["results.txt"] + - label: ":github: upload PR reports" + key: "scan-upload-pr" + if: build.pull_request.id != null + depends_on: ["gosec", "go_test"] + plugins: + - artifacts#v1.9.4: + download: "results.txt" + - artifacts#v1.9.4: + download: "coverage.out" + step: "go_test" + - docker#v5.11.0: + image: "sonarsource/sonar-scanner-cli:5" + environment: + - "SONAR_TOKEN" + - "SONAR_HOST_URL=$SONAR_HOST" + - "SONAR_SCANNER_OPTS=-Dsonar.pullrequest.branch=$BUILDKITE_BRANCH -Dsonar.pullrequest.base=$BUILDKITE_PULL_REQUEST_BASE_BRANCH -Dsonar.pullrequest.key=$BUILDKITE_PULL_REQUEST" + - label: ":github: upload reports" + key: "scan-upload" + if: build.branch == "main" + depends_on: ["gosec", "go_test"] + plugins: + - artifacts#v1.9.4: + download: results.txt + - artifacts#v1.9.4: + download: coverage.out + step: "go_test" + - docker#v5.11.0: + image: "sonarsource/sonar-scanner-cli:5" + environment: + - "SONAR_TOKEN" + - "SONAR_HOST_URL=$SONAR_HOST" diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..f906a12 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @theopenlane/blacksmiths \ No newline at end of file diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 0000000..6e813dc --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,9 @@ +# Add 'bug' label to any PR where the head branch name starts with `bug` or has a `bug` section in the name +bug: + - head-branch: ["^bug", "bug"] +# Add 'enhancement' label to any PR where the head branch name starts with `enhancement` or has a `enhancement` section in the name +enhancement: + - head-branch: ["^enhancement", "enhancement", "^feature", "feature", "^enhance", "enhance", "^feat", "feat"] +# Add 'breaking-change' label to any PR where the head branch name starts with `breaking-change` or has a `breaking-change` section in the name +breaking-change: + - head-branch: ["^breaking-change", "breaking-change"] diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 0000000..37df9bc --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,24 @@ +changelog: + exclude: + labels: + - ignore-for-release + authors: [] + categories: + - title: Breaking Changes 🛠 + labels: + - Semver-Major + - breaking-change + - title: New Features 🎉 + labels: + - Semver-Minor + - enhancement + - feature + - title: Bug Fixes 🐛 + labels: + - bug + - title: 👒 Dependencies + labels: + - dependencies + - title: Other Changes + labels: + - "*" diff --git a/.github/workflows/labeler.yaml b/.github/workflows/labeler.yaml new file mode 100644 index 0000000..fc43cb1 --- /dev/null +++ b/.github/workflows/labeler.yaml @@ -0,0 +1,13 @@ +name: "Pull Request Labeler" +on: + - pull_request_target +jobs: + triage: + permissions: + contents: read + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@v5 + with: + sync-labels: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6978059 --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +*.exe +*.exe~ +*.dll +*.so +*.dylib + +*.test + +*.out + +go.work + +*.db +server.crt +server.key +private_key.pem +public_key.pem + +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar + +*.log + +.vscode + +.DS_Store* +.AppleDouble +.LSOverride +ehthumbs.db +Icon? +Thumbs.db + +*.mime +*.mim + +*.env +*.env-dev +*.config.yaml \ No newline at end of file diff --git a/.golangci.yaml b/.golangci.yaml new file mode 100644 index 0000000..a82e48c --- /dev/null +++ b/.golangci.yaml @@ -0,0 +1,43 @@ +run: + timeout: 10m + allow-serial-runners: true + concurrency: 0 +linters-settings: + goimports: + local-prefixes: github.com/theopenlane/iam + gofumpt: + extra-rules: true + gosec: + exclude-generated: true + revive: + ignore-generated-header: true +linters: + enable: + - bodyclose + - errcheck + - gocritic + - gocyclo + - err113 + - gofmt + - goimports + - mnd + - gosimple + - govet + - gosec + - ineffassign + - misspell + - noctx + - revive + - staticcheck + - stylecheck + - typecheck + - unused + - whitespace + - wsl +issues: + fix: true + exclude-use-default: true + exclude-dirs: + - mockery/* + - entfga/_examples/* + - entfga/templates/* diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..c725ca1 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,16 @@ +default_stages: [pre-commit] +fail_fast: true +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: trailing-whitespace + - id: detect-private-key + - repo: https://github.com/google/yamlfmt + rev: v0.13.0 + hooks: + - id: yamlfmt + - repo: https://github.com/crate-ci/typos + rev: v1.24.1 + hooks: + - id: typos diff --git a/.typos.toml b/.typos.toml new file mode 100644 index 0000000..52a69c0 --- /dev/null +++ b/.typos.toml @@ -0,0 +1,20 @@ +[files] +extend-exclude = ["db","internal/ent/generated/**","go.mod","go.sum","pkg/testutils/","pkg/passwd/","pkg/tokens/testdata/","pkg/tokens/expires_test.go","internal/graphapi/tools_test.go","internal/httpserve/handlers/tools_test.go","pkg/keygen/auth_test.go","pkg/utils/oas/","pkg/keygen/crypto_test.go","pkg/auth/auth_test.go"] +ignore-hidden = true +ignore-files = true +ignore-dot = true +ignore-vcs = true +ignore-global = true +ignore-parent = true + +[default] +binary = false +check-filename = true +check-file = true +unicode = true +ignore-hex = true +identifier-leading-digits = false +locale = "en" +extend-ignore-identifiers-re = [] +extend-ignore-words-re = ["(?i)requestor","(?i)indentity","(?i)encrypter","(?i)seeked","(?i)generater"] +extend-ignore-re = ["#\\s*spellchecker:off\\s*\\n.*\\n\\s*#\\s*spellchecker:on"] \ No newline at end of file diff --git a/.yamlfmt b/.yamlfmt new file mode 100644 index 0000000..f6cfc8b --- /dev/null +++ b/.yamlfmt @@ -0,0 +1,4 @@ +exclude: + - config/ +formatter: + retain_line_breaks: true \ No newline at end of file diff --git a/LICENSE b/LICENSE index 261eeb9..a3d69de 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright [2024] [The Open Lane, Inc.] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index 19c1ee7..46e6c8a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,65 @@ -# iam -identity and access management tooling and wrappers + helpers +[![Build status](https://badge.buildkite.com/3346f9d3732a143a78c4da3eb9dcb8f4e9616a64bebd0cbfbd.svg)](https://buildkite.com/theopenlane/iam) +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=theopenlane_iam&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=theopenlane_iam) +[![Go Report Card](https://goreportcard.com/badge/github.com/theopenlane/iam)](https://goreportcard.com/report/github.com/theopenlane/iam) +[![Go Reference](https://pkg.go.dev/badge/github.com/theopenlane/iam.svg)](https://pkg.go.dev/github.com/theopenlane/iam) +[![License: Apache 2.0](https://img.shields.io/badge/License-Apache2.0-brightgreen.svg)](https://opensource.org/licenses/Apache-2.0) + +# Identity and Access Management (IAM) + +A go library for interacting with [OpenFGA](https://openfga.dev/) - it is comprised of 2 packages, `fgax` and `entfga`. +- fgax: wrapper to interact with the [OpenFGA go-sdk](https://github.com/openfga/go-sdk) and client libraries +- entfga: an [ent extension](https://entgo.io/docs/extensions/) to create relationship tuples using [ent Hooks](https://entgo.io/docs/hooks/) + +## install + +You can install `fgax` by running the following command: + +```shell +go get github.com/theopenlane/fgax@latest +``` + +## fgax + +This package includes helper functions used heavily in [OpenLane](https://github.com/theopenlane/OpenLane/). + +For example, you can easily check for `Read` access of an organization using + +```go + // create client + fgaClient, err := fgax.Client("https://fga-host.example.com") + if err != nil { + return false + } + + // create access check + req := fgax.AccessCheck{ + SubjectID: "user-id", + SubjectType: "user", + ObjectID: "organization-id", + } + + allow, err := fgaClient.CheckOrgReadAccess(ctx, req) + if err != nil { + return false + } +``` + +## entfga + +See the [README](./entfga/README.md) for details + +## Contributing + +Please read the [contributing](.github/CONTRIBUTING.md) guide as well as the [Developer Certificate of Origin](https://developercertificate.org/). You will be required to sign all commits to the OpenLane project, so if you're unfamiliar with how to set that up, see [github's documentation](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification). + +## Security + +We take the security of our software products and services seriously, including all of the open source code repositories managed through our Github Organizations, such as [theopenlane](https://github.com/theopenlane). If you believe you have found a security vulnerability in any of our repositories, please report it to us through coordinated disclosure. + +**Please do NOT report security vulnerabilities through public github issues, discussions, or pull requests!** + +Instead, please send an email to `security@OpenLane.net` with as much information as possible to best help us understand and resolve the issues. See the security policy attached to this repository for more details. + +## Questions? + +Open a github issue on this repository and we'll respond as soon as we're able! diff --git a/Taskfile.yaml b/Taskfile.yaml new file mode 100644 index 0000000..caea403 --- /dev/null +++ b/Taskfile.yaml @@ -0,0 +1,56 @@ +version: '3' + +includes: + example: + taskfile: ./entfga/_examples/basic/ + dir: ./entfga/_examples/basic/ + +tasks: + generate: + desc: generate the mock fga client + cmds: + - go generate ./... + + go:lint: + desc: runs golangci-lint, the most annoying opinionated linter ever + cmds: + - golangci-lint run --config=.golangci.yaml --verbose --fix + + go:test: + desc: runs and outputs results of created go tests + cmds: + - go test -v ./... + + go:tidy: + desc: runs go mod tidy on the backend + aliases: [tidy] + cmds: + - go mod tidy + + go:all: + aliases: [go] + desc: runs all go test and lint related tasks + cmds: + - task: go:tidy + - task: go:lint + - task: go:test + + ci: + desc: a task that runs during CI + cmds: + - task: generate + - "git config --global --add safe.directory /workdir" + - | + status=$(git status --porcelain) + if [ -n "$status" ]; then + echo "detected git diff after running generate; please re-run tasks" + echo "$status" + exit 1 + fi + + precommit-full: + desc: Lint the project against all files + cmds: + - pre-commit install && pre-commit install-hooks + - pre-commit autoupdate + - pre-commit run --show-diff-on-failure --color=always --all-files diff --git a/auth/auth.go b/auth/auth.go new file mode 100644 index 0000000..ac31776 --- /dev/null +++ b/auth/auth.go @@ -0,0 +1,130 @@ +package auth + +import ( + "context" + "net/http" + "regexp" + "time" + + echo "github.com/theopenlane/echox" + + "github.com/theopenlane/iam/sessions" +) + +const ( + // Authorization is the key used in HTTP headers or cookies to represent the authorization token + Authorization = "Authorization" + // AccessTokenCookie is the key used in cookies to represent the access token + AccessTokenCookie = "access_token" + // RefreshTokenCookie is the key used in cookies to represent the refresh token + RefreshTokenCookie = "refresh_token" +) + +// used to extract the access token from the header +var ( + bearer = regexp.MustCompile(`^\s*[Bb]earer\s+([a-zA-Z0-9_\-\.]+)\s*$`) +) + +// GetAccessToken retrieves the bearer token from the authorization header and parses it +// to return only the JWT access token component of the header. Alternatively, if the +// authorization header is not present, then the token is fetched from cookies. If the +// header is missing or the token is not available, an error is returned. +// +// NOTE: the authorization header takes precedence over access tokens in cookies. +func GetAccessToken(c echo.Context) (string, error) { + // Attempt to get the access token from the header. + if h := c.Request().Header.Get(Authorization); h != "" { + match := bearer.FindStringSubmatch(h) + if len(match) == 2 { //nolint:mnd + return match[1], nil + } + + return "", ErrParseBearer + } + + // Attempt to get the access token from cookies. + if cookie, err := c.Cookie(AccessTokenCookie); err == nil { + // If the error is nil, that means we were able to retrieve the access token cookie + if CookieExpired(cookie) { + return "", ErrNoAuthorization + } + + return cookie.Value, nil + } + + return "", ErrNoAuthorization +} + +// GetRefreshToken retrieves the refresh token from the cookies in the request. If the +// cookie is not present or expired then an error is returned. +func GetRefreshToken(c echo.Context) (string, error) { + cookie, err := c.Cookie(RefreshTokenCookie) + if err != nil { + return "", ErrNoRefreshToken + } + + // ensure cookie is not expired + if CookieExpired(cookie) { + return "", ErrNoRefreshToken + } + + return cookie.Value, nil +} + +// AuthContextFromRequest creates a context from the echo request context, copying fields +// that may be required for forwarded requests. This method should be called by +// handlers which need to forward requests to other services and need to preserve data +// from the original request such as the user's credentials. +func AuthContextFromRequest(c echo.Context) (*context.Context, error) { + req := c.Request() + if req == nil { + return nil, ErrNoRequest + } + + // Add access token to context (from either header or cookie using Authenticate middleware) + ctx := req.Context() + if token := c.Get(ContextAccessToken.name); token != "" { + ctx = context.WithValue(ctx, ContextAccessToken, token) + } + + // Add request id to context + if requestID := c.Get(ContextRequestID.name); requestID != "" { + ctx = context.WithValue(ctx, ContextRequestID, requestID) + } else if requestID := c.Request().Header.Get("X-Request-ID"); requestID != "" { + ctx = context.WithValue(ctx, ContextRequestID, requestID) + } + + return &ctx, nil +} + +// SetAuthCookies is a helper function to set authentication cookies on a echo request. +// The access token cookie (access_token) is an http only cookie that expires when the +// access token expires. The refresh token cookie is not an http only cookie (it can be +// accessed by client-side scripts) and it expires when the refresh token expires. Both +// cookies require https and will not be set (silently) over http connections. +func SetAuthCookies(w http.ResponseWriter, accessToken, refreshToken string, c sessions.CookieConfig) { + sessions.SetCookie(w, accessToken, AccessTokenCookie, c) + sessions.SetCookie(w, refreshToken, RefreshTokenCookie, c) +} + +// ClearAuthCookies is a helper function to clear authentication cookies on a echo +// request to effectively logger out a user. +func ClearAuthCookies(w http.ResponseWriter) { + sessions.RemoveCookie(w, AccessTokenCookie, *sessions.DefaultCookieConfig) + sessions.RemoveCookie(w, RefreshTokenCookie, *sessions.DefaultCookieConfig) +} + +// CookieExpired checks to see if a cookie is expired +func CookieExpired(cookie *http.Cookie) bool { + // ensure cookie is not expired + if !cookie.Expires.IsZero() && cookie.Expires.Before(time.Now()) { + return true + } + + // negative max age means to expire immediately + if cookie.MaxAge < 0 { + return true + } + + return false +} diff --git a/auth/auth_test.go b/auth/auth_test.go new file mode 100644 index 0000000..a9bd590 --- /dev/null +++ b/auth/auth_test.go @@ -0,0 +1,321 @@ +package auth_test + +import ( + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + echo "github.com/theopenlane/echox" + + "github.com/theopenlane/iam/auth" + "github.com/theopenlane/iam/sessions" +) + +var happy = "happy path" + +func TestGetAccessToken(t *testing.T) { + testAccessToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZGF0dW0ubmV0IiwiYXVkIjoiaHR0cHM6Ly9kYXR1bS5uZXQiLCJzdWIiOiJVMVdNNHVGLTNxcGRsLWRtS0lISjQiLCJpYXQiOjE0NTg3ODU3OTYsImV4cCI6MTQ1ODg3MjE5Nn0.oXIjG4PauoHXEmZRDKRE018bkMv9rdZTjn563ujUh6o" // nolint:gosec + + var bear = "Bearer %s" + + tests := []struct { + name string + headerKey string + headerValue string + cookie *http.Cookie + wantTks string + wantErr bool + err error + }{ + { + name: "happy path from header", + headerKey: auth.Authorization, + headerValue: fmt.Sprintf(bear, testAccessToken), + wantTks: testAccessToken, + wantErr: false, + err: nil, + }, + { + name: "happy path from cookie", + headerKey: "", + headerValue: "", + cookie: &http.Cookie{ + Name: auth.AccessTokenCookie, + Value: testAccessToken, + }, + wantTks: testAccessToken, + wantErr: false, + err: nil, + }, + { + name: "happy path cookie and header set", + headerKey: auth.Authorization, + headerValue: fmt.Sprintf(bear, testAccessToken), + cookie: &http.Cookie{ + Name: auth.AccessTokenCookie, + Value: "access_token_from_cookie", // to confirm we get the one from the header, this will be a different value + }, + wantTks: testAccessToken, + wantErr: false, + err: nil, + }, + { + name: "no authorization header", + headerKey: "Hackorz", + headerValue: fmt.Sprintf(bear, testAccessToken), + wantTks: "", + wantErr: true, + err: auth.ErrNoAuthorization, + }, + { + name: "no bearer", + headerKey: auth.Authorization, + headerValue: fmt.Sprintf("Bear %s", testAccessToken), + wantTks: "", + wantErr: true, + err: auth.ErrParseBearer, + }, + { + name: "bearer not spaced", + headerKey: auth.Authorization, + headerValue: fmt.Sprintf("Bearer%s", testAccessToken), + wantTks: "", + wantErr: true, + err: auth.ErrParseBearer, + }, + { + name: "cookie set, but no access token cookie", + headerKey: "", + headerValue: "", + cookie: &http.Cookie{ + Name: "not_an_access_token", + Value: testAccessToken, + }, + wantTks: "", + wantErr: true, + err: auth.ErrNoAuthorization, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + e := echo.New() + + req := &http.Request{ + Header: http.Header{}, + } + + // Add header/cookies + req.Header.Add(tc.headerKey, tc.headerValue) + + if tc.cookie != nil { + req.AddCookie(tc.cookie) + } + + recorder := httptest.NewRecorder() + res := &echo.Response{ + Writer: recorder, + } + + ctx := e.NewContext(req, res) + + gotTks, err := auth.GetAccessToken(ctx) + if tc.wantErr { + assert.Error(t, err) + assert.Equal(t, tc.err, err) + assert.Empty(t, gotTks) + + return + } + + require.NoError(t, err) + assert.Equal(t, tc.wantTks, gotTks) + }) + } +} + +func TestGetRefreshToken(t *testing.T) { + testRefreshToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZGF0dW0ubmV0IiwiYXVkIjoiaHR0cHM6Ly9kYXR1bS5uZXQiLCJzdWIiOiJVMVdNNHVGLTNxcGRsLWRtS0lISjQiLCJpYXQiOjE0NTg3ODU3OTYsImV4cCI6MTQ1ODg3MjE5Nn0.oXIjG4PauoHXEmZRDKRE018bkMv9rdZTjn563ujUh6o" //nolint:gosec + tests := []struct { + name string + cookie *http.Cookie + wantTks string + wantErr bool + err error + }{ + + { + name: "happy path from cookie", + cookie: &http.Cookie{ + Name: auth.RefreshTokenCookie, + Value: testRefreshToken, + }, + wantTks: testRefreshToken, + wantErr: false, + err: nil, + }, + { + name: "no cookie", + wantTks: "", + wantErr: true, + err: auth.ErrNoRefreshToken, + }, + { + name: "cookie present, but no refresh cookie", + cookie: &http.Cookie{ + Name: "another_cookie", + Value: testRefreshToken, + }, + wantTks: "", + wantErr: true, + err: auth.ErrNoRefreshToken, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + e := echo.New() + + req := &http.Request{ + Header: http.Header{}, + } + + // Add cookies + if tc.cookie != nil { + req.AddCookie(tc.cookie) + } + + recorder := httptest.NewRecorder() + res := &echo.Response{ + Writer: recorder, + } + + ctx := e.NewContext(req, res) + + gotTks, err := auth.GetRefreshToken(ctx) + if tc.wantErr { + assert.Error(t, err) + assert.Equal(t, tc.err, err) + assert.Empty(t, gotTks) + + return + } + + require.NoError(t, err) + assert.Equal(t, tc.wantTks, gotTks) + }) + } +} + +func TestSetAuthCookies(t *testing.T) { + validCtx, err := auth.NewTestEchoContextWithValidUser("funks") + if err != nil { + t.Fatal() + } + + testAccessToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZGF0dW0ubmV0IiwiYXVkIjoiaHR0cHM6Ly9kYXR1bS5uZXQiLCJzdWIiOiJVMVdNNHVGLTNxcGRsLWRtS0lISjQiLCJpYXQiOjE3MDE5ODc2NDYsImV4cCI6MzMyNTg4OTY0NDZ9.y51S2D9qMHLRixj230YZbvQZyhWzDOQ2RPbyJmnEYXA" //nolint:gosec + testRefreshToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZGF0dW0ubmV0IiwiYXVkIjoiaHR0cHM6Ly9kYXR1bS5uZXQiLCJzdWIiOiJVMVdNNHVGLTNxcGRsLWRtS0lISjQiLCJpYXQiOjE3MDE5ODc2NDYsImV4cCI6MzMyNTg4OTY0NDZ9.y51S2D9qMHLRixj230YZbvQZyhWzDOQ2RPbyJmnEYXA" //nolint:gosec + + tests := []struct { + name string + ctx echo.Context + accessToken string + refreshToken string + }{ + + { + name: happy, + ctx: validCtx, + accessToken: testAccessToken, + refreshToken: testRefreshToken, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + auth.SetAuthCookies(tc.ctx.Response().Writer, tc.accessToken, tc.refreshToken, *sessions.DebugCookieConfig) + }) + } +} + +func TestClearAuthCookies(t *testing.T) { + validCtx, err := auth.NewTestEchoContextWithValidUser("funks") + if err != nil { + t.Fatal() + } + + tests := []struct { + name string + ctx echo.Context + accessToken string + refreshToken string + wantErr bool + err error + }{ + + { + name: happy, + ctx: validCtx, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + auth.ClearAuthCookies(tc.ctx.Response().Writer) + }) + } +} + +func TestCookieExpired(t *testing.T) { + tests := []struct { + name string + cookie *http.Cookie + want bool + }{ + { + name: "expired cookie based on expires", + cookie: &http.Cookie{ + Name: auth.AccessTokenCookie, + Value: "access_token_from_cookie", + Expires: time.Now().Add(-1 * time.Minute), + }, + want: true, + }, + { + name: "expired cookie based on max age", + cookie: &http.Cookie{ + Name: auth.AccessTokenCookie, + Value: "access_token_from_cookie", + MaxAge: -1, + }, + want: true, + }, + { + name: "not expired", + cookie: &http.Cookie{ + Name: auth.AccessTokenCookie, + Value: "access_token_from_cookie", + MaxAge: 3600, + }, + want: false, + }, + { + name: "not expired", + cookie: &http.Cookie{ + Name: auth.AccessTokenCookie, + Value: "access_token_from_cookie", + Expires: time.Now().Add(10 * time.Minute), + }, + want: false, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := auth.CookieExpired(tc.cookie) + assert.Equal(t, tc.want, got) + }) + } +} diff --git a/auth/context.go b/auth/context.go new file mode 100644 index 0000000..b440935 --- /dev/null +++ b/auth/context.go @@ -0,0 +1,350 @@ +package auth + +import ( + "context" + + echo "github.com/theopenlane/echox" + + "github.com/theopenlane/core/pkg/middleware/echocontext" + "github.com/theopenlane/utils/ulids" +) + +type AuthenticationType string + +const ( + // JWTAuthentication is the authentication type for JWT tokens + JWTAuthentication AuthenticationType = "jwt" + // PATAuthentication is the authentication type for personal access tokens + PATAuthentication AuthenticationType = "pat" + // APITokenAuthentication is the authentication type for API tokens + APITokenAuthentication AuthenticationType = "api_token" +) + +// ContextAuthenticatedUser is the context key for the user claims +var ContextAuthenticatedUser = &ContextKey{"authenticated_user"} + +// ContextAccessToken is the context key for the access token +var ContextAccessToken = &ContextKey{"access_token"} + +// ContextAccessToken is the context key for the access token +var ContextRefreshToken = &ContextKey{"refresh_token"} + +// ContextRequestID is the context key for the request ID +var ContextRequestID = &ContextKey{"request_id"} + +// ContextKey is the key name for the additional context +type ContextKey struct { + name string +} + +// AuthenticatedUser contains the user and organization ID for the authenticated user +type AuthenticatedUser struct { + // SubjectID is the user ID of the authenticated user or the api token ID if the user is an API token + SubjectID string + // SubjectName is the name of the authenticated user + SubjectName string + // OrganizationID is the organization ID of the authenticated user + OrganizationID string + // OrganizationName is the name of the organization the user is authenticated to + OrganizationName string + // OrganizationIDs is the list of organization IDs the user is authorized to access + OrganizationIDs []string + // AuthenticationType is the type of authentication used to authenticate the user (JWT, PAT, API Token) + AuthenticationType AuthenticationType +} + +// GetContextName returns the name of the context key +func GetContextName(key *ContextKey) string { + return key.name +} + +// SetAuthenticatedUserContext sets the authenticated user context in the echo context +func SetAuthenticatedUserContext(c echo.Context, user *AuthenticatedUser) { + c.Set(ContextAuthenticatedUser.name, user) +} + +// GetAuthenticatedUserContext gets the authenticated user context +func GetAuthenticatedUserContext(c context.Context) (*AuthenticatedUser, error) { + ec, err := echocontext.EchoContextFromContext(c) + if err != nil { + return nil, err + } + + result := ec.Get(ContextAuthenticatedUser.name) + + au, ok := result.(*AuthenticatedUser) + if !ok { + return nil, ErrNoAuthUser + } + + return au, nil +} + +// AddAuthenticatedUserContext adds the authenticated user context and returns the context +func AddAuthenticatedUserContext(c echo.Context, user *AuthenticatedUser) context.Context { + c.Set(ContextAuthenticatedUser.name, user) + + ctx := context.WithValue(c.Request().Context(), echocontext.EchoContextKey, c) + + c.SetRequest(c.Request().WithContext(ctx)) + + return ctx +} + +// GetAuthTypeFromEchoContext retrieves the authentication type from the echo context +func GetAuthTypeFromEchoContext(c echo.Context) AuthenticationType { + if v := c.Get(ContextAuthenticatedUser.name); v != nil { + a, ok := v.(*AuthenticatedUser) + if ok { + return a.AuthenticationType + } + } + + return "" +} + +// getSubjectIDFromEchoContext retrieves the subject ID from the echo context +func getSubjectIDFromEchoContext(c echo.Context) (string, error) { + if v := c.Get(ContextAuthenticatedUser.name); v != nil { + a, ok := v.(*AuthenticatedUser) + if !ok { + return "", ErrNoAuthUser + } + + uid, err := ulids.Parse(a.SubjectID) + if err != nil { + return "", err + } + + if ulids.IsZero(uid) { + return "", ErrNoAuthUser + } + + return a.SubjectID, nil + } + + return "", ErrNoAuthUser +} + +// getSubjectNameFromEchoContext retrieves the subject name from the echo context +func getSubjectNameFromEchoContext(c echo.Context) (string, error) { + if v := c.Get(ContextAuthenticatedUser.name); v != nil { + a, ok := v.(*AuthenticatedUser) + if !ok { + return "", ErrNoAuthUser + } + + return a.SubjectName, nil + } + + return "", ErrNoAuthUser +} + +// getOrganizationIDFromEchoContext returns the organization ID from the echo context +func getOrganizationIDFromEchoContext(c echo.Context) (string, error) { + if v := c.Get(ContextAuthenticatedUser.name); v != nil { + a, ok := v.(*AuthenticatedUser) + if !ok { + return "", ErrNoAuthUser + } + + oID, err := ulids.Parse(a.OrganizationID) + if err != nil { + return "", err + } + + if ulids.IsZero(oID) { + return "", ErrNoAuthUser + } + + return a.OrganizationID, nil + } + + return "", ErrNoAuthUser +} + +// getOrganizationIDsFromEchoContext returns the list of organization IDs from the echo context +func getOrganizationIDsFromEchoContext(c echo.Context) ([]string, error) { + if v := c.Get(ContextAuthenticatedUser.name); v != nil { + a, ok := v.(*AuthenticatedUser) + if !ok { + return []string{}, ErrNoAuthUser + } + + return a.OrganizationIDs, nil + } + + return []string{}, ErrNoAuthUser +} + +// getOrganizationNameFromEchoContext returns the organization name from the echo context +func getOrganizationNameFromEchoContext(c echo.Context) (string, error) { + if v := c.Get(ContextAuthenticatedUser.name); v != nil { + a, ok := v.(*AuthenticatedUser) + if !ok { + return "", ErrNoAuthUser + } + + return a.OrganizationName, nil + } + + return "", ErrNoAuthUser +} + +// GetOrganizationIDFromContext returns the organization ID from context +func GetOrganizationIDFromContext(ctx context.Context) (string, error) { + ec, err := echocontext.EchoContextFromContext(ctx) + if err != nil { + return "", err + } + + return getOrganizationIDFromEchoContext(ec) +} + +// GetOrganizationNameFromContext returns the organization name from context +func GetOrganizationNameFromContext(ctx context.Context) (string, error) { + ec, err := echocontext.EchoContextFromContext(ctx) + if err != nil { + return "", err + } + + return getOrganizationNameFromEchoContext(ec) +} + +// GetOrganizationIDsFromContext returns the list of organization IDs from context +func GetOrganizationIDsFromContext(ctx context.Context) ([]string, error) { + ec, err := echocontext.EchoContextFromContext(ctx) + if err != nil { + return []string{}, err + } + + return getOrganizationIDsFromEchoContext(ec) +} + +// GetUserIDFromContext returns the actor subject from the context +func GetUserIDFromContext(ctx context.Context) (string, error) { + ec, err := echocontext.EchoContextFromContext(ctx) + if err != nil { + return "", err + } + + return getSubjectIDFromEchoContext(ec) +} + +// GetUserNameFromContext returns the actor name from the context +func GetUserNameFromContext(ctx context.Context) (string, error) { + ec, err := echocontext.EchoContextFromContext(ctx) + if err != nil { + return "", err + } + + return getSubjectNameFromEchoContext(ec) +} + +// GetAuthTypeFromEchoContext retrieves the authentication type from the context +func GetAuthTypeFromContext(ctx context.Context) AuthenticationType { + ec, err := echocontext.EchoContextFromContext(ctx) + if err != nil { + return "" + } + + return GetAuthTypeFromEchoContext(ec) +} + +func IsAPITokenAuthentication(ctx context.Context) bool { + return GetAuthTypeFromContext(ctx) == APITokenAuthentication +} + +const ( + // UserSubjectType is the subject type for user accounts + UserSubjectType = "user" + // ServiceSubjectType is the subject type for service accounts + ServiceSubjectType = "service" +) + +// GetAuthzSubjectType returns the subject type based on the authentication type +func GetAuthzSubjectType(ctx context.Context) string { + subjectType := UserSubjectType + + authType := GetAuthTypeFromContext(ctx) + if authType == APITokenAuthentication { + subjectType = ServiceSubjectType + } + + return subjectType +} + +// AddOrganizationIDToContext appends an authorized organization ID to the context. +// This generally should not be used, as the authorized organization should be +// determined by the claims or the token. This is only used in cases where the +// a user is newly authorized to an organization and the organization ID is not +// in the token claims +func AddOrganizationIDToContext(ctx context.Context, orgID string) error { + ec, err := echocontext.EchoContextFromContext(ctx) + if err != nil { + return err + } + + return addOrganizationIDsToEchoContext(ec, orgID) +} + +// getOrganizationIDsFromEchoContext appends an authorized organization ID to the echo context +func addOrganizationIDsToEchoContext(c echo.Context, orgID string) error { + if v := c.Get(ContextAuthenticatedUser.name); v != nil { + a, ok := v.(*AuthenticatedUser) + if !ok { + return ErrNoAuthUser + } + + // append the organization ID to the list of organization IDs + a.OrganizationIDs = append(a.OrganizationIDs, orgID) + + return nil + } + + return ErrNoAuthUser +} + +// SetRefreshTokenContext sets the refresh token context in the echo context +func SetRefreshTokenContext(c echo.Context, token string) { + c.Set(ContextRefreshToken.name, token) +} + +// SetAccessTokenContext sets the access token context in the echo context +func SetAccessTokenContext(c echo.Context, token string) { + c.Set(ContextAccessToken.name, token) +} + +// GetAccessTokenContext gets the authenticated user context +func GetAccessTokenContext(c context.Context) (string, error) { + ec, err := echocontext.EchoContextFromContext(c) + if err != nil { + return "", err + } + + result := ec.Get(ContextAccessToken.name) + + token, ok := result.(string) + if !ok { + return "", ErrNoAuthUser + } + + return token, nil +} + +// GetRefreshTokenContext gets the authenticated user context +func GetRefreshTokenContext(c context.Context) (string, error) { + ec, err := echocontext.EchoContextFromContext(c) + if err != nil { + return "", err + } + + result := ec.Get(ContextRefreshToken.name) + + token, ok := result.(string) + if !ok { + return "", ErrNoAuthUser + } + + return token, nil +} diff --git a/auth/context_test.go b/auth/context_test.go new file mode 100644 index 0000000..ad88552 --- /dev/null +++ b/auth/context_test.go @@ -0,0 +1,131 @@ +package auth_test + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/theopenlane/core/pkg/middleware/echocontext" + "github.com/theopenlane/utils/ulids" + + "github.com/theopenlane/iam/auth" +) + +func TestGetSubjectIDFromContext(t *testing.T) { + // context with no user set + ec := echocontext.NewTestEchoContext() + + basicContext := context.WithValue(ec.Request().Context(), echocontext.EchoContextKey, ec) + + ec.SetRequest(ec.Request().WithContext(basicContext)) + + sub := ulids.New().String() + + validCtx, err := auth.NewTestContextWithValidUser(sub) + if err != nil { + t.Fatal() + } + + invalidUserCtx, err := auth.NewTestContextWithValidUser(ulids.Null.String()) + if err != nil { + t.Fatal() + } + + testCases := []struct { + name string + ctx context.Context + err error + }{ + { + name: "happy path", + ctx: validCtx, + err: nil, + }, + { + name: "no user", + ctx: basicContext, + err: auth.ErrNoAuthUser, + }, + { + name: "null user", + ctx: invalidUserCtx, + err: auth.ErrNoAuthUser, + }, + } + + for _, tc := range testCases { + t.Run("Get "+tc.name, func(t *testing.T) { + got, err := auth.GetUserIDFromContext(tc.ctx) + if tc.err != nil { + assert.Error(t, err) + assert.Empty(t, got) + assert.ErrorContains(t, err, tc.err.Error()) + + return + } + + assert.NoError(t, err) + assert.Equal(t, sub, got) + }) + } +} + +func TestGetOrganizationIDFromContext(t *testing.T) { + // context with no user set + ec := echocontext.NewTestEchoContext() + + basicContext := context.WithValue(ec.Request().Context(), echocontext.EchoContextKey, ec) + + ec.SetRequest(ec.Request().WithContext(basicContext)) + + orgID := ulids.New().String() + + validCtx, err := auth.NewTestContextWithOrgID(ulids.New().String(), orgID) + if err != nil { + t.Fatal() + } + + invalidUserCtx, err := auth.NewTestContextWithOrgID(ulids.Null.String(), ulids.Null.String()) + if err != nil { + t.Fatal() + } + + testCases := []struct { + name string + ctx context.Context + err error + }{ + { + name: "happy path", + ctx: validCtx, + err: nil, + }, + { + name: "no user", + ctx: basicContext, + err: auth.ErrNoAuthUser, + }, + { + name: "null user", + ctx: invalidUserCtx, + err: auth.ErrNoAuthUser, + }, + } + + for _, tc := range testCases { + t.Run("Get "+tc.name, func(t *testing.T) { + got, err := auth.GetOrganizationIDFromContext(tc.ctx) + if tc.err != nil { + assert.Error(t, err) + assert.Empty(t, got) + assert.ErrorContains(t, err, tc.err.Error()) + + return + } + + assert.NoError(t, err) + assert.Equal(t, orgID, got) + }) + } +} diff --git a/auth/doc.go b/auth/doc.go new file mode 100644 index 0000000..cab6146 --- /dev/null +++ b/auth/doc.go @@ -0,0 +1,2 @@ +// Package auth handles auth +package auth diff --git a/auth/errors.go b/auth/errors.go new file mode 100644 index 0000000..998d721 --- /dev/null +++ b/auth/errors.go @@ -0,0 +1,40 @@ +package auth + +import ( + "errors" +) + +var ( + // ErrNoClaims is returned when no claims are found on the request context + ErrNoClaims = errors.New("no claims found on the request context") + + // ErrNoUserInfo is returned when no user info is found on the request context + ErrNoUserInfo = errors.New("no user info found on the request context") + + // ErrNoAuthUser is returned when no authenticated user is found on the request context + ErrNoAuthUser = errors.New("could not identify authenticated user in request") + + // ErrUnverifiedUser is returned when the user is not verified + ErrUnverifiedUser = errors.New("user is not verified") + + // ErrParseBearer is returned when the bearer token could not be parsed from the authorization header + ErrParseBearer = errors.New("could not parse bearer token from authorization header") + + // ErrNoAuthorization is returned when no authorization header is found in the request + ErrNoAuthorization = errors.New("no authorization header in request") + + // ErrNoRequest is returned when no request is found on the context + ErrNoRequest = errors.New("no request found on the context") + + // ErrNoRefreshToken is returned when no refresh token is found on the request + ErrNoRefreshToken = errors.New("no refresh token available on request") + + // ErrRefreshDisabled is returned when re-authentication with refresh tokens is disabled + ErrRefreshDisabled = errors.New("re-authentication with refresh tokens disabled") + + // ErrUnableToConstructValidator is returned when the validator cannot be constructed + ErrUnableToConstructValidator = errors.New("unable to construct validator") + + // ErrPasswordTooWeak is returned when the password is too weak + ErrPasswordTooWeak = errors.New("password is too weak: use a combination of upper and lower case letters, numbers, and special characters") +) diff --git a/auth/test_tools.go b/auth/test_tools.go new file mode 100644 index 0000000..58699a3 --- /dev/null +++ b/auth/test_tools.go @@ -0,0 +1,112 @@ +package auth + +import ( + "context" + "time" + + "github.com/golang-jwt/jwt/v5" + echo "github.com/theopenlane/echox" + + "github.com/theopenlane/core/pkg/middleware/echocontext" + "github.com/theopenlane/core/pkg/tokens" +) + +// newValidClaims returns claims with a fake subject for testing purposes ONLY +func newValidClaims(subject string) *tokens.Claims { + iat := time.Now() + nbf := iat + exp := time.Now().Add(time.Hour) + + claims := &tokens.Claims{ + RegisteredClaims: jwt.RegisteredClaims{ + Subject: subject, + Issuer: "test suite", + IssuedAt: jwt.NewNumericDate(iat), + NotBefore: jwt.NewNumericDate(nbf), + ExpiresAt: jwt.NewNumericDate(exp), + }, + UserID: subject, + OrgID: "ulid_id_of_org", + } + + return claims +} + +// NewTestEchoContextWithValidUser creates an echo context with a fake subject for testing purposes ONLY +func NewTestEchoContextWithValidUser(subject string) (echo.Context, error) { + ec := echocontext.NewTestEchoContext() + + claims := newValidClaims(subject) + + SetAuthenticatedUserContext(ec, &AuthenticatedUser{ + SubjectID: claims.UserID, + OrganizationID: claims.OrgID, + OrganizationIDs: []string{claims.OrgID}, + AuthenticationType: "jwt", + }) + + return ec, nil +} + +func NewTestContextWithValidUser(subject string) (context.Context, error) { + ec, err := NewTestEchoContextWithValidUser(subject) + if err != nil { + return nil, err + } + + reqCtx := context.WithValue(ec.Request().Context(), echocontext.EchoContextKey, ec) + + ec.SetRequest(ec.Request().WithContext(reqCtx)) + + return reqCtx, nil +} + +// newValidClaims returns claims with a fake orgID for testing purposes ONLY +func newValidClaimsOrgID(sub, orgID string) *tokens.Claims { + iat := time.Now() + nbf := iat + exp := time.Now().Add(time.Hour) + + claims := &tokens.Claims{ + RegisteredClaims: jwt.RegisteredClaims{ + Subject: sub, + Issuer: "test suite", + IssuedAt: jwt.NewNumericDate(iat), + NotBefore: jwt.NewNumericDate(nbf), + ExpiresAt: jwt.NewNumericDate(exp), + }, + UserID: sub, + OrgID: orgID, + } + + return claims +} + +// NewTestEchoContextWithOrgID creates an echo context with a fake orgID for testing purposes ONLY +func NewTestEchoContextWithOrgID(sub, orgID string) (echo.Context, error) { + ec := echocontext.NewTestEchoContext() + + claims := newValidClaimsOrgID(sub, orgID) + + SetAuthenticatedUserContext(ec, &AuthenticatedUser{ + SubjectID: claims.UserID, + OrganizationID: claims.OrgID, + OrganizationIDs: []string{claims.OrgID}, + AuthenticationType: "jwt", + }) + + return ec, nil +} + +func NewTestContextWithOrgID(sub, orgID string) (context.Context, error) { + ec, err := NewTestEchoContextWithOrgID(sub, orgID) + if err != nil { + return nil, err + } + + reqCtx := context.WithValue(ec.Request().Context(), echocontext.EchoContextKey, ec) + + ec.SetRequest(ec.Request().WithContext(reqCtx)) + + return reqCtx, nil +} diff --git a/entfga/README.md b/entfga/README.md new file mode 100644 index 0000000..0b71649 --- /dev/null +++ b/entfga/README.md @@ -0,0 +1,157 @@ +# entfga + +`entfga` is an [ent extension](https://entgo.io/docs/extensions/) to create relationship tuples using [ent Hooks](https://entgo.io/docs/hooks/) + +## install + +You can install `entfga` by running the following command: + +```shell +go get github.com/theopenlane/iam/entfga@latest +``` + +In addition to installing `entfga`, you need to create two files in your `ent` directory: `entc.go` and `generate.go`. +The `entc.go` file should contain the following code: + +```go +//go:build ignore + +package main + +import ( + "log" + "github.com/theopenlane/iam/entfga" + "entgo.io/ent/entc" +) + +func main() { + // initialize the entfga extension + entfgaExt := entfga.New( + entfga.WithSoftDeletes(), + entfga.WithSchemaPath(schemaPath), + ) + + // generate authz checks if you are using ent policies + if err := entfgaExt.Config.GenerateAuthzChecks(); err != nil { + log.Fatalf("generating authz checks: %v", err) + } + + if err := entc.Generate("./schema", + &gen.Config{}, + entc.Extensions( + entfgaExt, + ), + ); err != nil { + log.Fatal("running ent codegen:", err) + } +} +``` + +The `generate.go` file should contain the following code: + +```go +package ent + +//go:generate go run -mod=mod entc.go +``` + +### Usage + +When creating the `*ent.Client` add the following to enable the authz hooks and policies: + +``` + client.WithAuthz() +``` + +The `privacy` feature **must** be turned on: + +``` + Features: []gen.Feature{gen.FeaturePrivacy}, +``` + +## Generate Hooks and Policies + +In the `ent` schema, provide the following annotation: + +```go +// Annotations of the OrgMembership +func (OrgMembership) Annotations() []schema.Annotation { + return []schema.Annotation{ + entfga.Annotations{ + ObjectType: "organization", + IncludeHooks: true, + IDField: "OrganizationID", // Defaults to ID, override to object ID field + }, + } +} +``` + +The `ObjectType` **must** be the same between the ID field name in the schema and the object type in the FGA relationship. In the example above +the field in the schema is `OrganizationID` and the object in FGA is `organization`. + +If the `ID` field is `Optional()`, you'll need to set `NillableIDField: true,` on the annotation to ensure the `string` value is used instead of the `pointer` on the `CreateInput`. + + +## Generate Policies Only + +In the `ent` schema, provide the following annotation: + +```go +// Annotations of the Organization +func (Organization) Annotations() []schema.Annotation { + return []schema.Annotation{ + entfga.Annotations{ + ObjectType: "organization", + IncludeHooks: false, + }, + } +} +``` + +## Using Policies + +A policy check function will be created per mutation and query type when the annotation is used, these can be set on the policy of the schema. +They must be wrapped in the `privacy` `MutationRuleFunc`, as seen the example below: + +```go +// Policy of the Organization +func (Organization) Policy() ent.Policy { + return privacy.Policy{ + Mutation: privacy.MutationPolicy{ + rule.DenyIfNoSubject(), + privacy.OrganizationMutationRuleFunc(func(ctx context.Context, m *generated.OrganizationMutation) error { + return m.CheckAccessForEdit(ctx) + }), + // Add a separate delete policy if permissions for delete of the object differ from normal edit permissions + privacy.OrganizationMutationRuleFunc(func(ctx context.Context, m *generated.OrganizationMutation) error { + return m.CheckAccessForDelete(ctx) + }), + privacy.AlwaysDenyRule(), + }, + Query: privacy.QueryPolicy{ + privacy.OrganizationQueryRuleFunc(func(ctx context.Context, q *generated.OrganizationQuery) error { + return q.CheckAccess(ctx) + }), + privacy.AlwaysDenyRule(), + }, + } +} +``` + +**NOTE**: These policies can only be added after an initial run of `entc` with the `Annotations`. This is what creates the `CheckAccess`, etc functions that are referenced in the policy above. + +## Contributing + +Please read the [contributing](.github/CONTRIBUTING.md) guide as well as the [Developer Certificate of Origin](https://developercertificate.org/). You will be required to sign all commits to the OpenLane project, so if you're unfamiliar with how to set that up, see [github's documentation](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification). + +## Security + +We take the security of our software products and services seriously, including all of the open source code repositories managed through our Github Organizations, such as [theopenlane](https://github.com/theopenlane). If you believe you have found a security vulnerability in any of our repositories, please report it to us through coordinated disclosure. + +**Please do NOT report security vulnerabilities through public github issues, discussions, or pull requests!** + +Instead, please send an email to `security@theopenlane.io` with as much information as possible to best help us understand and resolve the issues. See the security policy attached to this repository for more details. + +## Questions? + +Open a github issue on this repository and we'll respond as soon as we're able! diff --git a/entfga/_examples/basic/Taskfile.yaml b/entfga/_examples/basic/Taskfile.yaml new file mode 100644 index 0000000..d547066 --- /dev/null +++ b/entfga/_examples/basic/Taskfile.yaml @@ -0,0 +1,23 @@ +version: '3' + +tasks: + ## Generate tasks + ent: + desc: runs go generate against ent schema - see the entc.go file and generates the fga mock client + cmds: + - go mod tidy + - go generate ./... + + gqlgen: + desc: runs gqlgen and gqlgenc commands using gen_generate.go and entc + cmds: + - go mod tidy + - go run github.com/99designs/gqlgen generate --verbose + - go mod tidy + - go run ./gen_schema.go + + generate: + desc: a combination of the ent, graph, and gqlgen tasks which are required to fully generate the necessary graph, server, resolvers, client, etc. + cmds: + - task: ent + - task: gqlgen diff --git a/entfga/_examples/basic/auth/auth.go b/entfga/_examples/basic/auth/auth.go new file mode 100644 index 0000000..0bb6b0b --- /dev/null +++ b/entfga/_examples/basic/auth/auth.go @@ -0,0 +1,11 @@ +package auth + +import ( + "context" +) + +// GetUserIDFromContext is a placeholder function to get the user id from the context +// see implementation at https://github.com/theopenlane/core/blob/main/internal/httpserve/middleware/auth/user.go#L29 +func GetUserIDFromContext(ctx context.Context) (string, error) { + return "USERID", nil +} diff --git a/entfga/_examples/basic/ent/auth_from_mutation.go b/entfga/_examples/basic/ent/auth_from_mutation.go new file mode 100644 index 0000000..9db66e9 --- /dev/null +++ b/entfga/_examples/basic/ent/auth_from_mutation.go @@ -0,0 +1,151 @@ +// Code generated by entfga, DO NOT EDIT. + +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "github.com/theopenlane/iam/fgax" + "github.com/theopenlane/iam/entfga" +) + +func (m *OrgMembershipMutation) CreateTuplesFromCreate(ctx context.Context) error { + + // Get fields for tuple creation + userID, _ := m.UserID() + objectID, _ := m.OrganizationID() + role, _ := m.Role() + + // get tuple key + req := fgax.TupleRequest{ + SubjectID: userID, + SubjectType: "user", + ObjectID: objectID, + ObjectType: "organization", + Relation: role.String(), + } + tuple := fgax.GetTupleKey(req) + + if _, err := m.Authz.WriteTupleKeys(ctx, []fgax.TupleKey{tuple}, nil); err != nil { + m.Logger.Errorw("failed to create relationship tuple", "error", err) + + return err + } + + m.Logger.Debugw("created relationship tuples", "relation", role, "object", tuple.Object) + + return nil +} + +func (m *OrgMembershipMutation) CreateTuplesFromUpdate(ctx context.Context) error { + + // get ids that will be updated + ids, err := m.IDs(ctx) + if err != nil { + return err + } + + var ( + writes []fgax.TupleKey + deletes []fgax.TupleKey + ) + + oldRole, err := m.OldRole(ctx) + if err != nil { + return err + } + + newRole, exists := m.Role() + if !exists { + return entfga.ErrMissingRole + } + + if oldRole == newRole { + m.Logger.Debugw("nothing to update, roles are the same", "old_role", oldRole, "new_role", newRole) + + return nil + } + + // User the IDs of the memberships and delete all related tuples + for _, id := range ids { + member, err := m.Client().OrgMembership.Get(ctx, id) + if err != nil { + return err + } + + req := fgax.TupleRequest{ + SubjectID: member.UserID, + SubjectType: "user", + ObjectID: member.OrganizationID, + ObjectType: "organization", + Relation: oldRole.String(), + } + d := fgax.GetTupleKey(req) + + deletes = append(deletes, d) + + req.Relation = newRole.String() + w := fgax.GetTupleKey(req) + + writes = append(writes, w) + + if len(writes) == 0 && len(deletes) == 0 { + m.Logger.Debugw("no relationships to create or delete") + + return nil + } + + if _, err := m.Authz.WriteTupleKeys(ctx, writes, deletes); err != nil { + m.Logger.Errorw("failed to update relationship tuple", "error", err) + + return err + } + } + + return nil +} + +func (m *OrgMembershipMutation) CreateTuplesFromDelete(ctx context.Context) error { + + // get ids that will be deleted + ids, err := m.IDs(ctx) + if err != nil { + return err + } + + tuples := []fgax.TupleKey{} + + // User the IDs of the memberships and delete all related tuples + for _, id := range ids { + // this wont work with soft deletes + members, err := m.Client().OrgMembership.Get(ctx, id) + if err != nil { + return err + } + + req := fgax.TupleRequest{ + SubjectID: members.UserID, + SubjectType: "user", + ObjectID: members.OrganizationID, + ObjectType: "organization", + Relation: members.Role.String(), + } + t := fgax.GetTupleKey(req) + + tuples = append(tuples, t) + } + + if len(tuples) > 0 { + if _, err := m.Authz.WriteTupleKeys(ctx, nil, tuples); err != nil { + m.Logger.Errorw("failed to delete relationship tuple", "error", err) + + return err + } + + m.Logger.Debugw("deleted relationship tuples") + } + + return nil +} diff --git a/entfga/_examples/basic/ent/authz_checks.go b/entfga/_examples/basic/ent/authz_checks.go new file mode 100644 index 0000000..daf258f --- /dev/null +++ b/entfga/_examples/basic/ent/authz_checks.go @@ -0,0 +1,340 @@ +// Code generated by entfga, DO NOT EDIT. +package ent + +import ( + "context" + + "entgo.io/ent/privacy" + "github.com/99designs/gqlgen/graphql" + + "github.com/theopenlane/iam/auth" + "github.com/theopenlane/iam/fgax" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" +) + +func (q *OrgMembershipQuery) CheckAccess(ctx context.Context) error { + gCtx := graphql.GetFieldContext(ctx) + + if gCtx != nil { + ac := fgax.AccessCheck{ + Relation: fgax.CanView, + ObjectType: "organization", + SubjectType: auth.GetAuthzSubjectType(ctx), + } + + // check id from graphql arg context + // when all objects are requested, the interceptor will check object access + // check the where input first + whereArg := gCtx.Args["where"] + if whereArg != nil { + where, ok := whereArg.(*OrgMembershipWhereInput) + if ok && where != nil && where.OrganizationID != nil { + ac.ObjectID = *where.OrganizationID + } + } + + // if that doesn't work, check for the id in the args + if ac.ObjectID == "" { + ac.ObjectID, _ = gCtx.Args["organizationid"].(string) + } + + // if we still don't have an object id, run the query and grab the object ID + // from the result + // this happens on join tables where we have the join ID (for updates and deletes) + // and not the actual object id + if ac.ObjectID == "" && "id" != "organizationid" { + // allow this query to run + reqCtx := privacy.DecisionContext(ctx, privacy.Allow) + ob, err := q.Clone().Only(reqCtx) + if err != nil { + return privacy.Allowf("nil request, bypassing auth check") + } + ac.ObjectID = ob.OrganizationID + } + + // request is for a list objects, will get filtered in interceptors + if ac.ObjectID == "" { + return privacy.Allowf("nil request, bypassing auth check") + } + + var err error + ac.SubjectID, err = auth.GetUserIDFromContext(ctx) + if err != nil { + return err + } + + access, err := q.Authz.CheckAccess(ctx, ac) + if err != nil { + return privacy.Skipf("unable to check access, %s", err.Error()) + } + + if access { + return privacy.Allow + } + } + + // Skip to the next privacy rule (equivalent to return nil) + return privacy.Skip +} +func (m *OrgMembershipMutation) CheckAccessForEdit(ctx context.Context) error { + ac := fgax.AccessCheck{ + Relation: fgax.CanEdit, + ObjectType: "organization", + SubjectType: auth.GetAuthzSubjectType(ctx), + } + orgID, oErr := auth.GetOrganizationIDFromContext(ctx) + + // if we still don't have an object id, run the query and grab the object ID + // from the result + // this happens when using a personal access token since it is authorized for multiple orgs + if orgID == "" || oErr != nil { + id, _ := m.ID() + + if id != "" { + // allow this query to run + reqCtx := privacy.DecisionContext(ctx, privacy.Allow) + ob, err := m.Client().OrgMembership.Get(reqCtx, id) + if err != nil { + m.Logger.Debugw("error getting object", "error", err) + + return err + } + + orgID = ob.OrganizationID + } + } + + ac.ObjectID = orgID + + // request is for a list objects, will get filtered in interceptors + if ac.ObjectID == "" { + return privacy.Allowf("nil request, bypassing auth check") + } + + m.Logger.Debugw("checking mutation access") + + var err error + ac.SubjectID, err = auth.GetUserIDFromContext(ctx) + if err != nil { + return err + } + + m.Logger.Infow("checking relationship tuples", "relation", ac.Relation, "object_id", ac.ObjectID) + + access, err := m.Authz.CheckAccess(ctx, ac) + if err != nil { + return privacy.Skipf("unable to check access, %s", err.Error()) + } + + if access { + m.Logger.Debugw("access allowed", "relation", ac.Relation, "object_id", ac.ObjectID) + + return privacy.Allow + } + + // deny if it was a mutation is not allowed + return privacy.Deny +} + +func (m *OrgMembershipMutation) CheckAccessForDelete(ctx context.Context) error { + ac := fgax.AccessCheck{ + Relation: fgax.CanDelete, + ObjectType: "organization", + SubjectType: auth.GetAuthzSubjectType(ctx), + } + + gCtx := graphql.GetFieldContext(ctx) + + var ok bool + ac.ObjectID, ok = gCtx.Args["id"].(string) + if !ok { + return privacy.Allowf("nil request, bypassing auth check") + } + + m.Logger.Debugw("checking mutation access") + + var err error + ac.SubjectID, err = auth.GetUserIDFromContext(ctx) + if err != nil { + return err + } + + m.Logger.Infow("checking relationship tuples", "relation", ac.Relation, "object_id", ac.ObjectID) + + access, err := m.Authz.CheckAccess(ctx, ac) + if err != nil { + return privacy.Skipf("unable to check access, %s", err.Error()) + } + + if access { + m.Logger.Debugw("access allowed", "relation", ac.Relation, "object_id", ac.ObjectID) + + return privacy.Allow + } + + // deny if it was a mutation is not allowed + return privacy.Deny +} + +func (q *OrganizationQuery) CheckAccess(ctx context.Context) error { + gCtx := graphql.GetFieldContext(ctx) + + if gCtx != nil { + ac := fgax.AccessCheck{ + Relation: fgax.CanView, + ObjectType: "organization", + SubjectType: auth.GetAuthzSubjectType(ctx), + } + + // check id from graphql arg context + // when all objects are requested, the interceptor will check object access + // check the where input first + whereArg := gCtx.Args["where"] + if whereArg != nil { + where, ok := whereArg.(*OrganizationWhereInput) + if ok && where != nil && where.ID != nil { + ac.ObjectID = *where.ID + } + } + + // if that doesn't work, check for the id in the args + if ac.ObjectID == "" { + ac.ObjectID, _ = gCtx.Args["id"].(string) + } + + // if we still don't have an object id, run the query and grab the object ID + // from the result + // this happens on join tables where we have the join ID (for updates and deletes) + // and not the actual object id + if ac.ObjectID == "" && "id" != "id" { + // allow this query to run + reqCtx := privacy.DecisionContext(ctx, privacy.Allow) + ob, err := q.Clone().Only(reqCtx) + if err != nil { + return privacy.Allowf("nil request, bypassing auth check") + } + ac.ObjectID = ob.ID + } + + // request is for a list objects, will get filtered in interceptors + if ac.ObjectID == "" { + return privacy.Allowf("nil request, bypassing auth check") + } + + var err error + ac.SubjectID, err = auth.GetUserIDFromContext(ctx) + if err != nil { + return err + } + + access, err := q.Authz.CheckAccess(ctx, ac) + if err != nil { + return privacy.Skipf("unable to check access, %s", err.Error()) + } + + if access { + return privacy.Allow + } + } + + // Skip to the next privacy rule (equivalent to return nil) + return privacy.Skip +} +func (m *OrganizationMutation) CheckAccessForEdit(ctx context.Context) error { + ac := fgax.AccessCheck{ + Relation: fgax.CanEdit, + ObjectType: "organization", + SubjectType: auth.GetAuthzSubjectType(ctx), + } + + gCtx := graphql.GetFieldContext(ctx) + + // check the id from the args + if ac.ObjectID == "" { + ac.ObjectID, _ = gCtx.Args["id"].(string) + } + + // if this is still empty, we need to query the object to get the object id + // this happens on join tables where we have the join ID (for updates and deletes) + if ac.ObjectID == "" && "id" != "id" { + id, ok := gCtx.Args["id"].(string) + if ok { + // allow this query to run + reqCtx := privacy.DecisionContext(ctx, privacy.Allow) + ob, err := m.Client().Organization.Query().Where(organization.ID(id)).Only(reqCtx) + if err != nil { + return privacy.Skipf("nil request, skipping auth check") + } + ac.ObjectID = ob.ID + } + } + + // request is for a list objects, will get filtered in interceptors + if ac.ObjectID == "" { + return privacy.Allowf("nil request, bypassing auth check") + } + + m.Logger.Debugw("checking mutation access") + + var err error + ac.SubjectID, err = auth.GetUserIDFromContext(ctx) + if err != nil { + return err + } + + m.Logger.Infow("checking relationship tuples", "relation", ac.Relation, "object_id", ac.ObjectID) + + access, err := m.Authz.CheckAccess(ctx, ac) + if err != nil { + return privacy.Skipf("unable to check access, %s", err.Error()) + } + + if access { + m.Logger.Debugw("access allowed", "relation", ac.Relation, "object_id", ac.ObjectID) + + return privacy.Allow + } + + // deny if it was a mutation is not allowed + return privacy.Deny +} + +func (m *OrganizationMutation) CheckAccessForDelete(ctx context.Context) error { + ac := fgax.AccessCheck{ + Relation: fgax.CanDelete, + ObjectType: "organization", + SubjectType: auth.GetAuthzSubjectType(ctx), + } + + gCtx := graphql.GetFieldContext(ctx) + + var ok bool + ac.ObjectID, ok = gCtx.Args["id"].(string) + if !ok { + return privacy.Allowf("nil request, bypassing auth check") + } + + m.Logger.Debugw("checking mutation access") + + var err error + ac.SubjectID, err = auth.GetUserIDFromContext(ctx) + if err != nil { + return err + } + + m.Logger.Infow("checking relationship tuples", "relation", ac.Relation, "object_id", ac.ObjectID) + + access, err := m.Authz.CheckAccess(ctx, ac) + if err != nil { + return privacy.Skipf("unable to check access, %s", err.Error()) + } + + if access { + m.Logger.Debugw("access allowed", "relation", ac.Relation, "object_id", ac.ObjectID) + + return privacy.Allow + } + + // deny if it was a mutation is not allowed + return privacy.Deny +} diff --git a/entfga/_examples/basic/ent/client.go b/entfga/_examples/basic/ent/client.go new file mode 100644 index 0000000..bc9e3c0 --- /dev/null +++ b/entfga/_examples/basic/ent/client.go @@ -0,0 +1,538 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "github.com/theopenlane/iam/entfga" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/migrate" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/theopenlane/iam/fgax" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" + "go.uber.org/zap" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // OrgMembership is the client for interacting with the OrgMembership builders. + OrgMembership *OrgMembershipClient + // Organization is the client for interacting with the Organization builders. + Organization *OrganizationClient + + // authzActivated determines if the authz hooks have already been activated + authzActivated bool +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + client := &Client{config: cfg} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.OrgMembership = NewOrgMembershipClient(c.config) + c.Organization = NewOrganizationClient(c.config) +} + +// WithAuthz adds the authz hooks to the appropriate schemas - generated by entfga +func (c *Client) WithAuthz() { + if !c.authzActivated { + + for _, hook := range entfga.AuthzHooks[*OrgMembershipMutation]() { + c.OrgMembership.Use(hook) + } + + c.authzActivated = true + } +} + +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + Authz fgax.Client + Logger zap.SugaredLogger + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + +// Authz configures the Authz. +func Authz(v fgax.Client) Option { + return func(c *config) { + c.Authz = v + } +} + +// Logger configures the Logger. +func Logger(v zap.SugaredLogger) Option { + return func(c *config) { + c.Logger = v + } +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction") + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, ErrTxStarted + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + OrgMembership: NewOrgMembershipClient(cfg), + Organization: NewOrganizationClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + OrgMembership: NewOrgMembershipClient(cfg), + Organization: NewOrganizationClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// OrgMembership. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// Use adds the mutation hooks to all the entity clients. +// In order to add hooks to a specific client, call: `client.Node.Use(...)`. +func (c *Client) Use(hooks ...Hook) { + c.OrgMembership.Use(hooks...) + c.Organization.Use(hooks...) +} + +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + c.OrgMembership.Intercept(interceptors...) + c.Organization.Intercept(interceptors...) +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *OrgMembershipMutation: + return c.OrgMembership.mutate(ctx, m) + case *OrganizationMutation: + return c.Organization.mutate(ctx, m) + default: + return nil, fmt.Errorf("ent: unknown mutation type %T", m) + } +} + +// OrgMembershipClient is a client for the OrgMembership schema. +type OrgMembershipClient struct { + config +} + +// NewOrgMembershipClient returns a client for the OrgMembership from the given config. +func NewOrgMembershipClient(c config) *OrgMembershipClient { + return &OrgMembershipClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `orgmembership.Hooks(f(g(h())))`. +func (c *OrgMembershipClient) Use(hooks ...Hook) { + c.hooks.OrgMembership = append(c.hooks.OrgMembership, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `orgmembership.Intercept(f(g(h())))`. +func (c *OrgMembershipClient) Intercept(interceptors ...Interceptor) { + c.inters.OrgMembership = append(c.inters.OrgMembership, interceptors...) +} + +// Create returns a builder for creating a OrgMembership entity. +func (c *OrgMembershipClient) Create() *OrgMembershipCreate { + mutation := newOrgMembershipMutation(c.config, OpCreate) + return &OrgMembershipCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of OrgMembership entities. +func (c *OrgMembershipClient) CreateBulk(builders ...*OrgMembershipCreate) *OrgMembershipCreateBulk { + return &OrgMembershipCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *OrgMembershipClient) MapCreateBulk(slice any, setFunc func(*OrgMembershipCreate, int)) *OrgMembershipCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &OrgMembershipCreateBulk{err: fmt.Errorf("calling to OrgMembershipClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*OrgMembershipCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &OrgMembershipCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for OrgMembership. +func (c *OrgMembershipClient) Update() *OrgMembershipUpdate { + mutation := newOrgMembershipMutation(c.config, OpUpdate) + return &OrgMembershipUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *OrgMembershipClient) UpdateOne(om *OrgMembership) *OrgMembershipUpdateOne { + mutation := newOrgMembershipMutation(c.config, OpUpdateOne, withOrgMembership(om)) + return &OrgMembershipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *OrgMembershipClient) UpdateOneID(id string) *OrgMembershipUpdateOne { + mutation := newOrgMembershipMutation(c.config, OpUpdateOne, withOrgMembershipID(id)) + return &OrgMembershipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for OrgMembership. +func (c *OrgMembershipClient) Delete() *OrgMembershipDelete { + mutation := newOrgMembershipMutation(c.config, OpDelete) + return &OrgMembershipDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *OrgMembershipClient) DeleteOne(om *OrgMembership) *OrgMembershipDeleteOne { + return c.DeleteOneID(om.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *OrgMembershipClient) DeleteOneID(id string) *OrgMembershipDeleteOne { + builder := c.Delete().Where(orgmembership.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &OrgMembershipDeleteOne{builder} +} + +// Query returns a query builder for OrgMembership. +func (c *OrgMembershipClient) Query() *OrgMembershipQuery { + return &OrgMembershipQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeOrgMembership}, + inters: c.Interceptors(), + } +} + +// Get returns a OrgMembership entity by its id. +func (c *OrgMembershipClient) Get(ctx context.Context, id string) (*OrgMembership, error) { + return c.Query().Where(orgmembership.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *OrgMembershipClient) GetX(ctx context.Context, id string) *OrgMembership { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryOrganization queries the organization edge of a OrgMembership. +func (c *OrgMembershipClient) QueryOrganization(om *OrgMembership) *OrganizationQuery { + query := (&OrganizationClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := om.ID + step := sqlgraph.NewStep( + sqlgraph.From(orgmembership.Table, orgmembership.FieldID, id), + sqlgraph.To(organization.Table, organization.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, orgmembership.OrganizationTable, orgmembership.OrganizationColumn), + ) + fromV = sqlgraph.Neighbors(om.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *OrgMembershipClient) Hooks() []Hook { + hooks := c.hooks.OrgMembership + return append(hooks[:len(hooks):len(hooks)], orgmembership.Hooks[:]...) +} + +// Interceptors returns the client interceptors. +func (c *OrgMembershipClient) Interceptors() []Interceptor { + return c.inters.OrgMembership +} + +func (c *OrgMembershipClient) mutate(ctx context.Context, m *OrgMembershipMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&OrgMembershipCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&OrgMembershipUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&OrgMembershipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&OrgMembershipDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown OrgMembership mutation op: %q", m.Op()) + } +} + +// OrganizationClient is a client for the Organization schema. +type OrganizationClient struct { + config +} + +// NewOrganizationClient returns a client for the Organization from the given config. +func NewOrganizationClient(c config) *OrganizationClient { + return &OrganizationClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `organization.Hooks(f(g(h())))`. +func (c *OrganizationClient) Use(hooks ...Hook) { + c.hooks.Organization = append(c.hooks.Organization, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `organization.Intercept(f(g(h())))`. +func (c *OrganizationClient) Intercept(interceptors ...Interceptor) { + c.inters.Organization = append(c.inters.Organization, interceptors...) +} + +// Create returns a builder for creating a Organization entity. +func (c *OrganizationClient) Create() *OrganizationCreate { + mutation := newOrganizationMutation(c.config, OpCreate) + return &OrganizationCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Organization entities. +func (c *OrganizationClient) CreateBulk(builders ...*OrganizationCreate) *OrganizationCreateBulk { + return &OrganizationCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *OrganizationClient) MapCreateBulk(slice any, setFunc func(*OrganizationCreate, int)) *OrganizationCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &OrganizationCreateBulk{err: fmt.Errorf("calling to OrganizationClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*OrganizationCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &OrganizationCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Organization. +func (c *OrganizationClient) Update() *OrganizationUpdate { + mutation := newOrganizationMutation(c.config, OpUpdate) + return &OrganizationUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *OrganizationClient) UpdateOne(o *Organization) *OrganizationUpdateOne { + mutation := newOrganizationMutation(c.config, OpUpdateOne, withOrganization(o)) + return &OrganizationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *OrganizationClient) UpdateOneID(id string) *OrganizationUpdateOne { + mutation := newOrganizationMutation(c.config, OpUpdateOne, withOrganizationID(id)) + return &OrganizationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Organization. +func (c *OrganizationClient) Delete() *OrganizationDelete { + mutation := newOrganizationMutation(c.config, OpDelete) + return &OrganizationDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *OrganizationClient) DeleteOne(o *Organization) *OrganizationDeleteOne { + return c.DeleteOneID(o.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *OrganizationClient) DeleteOneID(id string) *OrganizationDeleteOne { + builder := c.Delete().Where(organization.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &OrganizationDeleteOne{builder} +} + +// Query returns a query builder for Organization. +func (c *OrganizationClient) Query() *OrganizationQuery { + return &OrganizationQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeOrganization}, + inters: c.Interceptors(), + } +} + +// Get returns a Organization entity by its id. +func (c *OrganizationClient) Get(ctx context.Context, id string) (*Organization, error) { + return c.Query().Where(organization.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *OrganizationClient) GetX(ctx context.Context, id string) *Organization { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *OrganizationClient) Hooks() []Hook { + hooks := c.hooks.Organization + return append(hooks[:len(hooks):len(hooks)], organization.Hooks[:]...) +} + +// Interceptors returns the client interceptors. +func (c *OrganizationClient) Interceptors() []Interceptor { + return c.inters.Organization +} + +func (c *OrganizationClient) mutate(ctx context.Context, m *OrganizationMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&OrganizationCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&OrganizationUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&OrganizationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&OrganizationDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Organization mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + OrgMembership, Organization []ent.Hook + } + inters struct { + OrgMembership, Organization []ent.Interceptor + } +) diff --git a/entfga/_examples/basic/ent/ent.go b/entfga/_examples/basic/ent/ent.go new file mode 100644 index 0000000..bc8fdd8 --- /dev/null +++ b/entfga/_examples/basic/ent/ent.go @@ -0,0 +1,610 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "reflect" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// columnChecker checks if the column exists in the given table. +func checkColumn(table, column string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + orgmembership.Table: orgmembership.ValidColumn, + organization.Table: organization.ValidColumn, + }) + }) + return columnCheck(table, column) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "ent: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "ent: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "ent: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "ent: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/entfga/_examples/basic/ent/entc.go b/entfga/_examples/basic/ent/entc.go new file mode 100644 index 0000000..a04b428 --- /dev/null +++ b/entfga/_examples/basic/ent/entc.go @@ -0,0 +1,59 @@ +//go:build ignore + +package main + +import ( + "log" + + "entgo.io/contrib/entgql" + "entgo.io/ent/entc/gen" + "github.com/theopenlane/iam/entfga" + "github.com/theopenlane/iam/fgax" + "go.uber.org/zap" + + "entgo.io/ent/entc" +) + +func main() { + gqlExt, err := entgql.NewExtension( + // Tell Ent to generate a GraphQL schema for + // the Ent schema in a file named ent.graphql. + entgql.WithSchemaGenerator(), + entgql.WithSchemaPath("../schema/ent.graphql"), + entgql.WithConfigPath("../gqlgen.yml"), + entgql.WithWhereInputs(true), + ) + if err != nil { + log.Fatalf("creating entgql extension: %v", err) + } + + entfgaExt := entfga.New( + entfga.WithSchemaPath("./schema"), + entfga.WithGeneratedPath("."), + entfga.WithGeneratedPkg("ent"), + ) + + if err := entfgaExt.GenerateAuthzChecks(); err != nil { + log.Fatalf("generating authz checks: %v", err) + } + + if err := entc.Generate("./schema", + &gen.Config{ + Features: []gen.Feature{gen.FeaturePrivacy}, + }, + entc.Dependency( + entc.DependencyName("Authz"), + entc.DependencyType(fgax.Client{}), + ), + entc.Dependency( + entc.DependencyName("Logger"), + entc.DependencyType(zap.SugaredLogger{}), + ), + entc.Extensions( + gqlExt, + entfgaExt, + ), + ); err != nil { + log.Fatal("running ent codegen:", err) + } +} diff --git a/entfga/_examples/basic/ent/enttest/enttest.go b/entfga/_examples/basic/ent/enttest/enttest.go new file mode 100644 index 0000000..77e09ef --- /dev/null +++ b/entfga/_examples/basic/ent/enttest/enttest.go @@ -0,0 +1,84 @@ +// Code generated by ent, DO NOT EDIT. + +package enttest + +import ( + "context" + + "github.com/theopenlane/iam/entfga/_examples/basic/ent" + // required by schema hooks. + _ "github.com/theopenlane/iam/entfga/_examples/basic/ent/runtime" + + "entgo.io/ent/dialect/sql/schema" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/migrate" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []ent.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...ent.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls ent.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client { + o := newOptions(opts) + c, err := ent.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + migrateSchema(t, c, o) + return c +} + +// NewClient calls ent.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *ent.Client { + o := newOptions(opts) + c := ent.NewClient(o.opts...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *ent.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/entfga/_examples/basic/ent/enums/auth_provider.go b/entfga/_examples/basic/ent/enums/auth_provider.go new file mode 100644 index 0000000..28e0bc2 --- /dev/null +++ b/entfga/_examples/basic/ent/enums/auth_provider.go @@ -0,0 +1,49 @@ +package enums + +import ( + "fmt" + "io" +) + +type AuthProvider string + +var ( + // Credentials provider is when the user authenticates with a username and password + Credentials AuthProvider = "CREDENTIALS" + // Google oauth2 provider for authentication + Google AuthProvider = "GOOGLE" + // Github oauth2 provider for authentication + GitHub AuthProvider = "GITHUB" +) + +// Values returns a slice of strings that represents all the possible values of the AuthProvider enum. +// Possible default values are "CREDENTIALS", "GOOGLE", and "GITHUB" +func (AuthProvider) Values() (kinds []string) { + for _, s := range []AuthProvider{Credentials, Google, GitHub} { + kinds = append(kinds, string(s)) + } + + return +} + +// String returns the AuthProvider as a string +func (r AuthProvider) String() string { + return string(r) +} + +// MarshalGQL implement the Marshaler interface for gqlgen +func (r AuthProvider) MarshalGQL(w io.Writer) { + _, _ = w.Write([]byte(`"` + r.String() + `"`)) +} + +// UnmarshalGQL implement the Unmarshaler interface for gqlgen +func (r *AuthProvider) UnmarshalGQL(v interface{}) error { + str, ok := v.(string) + if !ok { + return fmt.Errorf("wrong type for AuthProvider, got: %T", v) //nolint:err113 + } + + *r = AuthProvider(str) + + return nil +} diff --git a/entfga/_examples/basic/ent/enums/doc.go b/entfga/_examples/basic/ent/enums/doc.go new file mode 100644 index 0000000..ccc083a --- /dev/null +++ b/entfga/_examples/basic/ent/enums/doc.go @@ -0,0 +1,2 @@ +// Package enums has enums +package enums diff --git a/entfga/_examples/basic/ent/enums/role.go b/entfga/_examples/basic/ent/enums/role.go new file mode 100644 index 0000000..b6693ef --- /dev/null +++ b/entfga/_examples/basic/ent/enums/role.go @@ -0,0 +1,62 @@ +package enums + +import ( + "fmt" + "io" + "strings" +) + +type Role string + +var ( + RoleOwner Role = "OWNER" + RoleAdmin Role = "ADMIN" + RoleMember Role = "MEMBER" + Invalid Role = "INVALID" +) + +// Values returns a slice of strings that represents all the possible values of the Role enum. +// Possible default values are "ADMIN", and "MEMBER". +func (Role) Values() (kinds []string) { + for _, s := range []Role{RoleAdmin, RoleMember} { + kinds = append(kinds, string(s)) + } + + return +} + +// String returns the role as a string +func (r Role) String() string { + return string(r) +} + +// ToRole returns the Role based on string input +func ToRole(r string) Role { + switch r := strings.ToUpper(r); r { + case RoleOwner.String(): + return RoleOwner + case RoleAdmin.String(): + return RoleAdmin + case RoleMember.String(): + return RoleMember + default: + return Invalid + } +} + +// MarshalGQL implement the Marshaler interface for gqlgen +func (r Role) MarshalGQL(w io.Writer) { + _, _ = w.Write([]byte(`"` + r.String() + `"`)) +} + +// UnmarshalGQL implement the Unmarshaler interface for gqlgen +func (r *Role) UnmarshalGQL(v interface{}) error { + str, ok := v.(string) + if !ok { + return fmt.Errorf("wrong type for Role, got: %T", v) //nolint:err113 + } + + *r = Role(str) + + return nil +} diff --git a/entfga/_examples/basic/ent/generate.go b/entfga/_examples/basic/ent/generate.go new file mode 100644 index 0000000..8232761 --- /dev/null +++ b/entfga/_examples/basic/ent/generate.go @@ -0,0 +1,3 @@ +package ent + +//go:generate go run -mod=mod entc.go diff --git a/entfga/_examples/basic/ent/gql_collection.go b/entfga/_examples/basic/ent/gql_collection.go new file mode 100644 index 0000000..b469a32 --- /dev/null +++ b/entfga/_examples/basic/ent/gql_collection.go @@ -0,0 +1,242 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "github.com/99designs/gqlgen/graphql" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" +) + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (om *OrgMembershipQuery) CollectFields(ctx context.Context, satisfies ...string) (*OrgMembershipQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return om, nil + } + if err := om.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return om, nil +} + +func (om *OrgMembershipQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + var ( + unknownSeen bool + fieldSeen = make(map[string]struct{}, len(orgmembership.Columns)) + selectedFields = []string{orgmembership.FieldID} + ) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + + case "organization": + var ( + alias = field.Alias + path = append(path, alias) + query = (&OrganizationClient{config: om.config}).Query() + ) + if err := query.collectField(ctx, oneNode, opCtx, field, path, mayAddCondition(satisfies, organizationImplementors)...); err != nil { + return err + } + om.withOrganization = query + if _, ok := fieldSeen[orgmembership.FieldOrganizationID]; !ok { + selectedFields = append(selectedFields, orgmembership.FieldOrganizationID) + fieldSeen[orgmembership.FieldOrganizationID] = struct{}{} + } + case "role": + if _, ok := fieldSeen[orgmembership.FieldRole]; !ok { + selectedFields = append(selectedFields, orgmembership.FieldRole) + fieldSeen[orgmembership.FieldRole] = struct{}{} + } + case "organizationID": + if _, ok := fieldSeen[orgmembership.FieldOrganizationID]; !ok { + selectedFields = append(selectedFields, orgmembership.FieldOrganizationID) + fieldSeen[orgmembership.FieldOrganizationID] = struct{}{} + } + case "userID": + if _, ok := fieldSeen[orgmembership.FieldUserID]; !ok { + selectedFields = append(selectedFields, orgmembership.FieldUserID) + fieldSeen[orgmembership.FieldUserID] = struct{}{} + } + case "id": + case "__typename": + default: + unknownSeen = true + } + } + if !unknownSeen { + om.Select(selectedFields...) + } + return nil +} + +type orgmembershipPaginateArgs struct { + first, last *int + after, before *Cursor + opts []OrgMembershipPaginateOption +} + +func newOrgMembershipPaginateArgs(rv map[string]any) *orgmembershipPaginateArgs { + args := &orgmembershipPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[whereField].(*OrgMembershipWhereInput); ok { + args.opts = append(args.opts, WithOrgMembershipFilter(v.Filter)) + } + return args +} + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (o *OrganizationQuery) CollectFields(ctx context.Context, satisfies ...string) (*OrganizationQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return o, nil + } + if err := o.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return o, nil +} + +func (o *OrganizationQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + var ( + unknownSeen bool + fieldSeen = make(map[string]struct{}, len(organization.Columns)) + selectedFields = []string{organization.FieldID} + ) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + case "name": + if _, ok := fieldSeen[organization.FieldName]; !ok { + selectedFields = append(selectedFields, organization.FieldName) + fieldSeen[organization.FieldName] = struct{}{} + } + case "description": + if _, ok := fieldSeen[organization.FieldDescription]; !ok { + selectedFields = append(selectedFields, organization.FieldDescription) + fieldSeen[organization.FieldDescription] = struct{}{} + } + case "id": + case "__typename": + default: + unknownSeen = true + } + } + if !unknownSeen { + o.Select(selectedFields...) + } + return nil +} + +type organizationPaginateArgs struct { + first, last *int + after, before *Cursor + opts []OrganizationPaginateOption +} + +func newOrganizationPaginateArgs(rv map[string]any) *organizationPaginateArgs { + args := &organizationPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[whereField].(*OrganizationWhereInput); ok { + args.opts = append(args.opts, WithOrganizationFilter(v.Filter)) + } + return args +} + +const ( + afterField = "after" + firstField = "first" + beforeField = "before" + lastField = "last" + orderByField = "orderBy" + directionField = "direction" + fieldField = "field" + whereField = "where" +) + +func fieldArgs(ctx context.Context, whereInput any, path ...string) map[string]any { + field := collectedField(ctx, path...) + if field == nil || field.Arguments == nil { + return nil + } + oc := graphql.GetOperationContext(ctx) + args := field.ArgumentMap(oc.Variables) + return unmarshalArgs(ctx, whereInput, args) +} + +// unmarshalArgs allows extracting the field arguments from their raw representation. +func unmarshalArgs(ctx context.Context, whereInput any, args map[string]any) map[string]any { + for _, k := range []string{firstField, lastField} { + v, ok := args[k] + if !ok { + continue + } + i, err := graphql.UnmarshalInt(v) + if err == nil { + args[k] = &i + } + } + for _, k := range []string{beforeField, afterField} { + v, ok := args[k] + if !ok { + continue + } + c := &Cursor{} + if c.UnmarshalGQL(v) == nil { + args[k] = c + } + } + if v, ok := args[whereField]; ok && whereInput != nil { + if err := graphql.UnmarshalInputFromContext(ctx, v, whereInput); err == nil { + args[whereField] = whereInput + } + } + + return args +} + +// mayAddCondition appends another type condition to the satisfies list +// if it does not exist in the list. +func mayAddCondition(satisfies []string, typeCond []string) []string { +Cond: + for _, c := range typeCond { + for _, s := range satisfies { + if c == s { + continue Cond + } + } + satisfies = append(satisfies, c) + } + return satisfies +} diff --git a/entfga/_examples/basic/ent/gql_edge.go b/entfga/_examples/basic/ent/gql_edge.go new file mode 100644 index 0000000..c0d3f71 --- /dev/null +++ b/entfga/_examples/basic/ent/gql_edge.go @@ -0,0 +1,15 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" +) + +func (om *OrgMembership) Organization(ctx context.Context) (*Organization, error) { + result, err := om.Edges.OrganizationOrErr() + if IsNotLoaded(err) { + result, err = om.QueryOrganization().Only(ctx) + } + return result, err +} diff --git a/entfga/_examples/basic/ent/gql_mutation_input.go b/entfga/_examples/basic/ent/gql_mutation_input.go new file mode 100644 index 0000000..ccb5034 --- /dev/null +++ b/entfga/_examples/basic/ent/gql_mutation_input.go @@ -0,0 +1,105 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums" +) + +// CreateOrgMembershipInput represents a mutation input for creating orgmemberships. +type CreateOrgMembershipInput struct { + Role *enums.Role + UserID string + OrganizationID string +} + +// Mutate applies the CreateOrgMembershipInput on the OrgMembershipMutation builder. +func (i *CreateOrgMembershipInput) Mutate(m *OrgMembershipMutation) { + if v := i.Role; v != nil { + m.SetRole(*v) + } + m.SetUserID(i.UserID) + m.SetOrganizationID(i.OrganizationID) +} + +// SetInput applies the change-set in the CreateOrgMembershipInput on the OrgMembershipCreate builder. +func (c *OrgMembershipCreate) SetInput(i CreateOrgMembershipInput) *OrgMembershipCreate { + i.Mutate(c.Mutation()) + return c +} + +// UpdateOrgMembershipInput represents a mutation input for updating orgmemberships. +type UpdateOrgMembershipInput struct { + Role *enums.Role +} + +// Mutate applies the UpdateOrgMembershipInput on the OrgMembershipMutation builder. +func (i *UpdateOrgMembershipInput) Mutate(m *OrgMembershipMutation) { + if v := i.Role; v != nil { + m.SetRole(*v) + } +} + +// SetInput applies the change-set in the UpdateOrgMembershipInput on the OrgMembershipUpdate builder. +func (c *OrgMembershipUpdate) SetInput(i UpdateOrgMembershipInput) *OrgMembershipUpdate { + i.Mutate(c.Mutation()) + return c +} + +// SetInput applies the change-set in the UpdateOrgMembershipInput on the OrgMembershipUpdateOne builder. +func (c *OrgMembershipUpdateOne) SetInput(i UpdateOrgMembershipInput) *OrgMembershipUpdateOne { + i.Mutate(c.Mutation()) + return c +} + +// CreateOrganizationInput represents a mutation input for creating organizations. +type CreateOrganizationInput struct { + Name string + Description *string +} + +// Mutate applies the CreateOrganizationInput on the OrganizationMutation builder. +func (i *CreateOrganizationInput) Mutate(m *OrganizationMutation) { + m.SetName(i.Name) + if v := i.Description; v != nil { + m.SetDescription(*v) + } +} + +// SetInput applies the change-set in the CreateOrganizationInput on the OrganizationCreate builder. +func (c *OrganizationCreate) SetInput(i CreateOrganizationInput) *OrganizationCreate { + i.Mutate(c.Mutation()) + return c +} + +// UpdateOrganizationInput represents a mutation input for updating organizations. +type UpdateOrganizationInput struct { + Name *string + ClearDescription bool + Description *string +} + +// Mutate applies the UpdateOrganizationInput on the OrganizationMutation builder. +func (i *UpdateOrganizationInput) Mutate(m *OrganizationMutation) { + if v := i.Name; v != nil { + m.SetName(*v) + } + if i.ClearDescription { + m.ClearDescription() + } + if v := i.Description; v != nil { + m.SetDescription(*v) + } +} + +// SetInput applies the change-set in the UpdateOrganizationInput on the OrganizationUpdate builder. +func (c *OrganizationUpdate) SetInput(i UpdateOrganizationInput) *OrganizationUpdate { + i.Mutate(c.Mutation()) + return c +} + +// SetInput applies the change-set in the UpdateOrganizationInput on the OrganizationUpdateOne builder. +func (c *OrganizationUpdateOne) SetInput(i UpdateOrganizationInput) *OrganizationUpdateOne { + i.Mutate(c.Mutation()) + return c +} diff --git a/entfga/_examples/basic/ent/gql_node.go b/entfga/_examples/basic/ent/gql_node.go new file mode 100644 index 0000000..4fe3014 --- /dev/null +++ b/entfga/_examples/basic/ent/gql_node.go @@ -0,0 +1,216 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/contrib/entgql" + "github.com/99designs/gqlgen/graphql" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" + "github.com/hashicorp/go-multierror" +) + +// Noder wraps the basic Node method. +type Noder interface { + IsNode() +} + +var orgmembershipImplementors = []string{"OrgMembership", "Node"} + +// IsNode implements the Node interface check for GQLGen. +func (*OrgMembership) IsNode() {} + +var organizationImplementors = []string{"Organization", "Node"} + +// IsNode implements the Node interface check for GQLGen. +func (*Organization) IsNode() {} + +var errNodeInvalidID = &NotFoundError{"node"} + +// NodeOption allows configuring the Noder execution using functional options. +type NodeOption func(*nodeOptions) + +// WithNodeType sets the node Type resolver function (i.e. the table to query). +// If was not provided, the table will be derived from the universal-id +// configuration as described in: https://entgo.io/docs/migrate/#universal-ids. +func WithNodeType(f func(context.Context, string) (string, error)) NodeOption { + return func(o *nodeOptions) { + o.nodeType = f + } +} + +// WithFixedNodeType sets the Type of the node to a fixed value. +func WithFixedNodeType(t string) NodeOption { + return WithNodeType(func(context.Context, string) (string, error) { + return t, nil + }) +} + +type nodeOptions struct { + nodeType func(context.Context, string) (string, error) +} + +func (c *Client) newNodeOpts(opts []NodeOption) *nodeOptions { + nopts := &nodeOptions{} + for _, opt := range opts { + opt(nopts) + } + if nopts.nodeType == nil { + nopts.nodeType = func(ctx context.Context, id string) (string, error) { + return "", fmt.Errorf("cannot resolve noder (%v) without its type", id) + } + } + return nopts +} + +// Noder returns a Node by its id. If the NodeType was not provided, it will +// be derived from the id value according to the universal-id configuration. +// +// c.Noder(ctx, id) +// c.Noder(ctx, id, ent.WithNodeType(typeResolver)) +func (c *Client) Noder(ctx context.Context, id string, opts ...NodeOption) (_ Noder, err error) { + defer func() { + if IsNotFound(err) { + err = multierror.Append(err, entgql.ErrNodeNotFound(id)) + } + }() + table, err := c.newNodeOpts(opts).nodeType(ctx, id) + if err != nil { + return nil, err + } + return c.noder(ctx, table, id) +} + +func (c *Client) noder(ctx context.Context, table string, id string) (Noder, error) { + switch table { + case orgmembership.Table: + query := c.OrgMembership.Query(). + Where(orgmembership.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, orgmembershipImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + case organization.Table: + query := c.Organization.Query(). + Where(organization.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, organizationImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + default: + return nil, fmt.Errorf("cannot resolve noder from table %q: %w", table, errNodeInvalidID) + } +} + +func (c *Client) Noders(ctx context.Context, ids []string, opts ...NodeOption) ([]Noder, error) { + switch len(ids) { + case 1: + noder, err := c.Noder(ctx, ids[0], opts...) + if err != nil { + return nil, err + } + return []Noder{noder}, nil + case 0: + return []Noder{}, nil + } + + noders := make([]Noder, len(ids)) + errors := make([]error, len(ids)) + tables := make(map[string][]string) + id2idx := make(map[string][]int, len(ids)) + nopts := c.newNodeOpts(opts) + for i, id := range ids { + table, err := nopts.nodeType(ctx, id) + if err != nil { + errors[i] = err + continue + } + tables[table] = append(tables[table], id) + id2idx[id] = append(id2idx[id], i) + } + + for table, ids := range tables { + nodes, err := c.noders(ctx, table, ids) + if err != nil { + for _, id := range ids { + for _, idx := range id2idx[id] { + errors[idx] = err + } + } + } else { + for i, id := range ids { + for _, idx := range id2idx[id] { + noders[idx] = nodes[i] + } + } + } + } + + for i, id := range ids { + if errors[i] == nil { + if noders[i] != nil { + continue + } + errors[i] = entgql.ErrNodeNotFound(id) + } else if IsNotFound(errors[i]) { + errors[i] = multierror.Append(errors[i], entgql.ErrNodeNotFound(id)) + } + ctx := graphql.WithPathContext(ctx, + graphql.NewPathWithIndex(i), + ) + graphql.AddError(ctx, errors[i]) + } + return noders, nil +} + +func (c *Client) noders(ctx context.Context, table string, ids []string) ([]Noder, error) { + noders := make([]Noder, len(ids)) + idmap := make(map[string][]*Noder, len(ids)) + for i, id := range ids { + idmap[id] = append(idmap[id], &noders[i]) + } + switch table { + case orgmembership.Table: + query := c.OrgMembership.Query(). + Where(orgmembership.IDIn(ids...)) + query, err := query.CollectFields(ctx, orgmembershipImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + case organization.Table: + query := c.Organization.Query(). + Where(organization.IDIn(ids...)) + query, err := query.CollectFields(ctx, organizationImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + default: + return nil, fmt.Errorf("cannot resolve noders from table %q: %w", table, errNodeInvalidID) + } + return noders, nil +} diff --git a/entfga/_examples/basic/ent/gql_pagination.go b/entfga/_examples/basic/ent/gql_pagination.go new file mode 100644 index 0000000..c2b7bdb --- /dev/null +++ b/entfga/_examples/basic/ent/gql_pagination.go @@ -0,0 +1,595 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/99designs/gqlgen/graphql" + "github.com/99designs/gqlgen/graphql/errcode" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" + "github.com/vektah/gqlparser/v2/gqlerror" +) + +// Common entgql types. +type ( + Cursor = entgql.Cursor[string] + PageInfo = entgql.PageInfo[string] + OrderDirection = entgql.OrderDirection +) + +func orderFunc(o OrderDirection, field string) func(*sql.Selector) { + if o == entgql.OrderDirectionDesc { + return Desc(field) + } + return Asc(field) +} + +const errInvalidPagination = "INVALID_PAGINATION" + +func validateFirstLast(first, last *int) (err *gqlerror.Error) { + switch { + case first != nil && last != nil: + err = &gqlerror.Error{ + Message: "Passing both `first` and `last` to paginate a connection is not supported.", + } + case first != nil && *first < 0: + err = &gqlerror.Error{ + Message: "`first` on a connection cannot be less than zero.", + } + errcode.Set(err, errInvalidPagination) + case last != nil && *last < 0: + err = &gqlerror.Error{ + Message: "`last` on a connection cannot be less than zero.", + } + errcode.Set(err, errInvalidPagination) + } + return err +} + +func collectedField(ctx context.Context, path ...string) *graphql.CollectedField { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return nil + } + field := fc.Field + oc := graphql.GetOperationContext(ctx) +walk: + for _, name := range path { + for _, f := range graphql.CollectFields(oc, field.Selections, nil) { + if f.Alias == name { + field = f + continue walk + } + } + return nil + } + return &field +} + +func hasCollectedField(ctx context.Context, path ...string) bool { + if graphql.GetFieldContext(ctx) == nil { + return true + } + return collectedField(ctx, path...) != nil +} + +const ( + edgesField = "edges" + nodeField = "node" + pageInfoField = "pageInfo" + totalCountField = "totalCount" +) + +func paginateLimit(first, last *int) int { + var limit int + if first != nil { + limit = *first + 1 + } else if last != nil { + limit = *last + 1 + } + return limit +} + +// OrgMembershipEdge is the edge representation of OrgMembership. +type OrgMembershipEdge struct { + Node *OrgMembership `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// OrgMembershipConnection is the connection containing edges to OrgMembership. +type OrgMembershipConnection struct { + Edges []*OrgMembershipEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *OrgMembershipConnection) build(nodes []*OrgMembership, pager *orgmembershipPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *OrgMembership + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *OrgMembership { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *OrgMembership { + return nodes[i] + } + } + c.Edges = make([]*OrgMembershipEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &OrgMembershipEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// OrgMembershipPaginateOption enables pagination customization. +type OrgMembershipPaginateOption func(*orgmembershipPager) error + +// WithOrgMembershipOrder configures pagination ordering. +func WithOrgMembershipOrder(order *OrgMembershipOrder) OrgMembershipPaginateOption { + if order == nil { + order = DefaultOrgMembershipOrder + } + o := *order + return func(pager *orgmembershipPager) error { + if err := o.Direction.Validate(); err != nil { + return err + } + if o.Field == nil { + o.Field = DefaultOrgMembershipOrder.Field + } + pager.order = &o + return nil + } +} + +// WithOrgMembershipFilter configures pagination filter. +func WithOrgMembershipFilter(filter func(*OrgMembershipQuery) (*OrgMembershipQuery, error)) OrgMembershipPaginateOption { + return func(pager *orgmembershipPager) error { + if filter == nil { + return errors.New("OrgMembershipQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type orgmembershipPager struct { + reverse bool + order *OrgMembershipOrder + filter func(*OrgMembershipQuery) (*OrgMembershipQuery, error) +} + +func newOrgMembershipPager(opts []OrgMembershipPaginateOption, reverse bool) (*orgmembershipPager, error) { + pager := &orgmembershipPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + if pager.order == nil { + pager.order = DefaultOrgMembershipOrder + } + return pager, nil +} + +func (p *orgmembershipPager) applyFilter(query *OrgMembershipQuery) (*OrgMembershipQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *orgmembershipPager) toCursor(om *OrgMembership) Cursor { + return p.order.Field.toCursor(om) +} + +func (p *orgmembershipPager) applyCursors(query *OrgMembershipQuery, after, before *Cursor) (*OrgMembershipQuery, error) { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + for _, predicate := range entgql.CursorsPredicate(after, before, DefaultOrgMembershipOrder.Field.column, p.order.Field.column, direction) { + query = query.Where(predicate) + } + return query, nil +} + +func (p *orgmembershipPager) applyOrder(query *OrgMembershipQuery) *OrgMembershipQuery { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(p.order.Field.toTerm(direction.OrderTermOption())) + if p.order.Field != DefaultOrgMembershipOrder.Field { + query = query.Order(DefaultOrgMembershipOrder.Field.toTerm(direction.OrderTermOption())) + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return query +} + +func (p *orgmembershipPager) orderExpr(query *OrgMembershipQuery) sql.Querier { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return sql.ExprFunc(func(b *sql.Builder) { + b.Ident(p.order.Field.column).Pad().WriteString(string(direction)) + if p.order.Field != DefaultOrgMembershipOrder.Field { + b.Comma().Ident(DefaultOrgMembershipOrder.Field.column).Pad().WriteString(string(direction)) + } + }) +} + +// Paginate executes the query and returns a relay based cursor connection to OrgMembership. +func (om *OrgMembershipQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...OrgMembershipPaginateOption, +) (*OrgMembershipConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newOrgMembershipPager(opts, last != nil) + if err != nil { + return nil, err + } + if om, err = pager.applyFilter(om); err != nil { + return nil, err + } + conn := &OrgMembershipConnection{Edges: []*OrgMembershipEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := om.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if om, err = pager.applyCursors(om, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + om.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := om.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + om = pager.applyOrder(om) + nodes, err := om.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +// OrgMembershipOrderField defines the ordering field of OrgMembership. +type OrgMembershipOrderField struct { + // Value extracts the ordering value from the given OrgMembership. + Value func(*OrgMembership) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) orgmembership.OrderOption + toCursor func(*OrgMembership) Cursor +} + +// OrgMembershipOrder defines the ordering of OrgMembership. +type OrgMembershipOrder struct { + Direction OrderDirection `json:"direction"` + Field *OrgMembershipOrderField `json:"field"` +} + +// DefaultOrgMembershipOrder is the default ordering of OrgMembership. +var DefaultOrgMembershipOrder = &OrgMembershipOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &OrgMembershipOrderField{ + Value: func(om *OrgMembership) (ent.Value, error) { + return om.ID, nil + }, + column: orgmembership.FieldID, + toTerm: orgmembership.ByID, + toCursor: func(om *OrgMembership) Cursor { + return Cursor{ID: om.ID} + }, + }, +} + +// ToEdge converts OrgMembership into OrgMembershipEdge. +func (om *OrgMembership) ToEdge(order *OrgMembershipOrder) *OrgMembershipEdge { + if order == nil { + order = DefaultOrgMembershipOrder + } + return &OrgMembershipEdge{ + Node: om, + Cursor: order.Field.toCursor(om), + } +} + +// OrganizationEdge is the edge representation of Organization. +type OrganizationEdge struct { + Node *Organization `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// OrganizationConnection is the connection containing edges to Organization. +type OrganizationConnection struct { + Edges []*OrganizationEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *OrganizationConnection) build(nodes []*Organization, pager *organizationPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *Organization + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *Organization { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *Organization { + return nodes[i] + } + } + c.Edges = make([]*OrganizationEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &OrganizationEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// OrganizationPaginateOption enables pagination customization. +type OrganizationPaginateOption func(*organizationPager) error + +// WithOrganizationOrder configures pagination ordering. +func WithOrganizationOrder(order *OrganizationOrder) OrganizationPaginateOption { + if order == nil { + order = DefaultOrganizationOrder + } + o := *order + return func(pager *organizationPager) error { + if err := o.Direction.Validate(); err != nil { + return err + } + if o.Field == nil { + o.Field = DefaultOrganizationOrder.Field + } + pager.order = &o + return nil + } +} + +// WithOrganizationFilter configures pagination filter. +func WithOrganizationFilter(filter func(*OrganizationQuery) (*OrganizationQuery, error)) OrganizationPaginateOption { + return func(pager *organizationPager) error { + if filter == nil { + return errors.New("OrganizationQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type organizationPager struct { + reverse bool + order *OrganizationOrder + filter func(*OrganizationQuery) (*OrganizationQuery, error) +} + +func newOrganizationPager(opts []OrganizationPaginateOption, reverse bool) (*organizationPager, error) { + pager := &organizationPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + if pager.order == nil { + pager.order = DefaultOrganizationOrder + } + return pager, nil +} + +func (p *organizationPager) applyFilter(query *OrganizationQuery) (*OrganizationQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *organizationPager) toCursor(o *Organization) Cursor { + return p.order.Field.toCursor(o) +} + +func (p *organizationPager) applyCursors(query *OrganizationQuery, after, before *Cursor) (*OrganizationQuery, error) { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + for _, predicate := range entgql.CursorsPredicate(after, before, DefaultOrganizationOrder.Field.column, p.order.Field.column, direction) { + query = query.Where(predicate) + } + return query, nil +} + +func (p *organizationPager) applyOrder(query *OrganizationQuery) *OrganizationQuery { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(p.order.Field.toTerm(direction.OrderTermOption())) + if p.order.Field != DefaultOrganizationOrder.Field { + query = query.Order(DefaultOrganizationOrder.Field.toTerm(direction.OrderTermOption())) + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return query +} + +func (p *organizationPager) orderExpr(query *OrganizationQuery) sql.Querier { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return sql.ExprFunc(func(b *sql.Builder) { + b.Ident(p.order.Field.column).Pad().WriteString(string(direction)) + if p.order.Field != DefaultOrganizationOrder.Field { + b.Comma().Ident(DefaultOrganizationOrder.Field.column).Pad().WriteString(string(direction)) + } + }) +} + +// Paginate executes the query and returns a relay based cursor connection to Organization. +func (o *OrganizationQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...OrganizationPaginateOption, +) (*OrganizationConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newOrganizationPager(opts, last != nil) + if err != nil { + return nil, err + } + if o, err = pager.applyFilter(o); err != nil { + return nil, err + } + conn := &OrganizationConnection{Edges: []*OrganizationEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := o.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if o, err = pager.applyCursors(o, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + o.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := o.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + o = pager.applyOrder(o) + nodes, err := o.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +// OrganizationOrderField defines the ordering field of Organization. +type OrganizationOrderField struct { + // Value extracts the ordering value from the given Organization. + Value func(*Organization) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) organization.OrderOption + toCursor func(*Organization) Cursor +} + +// OrganizationOrder defines the ordering of Organization. +type OrganizationOrder struct { + Direction OrderDirection `json:"direction"` + Field *OrganizationOrderField `json:"field"` +} + +// DefaultOrganizationOrder is the default ordering of Organization. +var DefaultOrganizationOrder = &OrganizationOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &OrganizationOrderField{ + Value: func(o *Organization) (ent.Value, error) { + return o.ID, nil + }, + column: organization.FieldID, + toTerm: organization.ByID, + toCursor: func(o *Organization) Cursor { + return Cursor{ID: o.ID} + }, + }, +} + +// ToEdge converts Organization into OrganizationEdge. +func (o *Organization) ToEdge(order *OrganizationOrder) *OrganizationEdge { + if order == nil { + order = DefaultOrganizationOrder + } + return &OrganizationEdge{ + Node: o, + Cursor: order.Field.toCursor(o), + } +} diff --git a/entfga/_examples/basic/ent/gql_transaction.go b/entfga/_examples/basic/ent/gql_transaction.go new file mode 100644 index 0000000..9611713 --- /dev/null +++ b/entfga/_examples/basic/ent/gql_transaction.go @@ -0,0 +1,30 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "errors" +) + +// OpenTx opens a transaction and returns a transactional +// context along with the created transaction. +func (c *Client) OpenTx(ctx context.Context) (context.Context, driver.Tx, error) { + tx, err := c.Tx(ctx) + if err != nil { + return nil, nil, err + } + ctx = NewTxContext(ctx, tx) + ctx = NewContext(ctx, tx.Client()) + return ctx, tx, nil +} + +// OpenTxFromContext open transactions from client stored in context. +func OpenTxFromContext(ctx context.Context) (context.Context, driver.Tx, error) { + client := FromContext(ctx) + if client == nil { + return nil, nil, errors.New("no client attached to context") + } + return client.OpenTx(ctx) +} diff --git a/entfga/_examples/basic/ent/gql_where_input.go b/entfga/_examples/basic/ent/gql_where_input.go new file mode 100644 index 0000000..4b43b7f --- /dev/null +++ b/entfga/_examples/basic/ent/gql_where_input.go @@ -0,0 +1,541 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "errors" + "fmt" + + "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/predicate" +) + +// OrgMembershipWhereInput represents a where input for filtering OrgMembership queries. +type OrgMembershipWhereInput struct { + Predicates []predicate.OrgMembership `json:"-"` + Not *OrgMembershipWhereInput `json:"not,omitempty"` + Or []*OrgMembershipWhereInput `json:"or,omitempty"` + And []*OrgMembershipWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *string `json:"id,omitempty"` + IDNEQ *string `json:"idNEQ,omitempty"` + IDIn []string `json:"idIn,omitempty"` + IDNotIn []string `json:"idNotIn,omitempty"` + IDGT *string `json:"idGT,omitempty"` + IDGTE *string `json:"idGTE,omitempty"` + IDLT *string `json:"idLT,omitempty"` + IDLTE *string `json:"idLTE,omitempty"` + IDEqualFold *string `json:"idEqualFold,omitempty"` + IDContainsFold *string `json:"idContainsFold,omitempty"` + + // "role" field predicates. + Role *enums.Role `json:"role,omitempty"` + RoleNEQ *enums.Role `json:"roleNEQ,omitempty"` + RoleIn []enums.Role `json:"roleIn,omitempty"` + RoleNotIn []enums.Role `json:"roleNotIn,omitempty"` + + // "organization_id" field predicates. + OrganizationID *string `json:"organizationID,omitempty"` + OrganizationIDNEQ *string `json:"organizationIDNEQ,omitempty"` + OrganizationIDIn []string `json:"organizationIDIn,omitempty"` + OrganizationIDNotIn []string `json:"organizationIDNotIn,omitempty"` + OrganizationIDGT *string `json:"organizationIDGT,omitempty"` + OrganizationIDGTE *string `json:"organizationIDGTE,omitempty"` + OrganizationIDLT *string `json:"organizationIDLT,omitempty"` + OrganizationIDLTE *string `json:"organizationIDLTE,omitempty"` + OrganizationIDContains *string `json:"organizationIDContains,omitempty"` + OrganizationIDHasPrefix *string `json:"organizationIDHasPrefix,omitempty"` + OrganizationIDHasSuffix *string `json:"organizationIDHasSuffix,omitempty"` + OrganizationIDEqualFold *string `json:"organizationIDEqualFold,omitempty"` + OrganizationIDContainsFold *string `json:"organizationIDContainsFold,omitempty"` + + // "user_id" field predicates. + UserID *string `json:"userID,omitempty"` + UserIDNEQ *string `json:"userIDNEQ,omitempty"` + UserIDIn []string `json:"userIDIn,omitempty"` + UserIDNotIn []string `json:"userIDNotIn,omitempty"` + UserIDGT *string `json:"userIDGT,omitempty"` + UserIDGTE *string `json:"userIDGTE,omitempty"` + UserIDLT *string `json:"userIDLT,omitempty"` + UserIDLTE *string `json:"userIDLTE,omitempty"` + UserIDContains *string `json:"userIDContains,omitempty"` + UserIDHasPrefix *string `json:"userIDHasPrefix,omitempty"` + UserIDHasSuffix *string `json:"userIDHasSuffix,omitempty"` + UserIDEqualFold *string `json:"userIDEqualFold,omitempty"` + UserIDContainsFold *string `json:"userIDContainsFold,omitempty"` + + // "organization" edge predicates. + HasOrganization *bool `json:"hasOrganization,omitempty"` + HasOrganizationWith []*OrganizationWhereInput `json:"hasOrganizationWith,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *OrgMembershipWhereInput) AddPredicates(predicates ...predicate.OrgMembership) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the OrgMembershipWhereInput filter on the OrgMembershipQuery builder. +func (i *OrgMembershipWhereInput) Filter(q *OrgMembershipQuery) (*OrgMembershipQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyOrgMembershipWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyOrgMembershipWhereInput is returned in case the OrgMembershipWhereInput is empty. +var ErrEmptyOrgMembershipWhereInput = errors.New("ent: empty predicate OrgMembershipWhereInput") + +// P returns a predicate for filtering orgmemberships. +// An error is returned if the input is empty or invalid. +func (i *OrgMembershipWhereInput) P() (predicate.OrgMembership, error) { + var predicates []predicate.OrgMembership + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, orgmembership.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.OrgMembership, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, orgmembership.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.OrgMembership, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, orgmembership.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, orgmembership.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, orgmembership.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, orgmembership.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, orgmembership.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, orgmembership.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, orgmembership.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, orgmembership.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, orgmembership.IDLTE(*i.IDLTE)) + } + if i.IDEqualFold != nil { + predicates = append(predicates, orgmembership.IDEqualFold(*i.IDEqualFold)) + } + if i.IDContainsFold != nil { + predicates = append(predicates, orgmembership.IDContainsFold(*i.IDContainsFold)) + } + if i.Role != nil { + predicates = append(predicates, orgmembership.RoleEQ(*i.Role)) + } + if i.RoleNEQ != nil { + predicates = append(predicates, orgmembership.RoleNEQ(*i.RoleNEQ)) + } + if len(i.RoleIn) > 0 { + predicates = append(predicates, orgmembership.RoleIn(i.RoleIn...)) + } + if len(i.RoleNotIn) > 0 { + predicates = append(predicates, orgmembership.RoleNotIn(i.RoleNotIn...)) + } + if i.OrganizationID != nil { + predicates = append(predicates, orgmembership.OrganizationIDEQ(*i.OrganizationID)) + } + if i.OrganizationIDNEQ != nil { + predicates = append(predicates, orgmembership.OrganizationIDNEQ(*i.OrganizationIDNEQ)) + } + if len(i.OrganizationIDIn) > 0 { + predicates = append(predicates, orgmembership.OrganizationIDIn(i.OrganizationIDIn...)) + } + if len(i.OrganizationIDNotIn) > 0 { + predicates = append(predicates, orgmembership.OrganizationIDNotIn(i.OrganizationIDNotIn...)) + } + if i.OrganizationIDGT != nil { + predicates = append(predicates, orgmembership.OrganizationIDGT(*i.OrganizationIDGT)) + } + if i.OrganizationIDGTE != nil { + predicates = append(predicates, orgmembership.OrganizationIDGTE(*i.OrganizationIDGTE)) + } + if i.OrganizationIDLT != nil { + predicates = append(predicates, orgmembership.OrganizationIDLT(*i.OrganizationIDLT)) + } + if i.OrganizationIDLTE != nil { + predicates = append(predicates, orgmembership.OrganizationIDLTE(*i.OrganizationIDLTE)) + } + if i.OrganizationIDContains != nil { + predicates = append(predicates, orgmembership.OrganizationIDContains(*i.OrganizationIDContains)) + } + if i.OrganizationIDHasPrefix != nil { + predicates = append(predicates, orgmembership.OrganizationIDHasPrefix(*i.OrganizationIDHasPrefix)) + } + if i.OrganizationIDHasSuffix != nil { + predicates = append(predicates, orgmembership.OrganizationIDHasSuffix(*i.OrganizationIDHasSuffix)) + } + if i.OrganizationIDEqualFold != nil { + predicates = append(predicates, orgmembership.OrganizationIDEqualFold(*i.OrganizationIDEqualFold)) + } + if i.OrganizationIDContainsFold != nil { + predicates = append(predicates, orgmembership.OrganizationIDContainsFold(*i.OrganizationIDContainsFold)) + } + if i.UserID != nil { + predicates = append(predicates, orgmembership.UserIDEQ(*i.UserID)) + } + if i.UserIDNEQ != nil { + predicates = append(predicates, orgmembership.UserIDNEQ(*i.UserIDNEQ)) + } + if len(i.UserIDIn) > 0 { + predicates = append(predicates, orgmembership.UserIDIn(i.UserIDIn...)) + } + if len(i.UserIDNotIn) > 0 { + predicates = append(predicates, orgmembership.UserIDNotIn(i.UserIDNotIn...)) + } + if i.UserIDGT != nil { + predicates = append(predicates, orgmembership.UserIDGT(*i.UserIDGT)) + } + if i.UserIDGTE != nil { + predicates = append(predicates, orgmembership.UserIDGTE(*i.UserIDGTE)) + } + if i.UserIDLT != nil { + predicates = append(predicates, orgmembership.UserIDLT(*i.UserIDLT)) + } + if i.UserIDLTE != nil { + predicates = append(predicates, orgmembership.UserIDLTE(*i.UserIDLTE)) + } + if i.UserIDContains != nil { + predicates = append(predicates, orgmembership.UserIDContains(*i.UserIDContains)) + } + if i.UserIDHasPrefix != nil { + predicates = append(predicates, orgmembership.UserIDHasPrefix(*i.UserIDHasPrefix)) + } + if i.UserIDHasSuffix != nil { + predicates = append(predicates, orgmembership.UserIDHasSuffix(*i.UserIDHasSuffix)) + } + if i.UserIDEqualFold != nil { + predicates = append(predicates, orgmembership.UserIDEqualFold(*i.UserIDEqualFold)) + } + if i.UserIDContainsFold != nil { + predicates = append(predicates, orgmembership.UserIDContainsFold(*i.UserIDContainsFold)) + } + + if i.HasOrganization != nil { + p := orgmembership.HasOrganization() + if !*i.HasOrganization { + p = orgmembership.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasOrganizationWith) > 0 { + with := make([]predicate.Organization, 0, len(i.HasOrganizationWith)) + for _, w := range i.HasOrganizationWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasOrganizationWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, orgmembership.HasOrganizationWith(with...)) + } + switch len(predicates) { + case 0: + return nil, ErrEmptyOrgMembershipWhereInput + case 1: + return predicates[0], nil + default: + return orgmembership.And(predicates...), nil + } +} + +// OrganizationWhereInput represents a where input for filtering Organization queries. +type OrganizationWhereInput struct { + Predicates []predicate.Organization `json:"-"` + Not *OrganizationWhereInput `json:"not,omitempty"` + Or []*OrganizationWhereInput `json:"or,omitempty"` + And []*OrganizationWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *string `json:"id,omitempty"` + IDNEQ *string `json:"idNEQ,omitempty"` + IDIn []string `json:"idIn,omitempty"` + IDNotIn []string `json:"idNotIn,omitempty"` + IDGT *string `json:"idGT,omitempty"` + IDGTE *string `json:"idGTE,omitempty"` + IDLT *string `json:"idLT,omitempty"` + IDLTE *string `json:"idLTE,omitempty"` + IDEqualFold *string `json:"idEqualFold,omitempty"` + IDContainsFold *string `json:"idContainsFold,omitempty"` + + // "name" field predicates. + Name *string `json:"name,omitempty"` + NameNEQ *string `json:"nameNEQ,omitempty"` + NameIn []string `json:"nameIn,omitempty"` + NameNotIn []string `json:"nameNotIn,omitempty"` + NameGT *string `json:"nameGT,omitempty"` + NameGTE *string `json:"nameGTE,omitempty"` + NameLT *string `json:"nameLT,omitempty"` + NameLTE *string `json:"nameLTE,omitempty"` + NameContains *string `json:"nameContains,omitempty"` + NameHasPrefix *string `json:"nameHasPrefix,omitempty"` + NameHasSuffix *string `json:"nameHasSuffix,omitempty"` + NameEqualFold *string `json:"nameEqualFold,omitempty"` + NameContainsFold *string `json:"nameContainsFold,omitempty"` + + // "description" field predicates. + Description *string `json:"description,omitempty"` + DescriptionNEQ *string `json:"descriptionNEQ,omitempty"` + DescriptionIn []string `json:"descriptionIn,omitempty"` + DescriptionNotIn []string `json:"descriptionNotIn,omitempty"` + DescriptionGT *string `json:"descriptionGT,omitempty"` + DescriptionGTE *string `json:"descriptionGTE,omitempty"` + DescriptionLT *string `json:"descriptionLT,omitempty"` + DescriptionLTE *string `json:"descriptionLTE,omitempty"` + DescriptionContains *string `json:"descriptionContains,omitempty"` + DescriptionHasPrefix *string `json:"descriptionHasPrefix,omitempty"` + DescriptionHasSuffix *string `json:"descriptionHasSuffix,omitempty"` + DescriptionIsNil bool `json:"descriptionIsNil,omitempty"` + DescriptionNotNil bool `json:"descriptionNotNil,omitempty"` + DescriptionEqualFold *string `json:"descriptionEqualFold,omitempty"` + DescriptionContainsFold *string `json:"descriptionContainsFold,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *OrganizationWhereInput) AddPredicates(predicates ...predicate.Organization) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the OrganizationWhereInput filter on the OrganizationQuery builder. +func (i *OrganizationWhereInput) Filter(q *OrganizationQuery) (*OrganizationQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyOrganizationWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyOrganizationWhereInput is returned in case the OrganizationWhereInput is empty. +var ErrEmptyOrganizationWhereInput = errors.New("ent: empty predicate OrganizationWhereInput") + +// P returns a predicate for filtering organizations. +// An error is returned if the input is empty or invalid. +func (i *OrganizationWhereInput) P() (predicate.Organization, error) { + var predicates []predicate.Organization + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, organization.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.Organization, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, organization.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.Organization, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, organization.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, organization.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, organization.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, organization.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, organization.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, organization.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, organization.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, organization.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, organization.IDLTE(*i.IDLTE)) + } + if i.IDEqualFold != nil { + predicates = append(predicates, organization.IDEqualFold(*i.IDEqualFold)) + } + if i.IDContainsFold != nil { + predicates = append(predicates, organization.IDContainsFold(*i.IDContainsFold)) + } + if i.Name != nil { + predicates = append(predicates, organization.NameEQ(*i.Name)) + } + if i.NameNEQ != nil { + predicates = append(predicates, organization.NameNEQ(*i.NameNEQ)) + } + if len(i.NameIn) > 0 { + predicates = append(predicates, organization.NameIn(i.NameIn...)) + } + if len(i.NameNotIn) > 0 { + predicates = append(predicates, organization.NameNotIn(i.NameNotIn...)) + } + if i.NameGT != nil { + predicates = append(predicates, organization.NameGT(*i.NameGT)) + } + if i.NameGTE != nil { + predicates = append(predicates, organization.NameGTE(*i.NameGTE)) + } + if i.NameLT != nil { + predicates = append(predicates, organization.NameLT(*i.NameLT)) + } + if i.NameLTE != nil { + predicates = append(predicates, organization.NameLTE(*i.NameLTE)) + } + if i.NameContains != nil { + predicates = append(predicates, organization.NameContains(*i.NameContains)) + } + if i.NameHasPrefix != nil { + predicates = append(predicates, organization.NameHasPrefix(*i.NameHasPrefix)) + } + if i.NameHasSuffix != nil { + predicates = append(predicates, organization.NameHasSuffix(*i.NameHasSuffix)) + } + if i.NameEqualFold != nil { + predicates = append(predicates, organization.NameEqualFold(*i.NameEqualFold)) + } + if i.NameContainsFold != nil { + predicates = append(predicates, organization.NameContainsFold(*i.NameContainsFold)) + } + if i.Description != nil { + predicates = append(predicates, organization.DescriptionEQ(*i.Description)) + } + if i.DescriptionNEQ != nil { + predicates = append(predicates, organization.DescriptionNEQ(*i.DescriptionNEQ)) + } + if len(i.DescriptionIn) > 0 { + predicates = append(predicates, organization.DescriptionIn(i.DescriptionIn...)) + } + if len(i.DescriptionNotIn) > 0 { + predicates = append(predicates, organization.DescriptionNotIn(i.DescriptionNotIn...)) + } + if i.DescriptionGT != nil { + predicates = append(predicates, organization.DescriptionGT(*i.DescriptionGT)) + } + if i.DescriptionGTE != nil { + predicates = append(predicates, organization.DescriptionGTE(*i.DescriptionGTE)) + } + if i.DescriptionLT != nil { + predicates = append(predicates, organization.DescriptionLT(*i.DescriptionLT)) + } + if i.DescriptionLTE != nil { + predicates = append(predicates, organization.DescriptionLTE(*i.DescriptionLTE)) + } + if i.DescriptionContains != nil { + predicates = append(predicates, organization.DescriptionContains(*i.DescriptionContains)) + } + if i.DescriptionHasPrefix != nil { + predicates = append(predicates, organization.DescriptionHasPrefix(*i.DescriptionHasPrefix)) + } + if i.DescriptionHasSuffix != nil { + predicates = append(predicates, organization.DescriptionHasSuffix(*i.DescriptionHasSuffix)) + } + if i.DescriptionIsNil { + predicates = append(predicates, organization.DescriptionIsNil()) + } + if i.DescriptionNotNil { + predicates = append(predicates, organization.DescriptionNotNil()) + } + if i.DescriptionEqualFold != nil { + predicates = append(predicates, organization.DescriptionEqualFold(*i.DescriptionEqualFold)) + } + if i.DescriptionContainsFold != nil { + predicates = append(predicates, organization.DescriptionContainsFold(*i.DescriptionContainsFold)) + } + + switch len(predicates) { + case 0: + return nil, ErrEmptyOrganizationWhereInput + case 1: + return predicates[0], nil + default: + return organization.And(predicates...), nil + } +} diff --git a/entfga/_examples/basic/ent/hook/hook.go b/entfga/_examples/basic/ent/hook/hook.go new file mode 100644 index 0000000..e539f22 --- /dev/null +++ b/entfga/_examples/basic/ent/hook/hook.go @@ -0,0 +1,211 @@ +// Code generated by ent, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "github.com/theopenlane/iam/entfga/_examples/basic/ent" +) + +// The OrgMembershipFunc type is an adapter to allow the use of ordinary +// function as OrgMembership mutator. +type OrgMembershipFunc func(context.Context, *ent.OrgMembershipMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f OrgMembershipFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.OrgMembershipMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.OrgMembershipMutation", m) +} + +// The OrganizationFunc type is an adapter to allow the use of ordinary +// function as Organization mutator. +type OrganizationFunc func(context.Context, *ent.OrganizationMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f OrganizationFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.OrganizationMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.OrganizationMutation", m) +} + +// Condition is a hook condition function. +type Condition func(context.Context, ent.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op ent.Op) Condition { + return func(_ context.Context, m ent.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +func If(hk ent.Hook, cond Condition) ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, ent.Delete|ent.Create) +func On(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, ent.Update|ent.UpdateOne) +func Unless(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) ent.Hook { + return func(ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []ent.Hook { +// return []ent.Hook{ +// Reject(ent.Delete|ent.Update), +// } +// } +func Reject(op ent.Op) ent.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []ent.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...ent.Hook) Chain { + return Chain{append([]ent.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() ent.Hook { + return func(mutator ent.Mutator) ent.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...ent.Hook) Chain { + newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/entfga/_examples/basic/ent/migrate/migrate.go b/entfga/_examples/basic/ent/migrate/migrate.go new file mode 100644 index 0000000..1956a6b --- /dev/null +++ b/entfga/_examples/basic/ent/migrate/migrate.go @@ -0,0 +1,64 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/entfga/_examples/basic/ent/migrate/schema.go b/entfga/_examples/basic/ent/migrate/schema.go new file mode 100644 index 0000000..cd1785f --- /dev/null +++ b/entfga/_examples/basic/ent/migrate/schema.go @@ -0,0 +1,67 @@ +// Code generated by ent, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // OrgMembershipsColumns holds the columns for the "org_memberships" table. + OrgMembershipsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString}, + {Name: "role", Type: field.TypeEnum, Enums: []string{"ADMIN", "MEMBER", "OWNER"}, Default: "MEMBER"}, + {Name: "user_id", Type: field.TypeString}, + {Name: "organization_id", Type: field.TypeString}, + } + // OrgMembershipsTable holds the schema information for the "org_memberships" table. + OrgMembershipsTable = &schema.Table{ + Name: "org_memberships", + Columns: OrgMembershipsColumns, + PrimaryKey: []*schema.Column{OrgMembershipsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "org_memberships_organizations_organization", + Columns: []*schema.Column{OrgMembershipsColumns[3]}, + RefColumns: []*schema.Column{OrganizationsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "orgmembership_user_id_organization_id", + Unique: true, + Columns: []*schema.Column{OrgMembershipsColumns[2], OrgMembershipsColumns[3]}, + }, + }, + } + // OrganizationsColumns holds the columns for the "organizations" table. + OrganizationsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString}, + {Name: "name", Type: field.TypeString}, + {Name: "description", Type: field.TypeString, Nullable: true}, + } + // OrganizationsTable holds the schema information for the "organizations" table. + OrganizationsTable = &schema.Table{ + Name: "organizations", + Columns: OrganizationsColumns, + PrimaryKey: []*schema.Column{OrganizationsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "organization_name", + Unique: true, + Columns: []*schema.Column{OrganizationsColumns[1]}, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + OrgMembershipsTable, + OrganizationsTable, + } +) + +func init() { + OrgMembershipsTable.ForeignKeys[0].RefTable = OrganizationsTable +} diff --git a/entfga/_examples/basic/ent/mutation.go b/entfga/_examples/basic/ent/mutation.go new file mode 100644 index 0000000..c3f88d7 --- /dev/null +++ b/entfga/_examples/basic/ent/mutation.go @@ -0,0 +1,932 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/predicate" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeOrgMembership = "OrgMembership" + TypeOrganization = "Organization" +) + +// OrgMembershipMutation represents an operation that mutates the OrgMembership nodes in the graph. +type OrgMembershipMutation struct { + config + op Op + typ string + id *string + role *enums.Role + user_id *string + clearedFields map[string]struct{} + organization *string + clearedorganization bool + done bool + oldValue func(context.Context) (*OrgMembership, error) + predicates []predicate.OrgMembership +} + +var _ ent.Mutation = (*OrgMembershipMutation)(nil) + +// orgmembershipOption allows management of the mutation configuration using functional options. +type orgmembershipOption func(*OrgMembershipMutation) + +// newOrgMembershipMutation creates new mutation for the OrgMembership entity. +func newOrgMembershipMutation(c config, op Op, opts ...orgmembershipOption) *OrgMembershipMutation { + m := &OrgMembershipMutation{ + config: c, + op: op, + typ: TypeOrgMembership, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withOrgMembershipID sets the ID field of the mutation. +func withOrgMembershipID(id string) orgmembershipOption { + return func(m *OrgMembershipMutation) { + var ( + err error + once sync.Once + value *OrgMembership + ) + m.oldValue = func(ctx context.Context) (*OrgMembership, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().OrgMembership.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withOrgMembership sets the old OrgMembership of the mutation. +func withOrgMembership(node *OrgMembership) orgmembershipOption { + return func(m *OrgMembershipMutation) { + m.oldValue = func(context.Context) (*OrgMembership, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m OrgMembershipMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m OrgMembershipMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of OrgMembership entities. +func (m *OrgMembershipMutation) SetID(id string) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *OrgMembershipMutation) ID() (id string, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *OrgMembershipMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().OrgMembership.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetRole sets the "role" field. +func (m *OrgMembershipMutation) SetRole(e enums.Role) { + m.role = &e +} + +// Role returns the value of the "role" field in the mutation. +func (m *OrgMembershipMutation) Role() (r enums.Role, exists bool) { + v := m.role + if v == nil { + return + } + return *v, true +} + +// OldRole returns the old "role" field's value of the OrgMembership entity. +// If the OrgMembership object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrgMembershipMutation) OldRole(ctx context.Context) (v enums.Role, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRole is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRole requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRole: %w", err) + } + return oldValue.Role, nil +} + +// ResetRole resets all changes to the "role" field. +func (m *OrgMembershipMutation) ResetRole() { + m.role = nil +} + +// SetOrganizationID sets the "organization_id" field. +func (m *OrgMembershipMutation) SetOrganizationID(s string) { + m.organization = &s +} + +// OrganizationID returns the value of the "organization_id" field in the mutation. +func (m *OrgMembershipMutation) OrganizationID() (r string, exists bool) { + v := m.organization + if v == nil { + return + } + return *v, true +} + +// OldOrganizationID returns the old "organization_id" field's value of the OrgMembership entity. +// If the OrgMembership object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrgMembershipMutation) OldOrganizationID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOrganizationID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOrganizationID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOrganizationID: %w", err) + } + return oldValue.OrganizationID, nil +} + +// ResetOrganizationID resets all changes to the "organization_id" field. +func (m *OrgMembershipMutation) ResetOrganizationID() { + m.organization = nil +} + +// SetUserID sets the "user_id" field. +func (m *OrgMembershipMutation) SetUserID(s string) { + m.user_id = &s +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *OrgMembershipMutation) UserID() (r string, exists bool) { + v := m.user_id + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the OrgMembership entity. +// If the OrgMembership object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrgMembershipMutation) OldUserID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *OrgMembershipMutation) ResetUserID() { + m.user_id = nil +} + +// ClearOrganization clears the "organization" edge to the Organization entity. +func (m *OrgMembershipMutation) ClearOrganization() { + m.clearedorganization = true + m.clearedFields[orgmembership.FieldOrganizationID] = struct{}{} +} + +// OrganizationCleared reports if the "organization" edge to the Organization entity was cleared. +func (m *OrgMembershipMutation) OrganizationCleared() bool { + return m.clearedorganization +} + +// OrganizationIDs returns the "organization" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// OrganizationID instead. It exists only for internal usage by the builders. +func (m *OrgMembershipMutation) OrganizationIDs() (ids []string) { + if id := m.organization; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetOrganization resets all changes to the "organization" edge. +func (m *OrgMembershipMutation) ResetOrganization() { + m.organization = nil + m.clearedorganization = false +} + +// Where appends a list predicates to the OrgMembershipMutation builder. +func (m *OrgMembershipMutation) Where(ps ...predicate.OrgMembership) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the OrgMembershipMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *OrgMembershipMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.OrgMembership, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *OrgMembershipMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *OrgMembershipMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (OrgMembership). +func (m *OrgMembershipMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *OrgMembershipMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.role != nil { + fields = append(fields, orgmembership.FieldRole) + } + if m.organization != nil { + fields = append(fields, orgmembership.FieldOrganizationID) + } + if m.user_id != nil { + fields = append(fields, orgmembership.FieldUserID) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *OrgMembershipMutation) Field(name string) (ent.Value, bool) { + switch name { + case orgmembership.FieldRole: + return m.Role() + case orgmembership.FieldOrganizationID: + return m.OrganizationID() + case orgmembership.FieldUserID: + return m.UserID() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *OrgMembershipMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case orgmembership.FieldRole: + return m.OldRole(ctx) + case orgmembership.FieldOrganizationID: + return m.OldOrganizationID(ctx) + case orgmembership.FieldUserID: + return m.OldUserID(ctx) + } + return nil, fmt.Errorf("unknown OrgMembership field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *OrgMembershipMutation) SetField(name string, value ent.Value) error { + switch name { + case orgmembership.FieldRole: + v, ok := value.(enums.Role) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRole(v) + return nil + case orgmembership.FieldOrganizationID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOrganizationID(v) + return nil + case orgmembership.FieldUserID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + } + return fmt.Errorf("unknown OrgMembership field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *OrgMembershipMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *OrgMembershipMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *OrgMembershipMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown OrgMembership numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *OrgMembershipMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *OrgMembershipMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *OrgMembershipMutation) ClearField(name string) error { + return fmt.Errorf("unknown OrgMembership nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *OrgMembershipMutation) ResetField(name string) error { + switch name { + case orgmembership.FieldRole: + m.ResetRole() + return nil + case orgmembership.FieldOrganizationID: + m.ResetOrganizationID() + return nil + case orgmembership.FieldUserID: + m.ResetUserID() + return nil + } + return fmt.Errorf("unknown OrgMembership field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *OrgMembershipMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.organization != nil { + edges = append(edges, orgmembership.EdgeOrganization) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *OrgMembershipMutation) AddedIDs(name string) []ent.Value { + switch name { + case orgmembership.EdgeOrganization: + if id := m.organization; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *OrgMembershipMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *OrgMembershipMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *OrgMembershipMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedorganization { + edges = append(edges, orgmembership.EdgeOrganization) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *OrgMembershipMutation) EdgeCleared(name string) bool { + switch name { + case orgmembership.EdgeOrganization: + return m.clearedorganization + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *OrgMembershipMutation) ClearEdge(name string) error { + switch name { + case orgmembership.EdgeOrganization: + m.ClearOrganization() + return nil + } + return fmt.Errorf("unknown OrgMembership unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *OrgMembershipMutation) ResetEdge(name string) error { + switch name { + case orgmembership.EdgeOrganization: + m.ResetOrganization() + return nil + } + return fmt.Errorf("unknown OrgMembership edge %s", name) +} + +// OrganizationMutation represents an operation that mutates the Organization nodes in the graph. +type OrganizationMutation struct { + config + op Op + typ string + id *string + name *string + description *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Organization, error) + predicates []predicate.Organization +} + +var _ ent.Mutation = (*OrganizationMutation)(nil) + +// organizationOption allows management of the mutation configuration using functional options. +type organizationOption func(*OrganizationMutation) + +// newOrganizationMutation creates new mutation for the Organization entity. +func newOrganizationMutation(c config, op Op, opts ...organizationOption) *OrganizationMutation { + m := &OrganizationMutation{ + config: c, + op: op, + typ: TypeOrganization, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withOrganizationID sets the ID field of the mutation. +func withOrganizationID(id string) organizationOption { + return func(m *OrganizationMutation) { + var ( + err error + once sync.Once + value *Organization + ) + m.oldValue = func(ctx context.Context) (*Organization, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Organization.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withOrganization sets the old Organization of the mutation. +func withOrganization(node *Organization) organizationOption { + return func(m *OrganizationMutation) { + m.oldValue = func(context.Context) (*Organization, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m OrganizationMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m OrganizationMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Organization entities. +func (m *OrganizationMutation) SetID(id string) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *OrganizationMutation) ID() (id string, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *OrganizationMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Organization.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *OrganizationMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *OrganizationMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Organization entity. +// If the Organization object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrganizationMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *OrganizationMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *OrganizationMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *OrganizationMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the Organization entity. +// If the Organization object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *OrganizationMutation) OldDescription(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *OrganizationMutation) ClearDescription() { + m.description = nil + m.clearedFields[organization.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *OrganizationMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[organization.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *OrganizationMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, organization.FieldDescription) +} + +// Where appends a list predicates to the OrganizationMutation builder. +func (m *OrganizationMutation) Where(ps ...predicate.Organization) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the OrganizationMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *OrganizationMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Organization, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *OrganizationMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *OrganizationMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Organization). +func (m *OrganizationMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *OrganizationMutation) Fields() []string { + fields := make([]string, 0, 2) + if m.name != nil { + fields = append(fields, organization.FieldName) + } + if m.description != nil { + fields = append(fields, organization.FieldDescription) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *OrganizationMutation) Field(name string) (ent.Value, bool) { + switch name { + case organization.FieldName: + return m.Name() + case organization.FieldDescription: + return m.Description() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *OrganizationMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case organization.FieldName: + return m.OldName(ctx) + case organization.FieldDescription: + return m.OldDescription(ctx) + } + return nil, fmt.Errorf("unknown Organization field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *OrganizationMutation) SetField(name string, value ent.Value) error { + switch name { + case organization.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case organization.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + } + return fmt.Errorf("unknown Organization field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *OrganizationMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *OrganizationMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *OrganizationMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Organization numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *OrganizationMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(organization.FieldDescription) { + fields = append(fields, organization.FieldDescription) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *OrganizationMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *OrganizationMutation) ClearField(name string) error { + switch name { + case organization.FieldDescription: + m.ClearDescription() + return nil + } + return fmt.Errorf("unknown Organization nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *OrganizationMutation) ResetField(name string) error { + switch name { + case organization.FieldName: + m.ResetName() + return nil + case organization.FieldDescription: + m.ResetDescription() + return nil + } + return fmt.Errorf("unknown Organization field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *OrganizationMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *OrganizationMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *OrganizationMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *OrganizationMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *OrganizationMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *OrganizationMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *OrganizationMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Organization unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *OrganizationMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Organization edge %s", name) +} diff --git a/entfga/_examples/basic/ent/organization.go b/entfga/_examples/basic/ent/organization.go new file mode 100644 index 0000000..445ff4e --- /dev/null +++ b/entfga/_examples/basic/ent/organization.go @@ -0,0 +1,112 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" +) + +// Organization is the model entity for the Organization schema. +type Organization struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // the name of the organization + Name string `json:"name,omitempty"` + // An optional description of the organization + Description string `json:"description,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Organization) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case organization.FieldID, organization.FieldName, organization.FieldDescription: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Organization fields. +func (o *Organization) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case organization.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + o.ID = value.String + } + case organization.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + o.Name = value.String + } + case organization.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + o.Description = value.String + } + default: + o.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Organization. +// This includes values selected through modifiers, order, etc. +func (o *Organization) Value(name string) (ent.Value, error) { + return o.selectValues.Get(name) +} + +// Update returns a builder for updating this Organization. +// Note that you need to call Organization.Unwrap() before calling this method if this Organization +// was returned from a transaction, and the transaction was committed or rolled back. +func (o *Organization) Update() *OrganizationUpdateOne { + return NewOrganizationClient(o.config).UpdateOne(o) +} + +// Unwrap unwraps the Organization entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (o *Organization) Unwrap() *Organization { + _tx, ok := o.config.driver.(*txDriver) + if !ok { + panic("ent: Organization is not a transactional entity") + } + o.config.driver = _tx.drv + return o +} + +// String implements the fmt.Stringer. +func (o *Organization) String() string { + var builder strings.Builder + builder.WriteString("Organization(") + builder.WriteString(fmt.Sprintf("id=%v, ", o.ID)) + builder.WriteString("name=") + builder.WriteString(o.Name) + builder.WriteString(", ") + builder.WriteString("description=") + builder.WriteString(o.Description) + builder.WriteByte(')') + return builder.String() +} + +// Organizations is a parsable slice of Organization. +type Organizations []*Organization diff --git a/entfga/_examples/basic/ent/organization/organization.go b/entfga/_examples/basic/ent/organization/organization.go new file mode 100644 index 0000000..60f877e --- /dev/null +++ b/entfga/_examples/basic/ent/organization/organization.go @@ -0,0 +1,68 @@ +// Code generated by ent, DO NOT EDIT. + +package organization + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the organization type in the database. + Label = "organization" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // Table holds the table name of the organization in the database. + Table = "organizations" +) + +// Columns holds all SQL columns for organization fields. +var Columns = []string{ + FieldID, + FieldName, + FieldDescription, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +// Note that the variables below are initialized by the runtime +// package on the initialization of the application. Therefore, +// it should be imported in the main as follows: +// +// import _ "github.com/theopenlane/iam/entfga/_examples/basic/ent/runtime" +var ( + Hooks [1]ent.Hook + Policy ent.Policy + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error +) + +// OrderOption defines the ordering options for the Organization queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByDescription orders the results by the description field. +func ByDescription(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDescription, opts...).ToFunc() +} diff --git a/entfga/_examples/basic/ent/organization/where.go b/entfga/_examples/basic/ent/organization/where.go new file mode 100644 index 0000000..4dab8a7 --- /dev/null +++ b/entfga/_examples/basic/ent/organization/where.go @@ -0,0 +1,228 @@ +// Code generated by ent, DO NOT EDIT. + +package organization + +import ( + "entgo.io/ent/dialect/sql" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.Organization { + return predicate.Organization(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Organization { + return predicate.Organization(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Organization { + return predicate.Organization(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Organization { + return predicate.Organization(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.Organization { + return predicate.Organization(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.Organization { + return predicate.Organization(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Organization { + return predicate.Organization(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Organization { + return predicate.Organization(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Organization { + return predicate.Organization(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.Organization { + return predicate.Organization(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.Organization { + return predicate.Organization(sql.FieldContainsFold(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Organization { + return predicate.Organization(sql.FieldEQ(FieldName, v)) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.Organization { + return predicate.Organization(sql.FieldEQ(FieldDescription, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Organization { + return predicate.Organization(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Organization { + return predicate.Organization(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Organization { + return predicate.Organization(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Organization { + return predicate.Organization(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Organization { + return predicate.Organization(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Organization { + return predicate.Organization(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Organization { + return predicate.Organization(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Organization { + return predicate.Organization(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Organization { + return predicate.Organization(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Organization { + return predicate.Organization(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Organization { + return predicate.Organization(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Organization { + return predicate.Organization(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Organization { + return predicate.Organization(sql.FieldContainsFold(FieldName, v)) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.Organization { + return predicate.Organization(sql.FieldEQ(FieldDescription, v)) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.Organization { + return predicate.Organization(sql.FieldNEQ(FieldDescription, v)) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.Organization { + return predicate.Organization(sql.FieldIn(FieldDescription, vs...)) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.Organization { + return predicate.Organization(sql.FieldNotIn(FieldDescription, vs...)) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.Organization { + return predicate.Organization(sql.FieldGT(FieldDescription, v)) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.Organization { + return predicate.Organization(sql.FieldGTE(FieldDescription, v)) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.Organization { + return predicate.Organization(sql.FieldLT(FieldDescription, v)) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.Organization { + return predicate.Organization(sql.FieldLTE(FieldDescription, v)) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.Organization { + return predicate.Organization(sql.FieldContains(FieldDescription, v)) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.Organization { + return predicate.Organization(sql.FieldHasPrefix(FieldDescription, v)) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.Organization { + return predicate.Organization(sql.FieldHasSuffix(FieldDescription, v)) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.Organization { + return predicate.Organization(sql.FieldIsNull(FieldDescription)) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.Organization { + return predicate.Organization(sql.FieldNotNull(FieldDescription)) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.Organization { + return predicate.Organization(sql.FieldEqualFold(FieldDescription, v)) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.Organization { + return predicate.Organization(sql.FieldContainsFold(FieldDescription, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Organization) predicate.Organization { + return predicate.Organization(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Organization) predicate.Organization { + return predicate.Organization(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Organization) predicate.Organization { + return predicate.Organization(sql.NotPredicates(p)) +} diff --git a/entfga/_examples/basic/ent/organization_create.go b/entfga/_examples/basic/ent/organization_create.go new file mode 100644 index 0000000..d4c66fa --- /dev/null +++ b/entfga/_examples/basic/ent/organization_create.go @@ -0,0 +1,217 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" +) + +// OrganizationCreate is the builder for creating a Organization entity. +type OrganizationCreate struct { + config + mutation *OrganizationMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (oc *OrganizationCreate) SetName(s string) *OrganizationCreate { + oc.mutation.SetName(s) + return oc +} + +// SetDescription sets the "description" field. +func (oc *OrganizationCreate) SetDescription(s string) *OrganizationCreate { + oc.mutation.SetDescription(s) + return oc +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (oc *OrganizationCreate) SetNillableDescription(s *string) *OrganizationCreate { + if s != nil { + oc.SetDescription(*s) + } + return oc +} + +// SetID sets the "id" field. +func (oc *OrganizationCreate) SetID(s string) *OrganizationCreate { + oc.mutation.SetID(s) + return oc +} + +// Mutation returns the OrganizationMutation object of the builder. +func (oc *OrganizationCreate) Mutation() *OrganizationMutation { + return oc.mutation +} + +// Save creates the Organization in the database. +func (oc *OrganizationCreate) Save(ctx context.Context) (*Organization, error) { + return withHooks(ctx, oc.sqlSave, oc.mutation, oc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (oc *OrganizationCreate) SaveX(ctx context.Context) *Organization { + v, err := oc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (oc *OrganizationCreate) Exec(ctx context.Context) error { + _, err := oc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (oc *OrganizationCreate) ExecX(ctx context.Context) { + if err := oc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (oc *OrganizationCreate) check() error { + if _, ok := oc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Organization.name"`)} + } + if v, ok := oc.mutation.Name(); ok { + if err := organization.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Organization.name": %w`, err)} + } + } + return nil +} + +func (oc *OrganizationCreate) sqlSave(ctx context.Context) (*Organization, error) { + if err := oc.check(); err != nil { + return nil, err + } + _node, _spec := oc.createSpec() + if err := sqlgraph.CreateNode(ctx, oc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected Organization.ID type: %T", _spec.ID.Value) + } + } + oc.mutation.id = &_node.ID + oc.mutation.done = true + return _node, nil +} + +func (oc *OrganizationCreate) createSpec() (*Organization, *sqlgraph.CreateSpec) { + var ( + _node = &Organization{config: oc.config} + _spec = sqlgraph.NewCreateSpec(organization.Table, sqlgraph.NewFieldSpec(organization.FieldID, field.TypeString)) + ) + if id, ok := oc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := oc.mutation.Name(); ok { + _spec.SetField(organization.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := oc.mutation.Description(); ok { + _spec.SetField(organization.FieldDescription, field.TypeString, value) + _node.Description = value + } + return _node, _spec +} + +// OrganizationCreateBulk is the builder for creating many Organization entities in bulk. +type OrganizationCreateBulk struct { + config + err error + builders []*OrganizationCreate +} + +// Save creates the Organization entities in the database. +func (ocb *OrganizationCreateBulk) Save(ctx context.Context) ([]*Organization, error) { + if ocb.err != nil { + return nil, ocb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ocb.builders)) + nodes := make([]*Organization, len(ocb.builders)) + mutators := make([]Mutator, len(ocb.builders)) + for i := range ocb.builders { + func(i int, root context.Context) { + builder := ocb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*OrganizationMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, ocb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, ocb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, ocb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ocb *OrganizationCreateBulk) SaveX(ctx context.Context) []*Organization { + v, err := ocb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ocb *OrganizationCreateBulk) Exec(ctx context.Context) error { + _, err := ocb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ocb *OrganizationCreateBulk) ExecX(ctx context.Context) { + if err := ocb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entfga/_examples/basic/ent/organization_delete.go b/entfga/_examples/basic/ent/organization_delete.go new file mode 100644 index 0000000..099d79d --- /dev/null +++ b/entfga/_examples/basic/ent/organization_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/predicate" +) + +// OrganizationDelete is the builder for deleting a Organization entity. +type OrganizationDelete struct { + config + hooks []Hook + mutation *OrganizationMutation +} + +// Where appends a list predicates to the OrganizationDelete builder. +func (od *OrganizationDelete) Where(ps ...predicate.Organization) *OrganizationDelete { + od.mutation.Where(ps...) + return od +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (od *OrganizationDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, od.sqlExec, od.mutation, od.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (od *OrganizationDelete) ExecX(ctx context.Context) int { + n, err := od.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (od *OrganizationDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(organization.Table, sqlgraph.NewFieldSpec(organization.FieldID, field.TypeString)) + if ps := od.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, od.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + od.mutation.done = true + return affected, err +} + +// OrganizationDeleteOne is the builder for deleting a single Organization entity. +type OrganizationDeleteOne struct { + od *OrganizationDelete +} + +// Where appends a list predicates to the OrganizationDelete builder. +func (odo *OrganizationDeleteOne) Where(ps ...predicate.Organization) *OrganizationDeleteOne { + odo.od.mutation.Where(ps...) + return odo +} + +// Exec executes the deletion query. +func (odo *OrganizationDeleteOne) Exec(ctx context.Context) error { + n, err := odo.od.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{organization.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (odo *OrganizationDeleteOne) ExecX(ctx context.Context) { + if err := odo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entfga/_examples/basic/ent/organization_query.go b/entfga/_examples/basic/ent/organization_query.go new file mode 100644 index 0000000..a2800c4 --- /dev/null +++ b/entfga/_examples/basic/ent/organization_query.go @@ -0,0 +1,546 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/predicate" +) + +// OrganizationQuery is the builder for querying Organization entities. +type OrganizationQuery struct { + config + ctx *QueryContext + order []organization.OrderOption + inters []Interceptor + predicates []predicate.Organization + modifiers []func(*sql.Selector) + loadTotal []func(context.Context, []*Organization) error + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the OrganizationQuery builder. +func (oq *OrganizationQuery) Where(ps ...predicate.Organization) *OrganizationQuery { + oq.predicates = append(oq.predicates, ps...) + return oq +} + +// Limit the number of records to be returned by this query. +func (oq *OrganizationQuery) Limit(limit int) *OrganizationQuery { + oq.ctx.Limit = &limit + return oq +} + +// Offset to start from. +func (oq *OrganizationQuery) Offset(offset int) *OrganizationQuery { + oq.ctx.Offset = &offset + return oq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (oq *OrganizationQuery) Unique(unique bool) *OrganizationQuery { + oq.ctx.Unique = &unique + return oq +} + +// Order specifies how the records should be ordered. +func (oq *OrganizationQuery) Order(o ...organization.OrderOption) *OrganizationQuery { + oq.order = append(oq.order, o...) + return oq +} + +// First returns the first Organization entity from the query. +// Returns a *NotFoundError when no Organization was found. +func (oq *OrganizationQuery) First(ctx context.Context) (*Organization, error) { + nodes, err := oq.Limit(1).All(setContextOp(ctx, oq.ctx, "First")) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{organization.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (oq *OrganizationQuery) FirstX(ctx context.Context) *Organization { + node, err := oq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Organization ID from the query. +// Returns a *NotFoundError when no Organization ID was found. +func (oq *OrganizationQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = oq.Limit(1).IDs(setContextOp(ctx, oq.ctx, "FirstID")); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{organization.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (oq *OrganizationQuery) FirstIDX(ctx context.Context) string { + id, err := oq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Organization entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Organization entity is found. +// Returns a *NotFoundError when no Organization entities are found. +func (oq *OrganizationQuery) Only(ctx context.Context) (*Organization, error) { + nodes, err := oq.Limit(2).All(setContextOp(ctx, oq.ctx, "Only")) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{organization.Label} + default: + return nil, &NotSingularError{organization.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (oq *OrganizationQuery) OnlyX(ctx context.Context) *Organization { + node, err := oq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Organization ID in the query. +// Returns a *NotSingularError when more than one Organization ID is found. +// Returns a *NotFoundError when no entities are found. +func (oq *OrganizationQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = oq.Limit(2).IDs(setContextOp(ctx, oq.ctx, "OnlyID")); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{organization.Label} + default: + err = &NotSingularError{organization.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (oq *OrganizationQuery) OnlyIDX(ctx context.Context) string { + id, err := oq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Organizations. +func (oq *OrganizationQuery) All(ctx context.Context) ([]*Organization, error) { + ctx = setContextOp(ctx, oq.ctx, "All") + if err := oq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Organization, *OrganizationQuery]() + return withInterceptors[[]*Organization](ctx, oq, qr, oq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (oq *OrganizationQuery) AllX(ctx context.Context) []*Organization { + nodes, err := oq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Organization IDs. +func (oq *OrganizationQuery) IDs(ctx context.Context) (ids []string, err error) { + if oq.ctx.Unique == nil && oq.path != nil { + oq.Unique(true) + } + ctx = setContextOp(ctx, oq.ctx, "IDs") + if err = oq.Select(organization.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (oq *OrganizationQuery) IDsX(ctx context.Context) []string { + ids, err := oq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (oq *OrganizationQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, oq.ctx, "Count") + if err := oq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, oq, querierCount[*OrganizationQuery](), oq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (oq *OrganizationQuery) CountX(ctx context.Context) int { + count, err := oq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (oq *OrganizationQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, oq.ctx, "Exist") + switch _, err := oq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (oq *OrganizationQuery) ExistX(ctx context.Context) bool { + exist, err := oq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the OrganizationQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (oq *OrganizationQuery) Clone() *OrganizationQuery { + if oq == nil { + return nil + } + return &OrganizationQuery{ + config: oq.config, + ctx: oq.ctx.Clone(), + order: append([]organization.OrderOption{}, oq.order...), + inters: append([]Interceptor{}, oq.inters...), + predicates: append([]predicate.Organization{}, oq.predicates...), + // clone intermediate query. + sql: oq.sql.Clone(), + path: oq.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Organization.Query(). +// GroupBy(organization.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (oq *OrganizationQuery) GroupBy(field string, fields ...string) *OrganizationGroupBy { + oq.ctx.Fields = append([]string{field}, fields...) + grbuild := &OrganizationGroupBy{build: oq} + grbuild.flds = &oq.ctx.Fields + grbuild.label = organization.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// } +// +// client.Organization.Query(). +// Select(organization.FieldName). +// Scan(ctx, &v) +func (oq *OrganizationQuery) Select(fields ...string) *OrganizationSelect { + oq.ctx.Fields = append(oq.ctx.Fields, fields...) + sbuild := &OrganizationSelect{OrganizationQuery: oq} + sbuild.label = organization.Label + sbuild.flds, sbuild.scan = &oq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a OrganizationSelect configured with the given aggregations. +func (oq *OrganizationQuery) Aggregate(fns ...AggregateFunc) *OrganizationSelect { + return oq.Select().Aggregate(fns...) +} + +func (oq *OrganizationQuery) prepareQuery(ctx context.Context) error { + for _, inter := range oq.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, oq); err != nil { + return err + } + } + } + for _, f := range oq.ctx.Fields { + if !organization.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if oq.path != nil { + prev, err := oq.path(ctx) + if err != nil { + return err + } + oq.sql = prev + } + if organization.Policy == nil { + return errors.New("ent: uninitialized organization.Policy (forgotten import ent/runtime?)") + } + if err := organization.Policy.EvalQuery(ctx, oq); err != nil { + return err + } + return nil +} + +func (oq *OrganizationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Organization, error) { + var ( + nodes = []*Organization{} + _spec = oq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Organization).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Organization{config: oq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + if len(oq.modifiers) > 0 { + _spec.Modifiers = oq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, oq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + for i := range oq.loadTotal { + if err := oq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (oq *OrganizationQuery) sqlCount(ctx context.Context) (int, error) { + _spec := oq.querySpec() + if len(oq.modifiers) > 0 { + _spec.Modifiers = oq.modifiers + } + _spec.Node.Columns = oq.ctx.Fields + if len(oq.ctx.Fields) > 0 { + _spec.Unique = oq.ctx.Unique != nil && *oq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, oq.driver, _spec) +} + +func (oq *OrganizationQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(organization.Table, organization.Columns, sqlgraph.NewFieldSpec(organization.FieldID, field.TypeString)) + _spec.From = oq.sql + if unique := oq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if oq.path != nil { + _spec.Unique = true + } + if fields := oq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, organization.FieldID) + for i := range fields { + if fields[i] != organization.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := oq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := oq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := oq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := oq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (oq *OrganizationQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(oq.driver.Dialect()) + t1 := builder.Table(organization.Table) + columns := oq.ctx.Fields + if len(columns) == 0 { + columns = organization.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if oq.sql != nil { + selector = oq.sql + selector.Select(selector.Columns(columns...)...) + } + if oq.ctx.Unique != nil && *oq.ctx.Unique { + selector.Distinct() + } + for _, p := range oq.predicates { + p(selector) + } + for _, p := range oq.order { + p(selector) + } + if offset := oq.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := oq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// OrganizationGroupBy is the group-by builder for Organization entities. +type OrganizationGroupBy struct { + selector + build *OrganizationQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (ogb *OrganizationGroupBy) Aggregate(fns ...AggregateFunc) *OrganizationGroupBy { + ogb.fns = append(ogb.fns, fns...) + return ogb +} + +// Scan applies the selector query and scans the result into the given value. +func (ogb *OrganizationGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ogb.build.ctx, "GroupBy") + if err := ogb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OrganizationQuery, *OrganizationGroupBy](ctx, ogb.build, ogb, ogb.build.inters, v) +} + +func (ogb *OrganizationGroupBy) sqlScan(ctx context.Context, root *OrganizationQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ogb.fns)) + for _, fn := range ogb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ogb.flds)+len(ogb.fns)) + for _, f := range *ogb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*ogb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ogb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// OrganizationSelect is the builder for selecting fields of Organization entities. +type OrganizationSelect struct { + *OrganizationQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (os *OrganizationSelect) Aggregate(fns ...AggregateFunc) *OrganizationSelect { + os.fns = append(os.fns, fns...) + return os +} + +// Scan applies the selector query and scans the result into the given value. +func (os *OrganizationSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, os.ctx, "Select") + if err := os.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OrganizationQuery, *OrganizationSelect](ctx, os.OrganizationQuery, os, os.inters, v) +} + +func (os *OrganizationSelect) sqlScan(ctx context.Context, root *OrganizationQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(os.fns)) + for _, fn := range os.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*os.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := os.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entfga/_examples/basic/ent/organization_update.go b/entfga/_examples/basic/ent/organization_update.go new file mode 100644 index 0000000..d4ade44 --- /dev/null +++ b/entfga/_examples/basic/ent/organization_update.go @@ -0,0 +1,287 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/predicate" +) + +// OrganizationUpdate is the builder for updating Organization entities. +type OrganizationUpdate struct { + config + hooks []Hook + mutation *OrganizationMutation +} + +// Where appends a list predicates to the OrganizationUpdate builder. +func (ou *OrganizationUpdate) Where(ps ...predicate.Organization) *OrganizationUpdate { + ou.mutation.Where(ps...) + return ou +} + +// SetName sets the "name" field. +func (ou *OrganizationUpdate) SetName(s string) *OrganizationUpdate { + ou.mutation.SetName(s) + return ou +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (ou *OrganizationUpdate) SetNillableName(s *string) *OrganizationUpdate { + if s != nil { + ou.SetName(*s) + } + return ou +} + +// SetDescription sets the "description" field. +func (ou *OrganizationUpdate) SetDescription(s string) *OrganizationUpdate { + ou.mutation.SetDescription(s) + return ou +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (ou *OrganizationUpdate) SetNillableDescription(s *string) *OrganizationUpdate { + if s != nil { + ou.SetDescription(*s) + } + return ou +} + +// ClearDescription clears the value of the "description" field. +func (ou *OrganizationUpdate) ClearDescription() *OrganizationUpdate { + ou.mutation.ClearDescription() + return ou +} + +// Mutation returns the OrganizationMutation object of the builder. +func (ou *OrganizationUpdate) Mutation() *OrganizationMutation { + return ou.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (ou *OrganizationUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, ou.sqlSave, ou.mutation, ou.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ou *OrganizationUpdate) SaveX(ctx context.Context) int { + affected, err := ou.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (ou *OrganizationUpdate) Exec(ctx context.Context) error { + _, err := ou.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ou *OrganizationUpdate) ExecX(ctx context.Context) { + if err := ou.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ou *OrganizationUpdate) check() error { + if v, ok := ou.mutation.Name(); ok { + if err := organization.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Organization.name": %w`, err)} + } + } + return nil +} + +func (ou *OrganizationUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := ou.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(organization.Table, organization.Columns, sqlgraph.NewFieldSpec(organization.FieldID, field.TypeString)) + if ps := ou.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ou.mutation.Name(); ok { + _spec.SetField(organization.FieldName, field.TypeString, value) + } + if value, ok := ou.mutation.Description(); ok { + _spec.SetField(organization.FieldDescription, field.TypeString, value) + } + if ou.mutation.DescriptionCleared() { + _spec.ClearField(organization.FieldDescription, field.TypeString) + } + if n, err = sqlgraph.UpdateNodes(ctx, ou.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{organization.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + ou.mutation.done = true + return n, nil +} + +// OrganizationUpdateOne is the builder for updating a single Organization entity. +type OrganizationUpdateOne struct { + config + fields []string + hooks []Hook + mutation *OrganizationMutation +} + +// SetName sets the "name" field. +func (ouo *OrganizationUpdateOne) SetName(s string) *OrganizationUpdateOne { + ouo.mutation.SetName(s) + return ouo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (ouo *OrganizationUpdateOne) SetNillableName(s *string) *OrganizationUpdateOne { + if s != nil { + ouo.SetName(*s) + } + return ouo +} + +// SetDescription sets the "description" field. +func (ouo *OrganizationUpdateOne) SetDescription(s string) *OrganizationUpdateOne { + ouo.mutation.SetDescription(s) + return ouo +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (ouo *OrganizationUpdateOne) SetNillableDescription(s *string) *OrganizationUpdateOne { + if s != nil { + ouo.SetDescription(*s) + } + return ouo +} + +// ClearDescription clears the value of the "description" field. +func (ouo *OrganizationUpdateOne) ClearDescription() *OrganizationUpdateOne { + ouo.mutation.ClearDescription() + return ouo +} + +// Mutation returns the OrganizationMutation object of the builder. +func (ouo *OrganizationUpdateOne) Mutation() *OrganizationMutation { + return ouo.mutation +} + +// Where appends a list predicates to the OrganizationUpdate builder. +func (ouo *OrganizationUpdateOne) Where(ps ...predicate.Organization) *OrganizationUpdateOne { + ouo.mutation.Where(ps...) + return ouo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (ouo *OrganizationUpdateOne) Select(field string, fields ...string) *OrganizationUpdateOne { + ouo.fields = append([]string{field}, fields...) + return ouo +} + +// Save executes the query and returns the updated Organization entity. +func (ouo *OrganizationUpdateOne) Save(ctx context.Context) (*Organization, error) { + return withHooks(ctx, ouo.sqlSave, ouo.mutation, ouo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (ouo *OrganizationUpdateOne) SaveX(ctx context.Context) *Organization { + node, err := ouo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (ouo *OrganizationUpdateOne) Exec(ctx context.Context) error { + _, err := ouo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ouo *OrganizationUpdateOne) ExecX(ctx context.Context) { + if err := ouo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (ouo *OrganizationUpdateOne) check() error { + if v, ok := ouo.mutation.Name(); ok { + if err := organization.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Organization.name": %w`, err)} + } + } + return nil +} + +func (ouo *OrganizationUpdateOne) sqlSave(ctx context.Context) (_node *Organization, err error) { + if err := ouo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(organization.Table, organization.Columns, sqlgraph.NewFieldSpec(organization.FieldID, field.TypeString)) + id, ok := ouo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Organization.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := ouo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, organization.FieldID) + for _, f := range fields { + if !organization.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != organization.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := ouo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := ouo.mutation.Name(); ok { + _spec.SetField(organization.FieldName, field.TypeString, value) + } + if value, ok := ouo.mutation.Description(); ok { + _spec.SetField(organization.FieldDescription, field.TypeString, value) + } + if ouo.mutation.DescriptionCleared() { + _spec.ClearField(organization.FieldDescription, field.TypeString) + } + _node = &Organization{config: ouo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, ouo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{organization.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + ouo.mutation.done = true + return _node, nil +} diff --git a/entfga/_examples/basic/ent/orgmembership.go b/entfga/_examples/basic/ent/orgmembership.go new file mode 100644 index 0000000..6ac4031 --- /dev/null +++ b/entfga/_examples/basic/ent/orgmembership.go @@ -0,0 +1,155 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" +) + +// OrgMembership is the model entity for the OrgMembership schema. +type OrgMembership struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // Role holds the value of the "role" field. + Role enums.Role `json:"role,omitempty"` + // OrganizationID holds the value of the "organization_id" field. + OrganizationID string `json:"organization_id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID string `json:"user_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the OrgMembershipQuery when eager-loading is set. + Edges OrgMembershipEdges `json:"edges"` + selectValues sql.SelectValues +} + +// OrgMembershipEdges holds the relations/edges for other nodes in the graph. +type OrgMembershipEdges struct { + // Organization holds the value of the organization edge. + Organization *Organization `json:"organization,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool + // totalCount holds the count of the edges above. + totalCount [1]map[string]int +} + +// OrganizationOrErr returns the Organization value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e OrgMembershipEdges) OrganizationOrErr() (*Organization, error) { + if e.Organization != nil { + return e.Organization, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: organization.Label} + } + return nil, &NotLoadedError{edge: "organization"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*OrgMembership) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case orgmembership.FieldID, orgmembership.FieldRole, orgmembership.FieldOrganizationID, orgmembership.FieldUserID: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the OrgMembership fields. +func (om *OrgMembership) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case orgmembership.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + om.ID = value.String + } + case orgmembership.FieldRole: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field role", values[i]) + } else if value.Valid { + om.Role = enums.Role(value.String) + } + case orgmembership.FieldOrganizationID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field organization_id", values[i]) + } else if value.Valid { + om.OrganizationID = value.String + } + case orgmembership.FieldUserID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + om.UserID = value.String + } + default: + om.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the OrgMembership. +// This includes values selected through modifiers, order, etc. +func (om *OrgMembership) Value(name string) (ent.Value, error) { + return om.selectValues.Get(name) +} + +// QueryOrganization queries the "organization" edge of the OrgMembership entity. +func (om *OrgMembership) QueryOrganization() *OrganizationQuery { + return NewOrgMembershipClient(om.config).QueryOrganization(om) +} + +// Update returns a builder for updating this OrgMembership. +// Note that you need to call OrgMembership.Unwrap() before calling this method if this OrgMembership +// was returned from a transaction, and the transaction was committed or rolled back. +func (om *OrgMembership) Update() *OrgMembershipUpdateOne { + return NewOrgMembershipClient(om.config).UpdateOne(om) +} + +// Unwrap unwraps the OrgMembership entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (om *OrgMembership) Unwrap() *OrgMembership { + _tx, ok := om.config.driver.(*txDriver) + if !ok { + panic("ent: OrgMembership is not a transactional entity") + } + om.config.driver = _tx.drv + return om +} + +// String implements the fmt.Stringer. +func (om *OrgMembership) String() string { + var builder strings.Builder + builder.WriteString("OrgMembership(") + builder.WriteString(fmt.Sprintf("id=%v, ", om.ID)) + builder.WriteString("role=") + builder.WriteString(fmt.Sprintf("%v", om.Role)) + builder.WriteString(", ") + builder.WriteString("organization_id=") + builder.WriteString(om.OrganizationID) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(om.UserID) + builder.WriteByte(')') + return builder.String() +} + +// OrgMemberships is a parsable slice of OrgMembership. +type OrgMemberships []*OrgMembership diff --git a/entfga/_examples/basic/ent/orgmembership/orgmembership.go b/entfga/_examples/basic/ent/orgmembership/orgmembership.go new file mode 100644 index 0000000..e13d10b --- /dev/null +++ b/entfga/_examples/basic/ent/orgmembership/orgmembership.go @@ -0,0 +1,121 @@ +// Code generated by ent, DO NOT EDIT. + +package orgmembership + +import ( + "fmt" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/99designs/gqlgen/graphql" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums" +) + +const ( + // Label holds the string label denoting the orgmembership type in the database. + Label = "org_membership" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldRole holds the string denoting the role field in the database. + FieldRole = "role" + // FieldOrganizationID holds the string denoting the organization_id field in the database. + FieldOrganizationID = "organization_id" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // EdgeOrganization holds the string denoting the organization edge name in mutations. + EdgeOrganization = "organization" + // Table holds the table name of the orgmembership in the database. + Table = "org_memberships" + // OrganizationTable is the table that holds the organization relation/edge. + OrganizationTable = "org_memberships" + // OrganizationInverseTable is the table name for the Organization entity. + // It exists in this package in order to avoid circular dependency with the "organization" package. + OrganizationInverseTable = "organizations" + // OrganizationColumn is the table column denoting the organization relation/edge. + OrganizationColumn = "organization_id" +) + +// Columns holds all SQL columns for orgmembership fields. +var Columns = []string{ + FieldID, + FieldRole, + FieldOrganizationID, + FieldUserID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +// Note that the variables below are initialized by the runtime +// package on the initialization of the application. Therefore, +// it should be imported in the main as follows: +// +// import _ "github.com/theopenlane/iam/entfga/_examples/basic/ent/runtime" +var ( + Hooks [1]ent.Hook + Policy ent.Policy +) + +const DefaultRole enums.Role = "MEMBER" + +// RoleValidator is a validator for the "role" field enum values. It is called by the builders before save. +func RoleValidator(r enums.Role) error { + switch r.String() { + case "ADMIN", "MEMBER", "OWNER": + return nil + default: + return fmt.Errorf("orgmembership: invalid enum value for role field: %q", r) + } +} + +// OrderOption defines the ordering options for the OrgMembership queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByRole orders the results by the role field. +func ByRole(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRole, opts...).ToFunc() +} + +// ByOrganizationID orders the results by the organization_id field. +func ByOrganizationID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOrganizationID, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByOrganizationField orders the results by organization field. +func ByOrganizationField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newOrganizationStep(), sql.OrderByField(field, opts...)) + } +} +func newOrganizationStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(OrganizationInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, OrganizationTable, OrganizationColumn), + ) +} + +var ( + // enums.Role must implement graphql.Marshaler. + _ graphql.Marshaler = (*enums.Role)(nil) + // enums.Role must implement graphql.Unmarshaler. + _ graphql.Unmarshaler = (*enums.Role)(nil) +) diff --git a/entfga/_examples/basic/ent/orgmembership/where.go b/entfga/_examples/basic/ent/orgmembership/where.go new file mode 100644 index 0000000..3bed29b --- /dev/null +++ b/entfga/_examples/basic/ent/orgmembership/where.go @@ -0,0 +1,273 @@ +// Code generated by ent, DO NOT EDIT. + +package orgmembership + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldContainsFold(FieldID, id)) +} + +// OrganizationID applies equality check predicate on the "organization_id" field. It's identical to OrganizationIDEQ. +func OrganizationID(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldEQ(FieldOrganizationID, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldEQ(FieldUserID, v)) +} + +// RoleEQ applies the EQ predicate on the "role" field. +func RoleEQ(v enums.Role) predicate.OrgMembership { + vc := v + return predicate.OrgMembership(sql.FieldEQ(FieldRole, vc)) +} + +// RoleNEQ applies the NEQ predicate on the "role" field. +func RoleNEQ(v enums.Role) predicate.OrgMembership { + vc := v + return predicate.OrgMembership(sql.FieldNEQ(FieldRole, vc)) +} + +// RoleIn applies the In predicate on the "role" field. +func RoleIn(vs ...enums.Role) predicate.OrgMembership { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.OrgMembership(sql.FieldIn(FieldRole, v...)) +} + +// RoleNotIn applies the NotIn predicate on the "role" field. +func RoleNotIn(vs ...enums.Role) predicate.OrgMembership { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.OrgMembership(sql.FieldNotIn(FieldRole, v...)) +} + +// OrganizationIDEQ applies the EQ predicate on the "organization_id" field. +func OrganizationIDEQ(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldEQ(FieldOrganizationID, v)) +} + +// OrganizationIDNEQ applies the NEQ predicate on the "organization_id" field. +func OrganizationIDNEQ(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldNEQ(FieldOrganizationID, v)) +} + +// OrganizationIDIn applies the In predicate on the "organization_id" field. +func OrganizationIDIn(vs ...string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldIn(FieldOrganizationID, vs...)) +} + +// OrganizationIDNotIn applies the NotIn predicate on the "organization_id" field. +func OrganizationIDNotIn(vs ...string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldNotIn(FieldOrganizationID, vs...)) +} + +// OrganizationIDGT applies the GT predicate on the "organization_id" field. +func OrganizationIDGT(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldGT(FieldOrganizationID, v)) +} + +// OrganizationIDGTE applies the GTE predicate on the "organization_id" field. +func OrganizationIDGTE(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldGTE(FieldOrganizationID, v)) +} + +// OrganizationIDLT applies the LT predicate on the "organization_id" field. +func OrganizationIDLT(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldLT(FieldOrganizationID, v)) +} + +// OrganizationIDLTE applies the LTE predicate on the "organization_id" field. +func OrganizationIDLTE(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldLTE(FieldOrganizationID, v)) +} + +// OrganizationIDContains applies the Contains predicate on the "organization_id" field. +func OrganizationIDContains(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldContains(FieldOrganizationID, v)) +} + +// OrganizationIDHasPrefix applies the HasPrefix predicate on the "organization_id" field. +func OrganizationIDHasPrefix(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldHasPrefix(FieldOrganizationID, v)) +} + +// OrganizationIDHasSuffix applies the HasSuffix predicate on the "organization_id" field. +func OrganizationIDHasSuffix(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldHasSuffix(FieldOrganizationID, v)) +} + +// OrganizationIDEqualFold applies the EqualFold predicate on the "organization_id" field. +func OrganizationIDEqualFold(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldEqualFold(FieldOrganizationID, v)) +} + +// OrganizationIDContainsFold applies the ContainsFold predicate on the "organization_id" field. +func OrganizationIDContainsFold(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldContainsFold(FieldOrganizationID, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldGT(FieldUserID, v)) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldGTE(FieldUserID, v)) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldLT(FieldUserID, v)) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldLTE(FieldUserID, v)) +} + +// UserIDContains applies the Contains predicate on the "user_id" field. +func UserIDContains(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldContains(FieldUserID, v)) +} + +// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field. +func UserIDHasPrefix(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldHasPrefix(FieldUserID, v)) +} + +// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field. +func UserIDHasSuffix(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldHasSuffix(FieldUserID, v)) +} + +// UserIDEqualFold applies the EqualFold predicate on the "user_id" field. +func UserIDEqualFold(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldEqualFold(FieldUserID, v)) +} + +// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field. +func UserIDContainsFold(v string) predicate.OrgMembership { + return predicate.OrgMembership(sql.FieldContainsFold(FieldUserID, v)) +} + +// HasOrganization applies the HasEdge predicate on the "organization" edge. +func HasOrganization() predicate.OrgMembership { + return predicate.OrgMembership(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, OrganizationTable, OrganizationColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasOrganizationWith applies the HasEdge predicate on the "organization" edge with a given conditions (other predicates). +func HasOrganizationWith(preds ...predicate.Organization) predicate.OrgMembership { + return predicate.OrgMembership(func(s *sql.Selector) { + step := newOrganizationStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.OrgMembership) predicate.OrgMembership { + return predicate.OrgMembership(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.OrgMembership) predicate.OrgMembership { + return predicate.OrgMembership(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.OrgMembership) predicate.OrgMembership { + return predicate.OrgMembership(sql.NotPredicates(p)) +} diff --git a/entfga/_examples/basic/ent/orgmembership_create.go b/entfga/_examples/basic/ent/orgmembership_create.go new file mode 100644 index 0000000..4c6c69b --- /dev/null +++ b/entfga/_examples/basic/ent/orgmembership_create.go @@ -0,0 +1,269 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" +) + +// OrgMembershipCreate is the builder for creating a OrgMembership entity. +type OrgMembershipCreate struct { + config + mutation *OrgMembershipMutation + hooks []Hook +} + +// SetRole sets the "role" field. +func (omc *OrgMembershipCreate) SetRole(e enums.Role) *OrgMembershipCreate { + omc.mutation.SetRole(e) + return omc +} + +// SetNillableRole sets the "role" field if the given value is not nil. +func (omc *OrgMembershipCreate) SetNillableRole(e *enums.Role) *OrgMembershipCreate { + if e != nil { + omc.SetRole(*e) + } + return omc +} + +// SetOrganizationID sets the "organization_id" field. +func (omc *OrgMembershipCreate) SetOrganizationID(s string) *OrgMembershipCreate { + omc.mutation.SetOrganizationID(s) + return omc +} + +// SetUserID sets the "user_id" field. +func (omc *OrgMembershipCreate) SetUserID(s string) *OrgMembershipCreate { + omc.mutation.SetUserID(s) + return omc +} + +// SetID sets the "id" field. +func (omc *OrgMembershipCreate) SetID(s string) *OrgMembershipCreate { + omc.mutation.SetID(s) + return omc +} + +// SetOrganization sets the "organization" edge to the Organization entity. +func (omc *OrgMembershipCreate) SetOrganization(o *Organization) *OrgMembershipCreate { + return omc.SetOrganizationID(o.ID) +} + +// Mutation returns the OrgMembershipMutation object of the builder. +func (omc *OrgMembershipCreate) Mutation() *OrgMembershipMutation { + return omc.mutation +} + +// Save creates the OrgMembership in the database. +func (omc *OrgMembershipCreate) Save(ctx context.Context) (*OrgMembership, error) { + if err := omc.defaults(); err != nil { + return nil, err + } + return withHooks(ctx, omc.sqlSave, omc.mutation, omc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (omc *OrgMembershipCreate) SaveX(ctx context.Context) *OrgMembership { + v, err := omc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (omc *OrgMembershipCreate) Exec(ctx context.Context) error { + _, err := omc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (omc *OrgMembershipCreate) ExecX(ctx context.Context) { + if err := omc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (omc *OrgMembershipCreate) defaults() error { + if _, ok := omc.mutation.Role(); !ok { + v := orgmembership.DefaultRole + omc.mutation.SetRole(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (omc *OrgMembershipCreate) check() error { + if _, ok := omc.mutation.Role(); !ok { + return &ValidationError{Name: "role", err: errors.New(`ent: missing required field "OrgMembership.role"`)} + } + if v, ok := omc.mutation.Role(); ok { + if err := orgmembership.RoleValidator(v); err != nil { + return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "OrgMembership.role": %w`, err)} + } + } + if _, ok := omc.mutation.OrganizationID(); !ok { + return &ValidationError{Name: "organization_id", err: errors.New(`ent: missing required field "OrgMembership.organization_id"`)} + } + if _, ok := omc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "OrgMembership.user_id"`)} + } + if _, ok := omc.mutation.OrganizationID(); !ok { + return &ValidationError{Name: "organization", err: errors.New(`ent: missing required edge "OrgMembership.organization"`)} + } + return nil +} + +func (omc *OrgMembershipCreate) sqlSave(ctx context.Context) (*OrgMembership, error) { + if err := omc.check(); err != nil { + return nil, err + } + _node, _spec := omc.createSpec() + if err := sqlgraph.CreateNode(ctx, omc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected OrgMembership.ID type: %T", _spec.ID.Value) + } + } + omc.mutation.id = &_node.ID + omc.mutation.done = true + return _node, nil +} + +func (omc *OrgMembershipCreate) createSpec() (*OrgMembership, *sqlgraph.CreateSpec) { + var ( + _node = &OrgMembership{config: omc.config} + _spec = sqlgraph.NewCreateSpec(orgmembership.Table, sqlgraph.NewFieldSpec(orgmembership.FieldID, field.TypeString)) + ) + if id, ok := omc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := omc.mutation.Role(); ok { + _spec.SetField(orgmembership.FieldRole, field.TypeEnum, value) + _node.Role = value + } + if value, ok := omc.mutation.UserID(); ok { + _spec.SetField(orgmembership.FieldUserID, field.TypeString, value) + _node.UserID = value + } + if nodes := omc.mutation.OrganizationIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: orgmembership.OrganizationTable, + Columns: []string{orgmembership.OrganizationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(organization.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.OrganizationID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OrgMembershipCreateBulk is the builder for creating many OrgMembership entities in bulk. +type OrgMembershipCreateBulk struct { + config + err error + builders []*OrgMembershipCreate +} + +// Save creates the OrgMembership entities in the database. +func (omcb *OrgMembershipCreateBulk) Save(ctx context.Context) ([]*OrgMembership, error) { + if omcb.err != nil { + return nil, omcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(omcb.builders)) + nodes := make([]*OrgMembership, len(omcb.builders)) + mutators := make([]Mutator, len(omcb.builders)) + for i := range omcb.builders { + func(i int, root context.Context) { + builder := omcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*OrgMembershipMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, omcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, omcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, omcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (omcb *OrgMembershipCreateBulk) SaveX(ctx context.Context) []*OrgMembership { + v, err := omcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (omcb *OrgMembershipCreateBulk) Exec(ctx context.Context) error { + _, err := omcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (omcb *OrgMembershipCreateBulk) ExecX(ctx context.Context) { + if err := omcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entfga/_examples/basic/ent/orgmembership_delete.go b/entfga/_examples/basic/ent/orgmembership_delete.go new file mode 100644 index 0000000..7a4e386 --- /dev/null +++ b/entfga/_examples/basic/ent/orgmembership_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/predicate" +) + +// OrgMembershipDelete is the builder for deleting a OrgMembership entity. +type OrgMembershipDelete struct { + config + hooks []Hook + mutation *OrgMembershipMutation +} + +// Where appends a list predicates to the OrgMembershipDelete builder. +func (omd *OrgMembershipDelete) Where(ps ...predicate.OrgMembership) *OrgMembershipDelete { + omd.mutation.Where(ps...) + return omd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (omd *OrgMembershipDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, omd.sqlExec, omd.mutation, omd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (omd *OrgMembershipDelete) ExecX(ctx context.Context) int { + n, err := omd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (omd *OrgMembershipDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(orgmembership.Table, sqlgraph.NewFieldSpec(orgmembership.FieldID, field.TypeString)) + if ps := omd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, omd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + omd.mutation.done = true + return affected, err +} + +// OrgMembershipDeleteOne is the builder for deleting a single OrgMembership entity. +type OrgMembershipDeleteOne struct { + omd *OrgMembershipDelete +} + +// Where appends a list predicates to the OrgMembershipDelete builder. +func (omdo *OrgMembershipDeleteOne) Where(ps ...predicate.OrgMembership) *OrgMembershipDeleteOne { + omdo.omd.mutation.Where(ps...) + return omdo +} + +// Exec executes the deletion query. +func (omdo *OrgMembershipDeleteOne) Exec(ctx context.Context) error { + n, err := omdo.omd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{orgmembership.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (omdo *OrgMembershipDeleteOne) ExecX(ctx context.Context) { + if err := omdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entfga/_examples/basic/ent/orgmembership_query.go b/entfga/_examples/basic/ent/orgmembership_query.go new file mode 100644 index 0000000..7b303c7 --- /dev/null +++ b/entfga/_examples/basic/ent/orgmembership_query.go @@ -0,0 +1,625 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "math" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/predicate" +) + +// OrgMembershipQuery is the builder for querying OrgMembership entities. +type OrgMembershipQuery struct { + config + ctx *QueryContext + order []orgmembership.OrderOption + inters []Interceptor + predicates []predicate.OrgMembership + withOrganization *OrganizationQuery + modifiers []func(*sql.Selector) + loadTotal []func(context.Context, []*OrgMembership) error + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the OrgMembershipQuery builder. +func (omq *OrgMembershipQuery) Where(ps ...predicate.OrgMembership) *OrgMembershipQuery { + omq.predicates = append(omq.predicates, ps...) + return omq +} + +// Limit the number of records to be returned by this query. +func (omq *OrgMembershipQuery) Limit(limit int) *OrgMembershipQuery { + omq.ctx.Limit = &limit + return omq +} + +// Offset to start from. +func (omq *OrgMembershipQuery) Offset(offset int) *OrgMembershipQuery { + omq.ctx.Offset = &offset + return omq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (omq *OrgMembershipQuery) Unique(unique bool) *OrgMembershipQuery { + omq.ctx.Unique = &unique + return omq +} + +// Order specifies how the records should be ordered. +func (omq *OrgMembershipQuery) Order(o ...orgmembership.OrderOption) *OrgMembershipQuery { + omq.order = append(omq.order, o...) + return omq +} + +// QueryOrganization chains the current query on the "organization" edge. +func (omq *OrgMembershipQuery) QueryOrganization() *OrganizationQuery { + query := (&OrganizationClient{config: omq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := omq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := omq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(orgmembership.Table, orgmembership.FieldID, selector), + sqlgraph.To(organization.Table, organization.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, orgmembership.OrganizationTable, orgmembership.OrganizationColumn), + ) + fromU = sqlgraph.SetNeighbors(omq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first OrgMembership entity from the query. +// Returns a *NotFoundError when no OrgMembership was found. +func (omq *OrgMembershipQuery) First(ctx context.Context) (*OrgMembership, error) { + nodes, err := omq.Limit(1).All(setContextOp(ctx, omq.ctx, "First")) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{orgmembership.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (omq *OrgMembershipQuery) FirstX(ctx context.Context) *OrgMembership { + node, err := omq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first OrgMembership ID from the query. +// Returns a *NotFoundError when no OrgMembership ID was found. +func (omq *OrgMembershipQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = omq.Limit(1).IDs(setContextOp(ctx, omq.ctx, "FirstID")); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{orgmembership.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (omq *OrgMembershipQuery) FirstIDX(ctx context.Context) string { + id, err := omq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single OrgMembership entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one OrgMembership entity is found. +// Returns a *NotFoundError when no OrgMembership entities are found. +func (omq *OrgMembershipQuery) Only(ctx context.Context) (*OrgMembership, error) { + nodes, err := omq.Limit(2).All(setContextOp(ctx, omq.ctx, "Only")) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{orgmembership.Label} + default: + return nil, &NotSingularError{orgmembership.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (omq *OrgMembershipQuery) OnlyX(ctx context.Context) *OrgMembership { + node, err := omq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only OrgMembership ID in the query. +// Returns a *NotSingularError when more than one OrgMembership ID is found. +// Returns a *NotFoundError when no entities are found. +func (omq *OrgMembershipQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = omq.Limit(2).IDs(setContextOp(ctx, omq.ctx, "OnlyID")); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{orgmembership.Label} + default: + err = &NotSingularError{orgmembership.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (omq *OrgMembershipQuery) OnlyIDX(ctx context.Context) string { + id, err := omq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of OrgMemberships. +func (omq *OrgMembershipQuery) All(ctx context.Context) ([]*OrgMembership, error) { + ctx = setContextOp(ctx, omq.ctx, "All") + if err := omq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*OrgMembership, *OrgMembershipQuery]() + return withInterceptors[[]*OrgMembership](ctx, omq, qr, omq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (omq *OrgMembershipQuery) AllX(ctx context.Context) []*OrgMembership { + nodes, err := omq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of OrgMembership IDs. +func (omq *OrgMembershipQuery) IDs(ctx context.Context) (ids []string, err error) { + if omq.ctx.Unique == nil && omq.path != nil { + omq.Unique(true) + } + ctx = setContextOp(ctx, omq.ctx, "IDs") + if err = omq.Select(orgmembership.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (omq *OrgMembershipQuery) IDsX(ctx context.Context) []string { + ids, err := omq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (omq *OrgMembershipQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, omq.ctx, "Count") + if err := omq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, omq, querierCount[*OrgMembershipQuery](), omq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (omq *OrgMembershipQuery) CountX(ctx context.Context) int { + count, err := omq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (omq *OrgMembershipQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, omq.ctx, "Exist") + switch _, err := omq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (omq *OrgMembershipQuery) ExistX(ctx context.Context) bool { + exist, err := omq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the OrgMembershipQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (omq *OrgMembershipQuery) Clone() *OrgMembershipQuery { + if omq == nil { + return nil + } + return &OrgMembershipQuery{ + config: omq.config, + ctx: omq.ctx.Clone(), + order: append([]orgmembership.OrderOption{}, omq.order...), + inters: append([]Interceptor{}, omq.inters...), + predicates: append([]predicate.OrgMembership{}, omq.predicates...), + withOrganization: omq.withOrganization.Clone(), + // clone intermediate query. + sql: omq.sql.Clone(), + path: omq.path, + } +} + +// WithOrganization tells the query-builder to eager-load the nodes that are connected to +// the "organization" edge. The optional arguments are used to configure the query builder of the edge. +func (omq *OrgMembershipQuery) WithOrganization(opts ...func(*OrganizationQuery)) *OrgMembershipQuery { + query := (&OrganizationClient{config: omq.config}).Query() + for _, opt := range opts { + opt(query) + } + omq.withOrganization = query + return omq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Role enums.Role `json:"role,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.OrgMembership.Query(). +// GroupBy(orgmembership.FieldRole). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (omq *OrgMembershipQuery) GroupBy(field string, fields ...string) *OrgMembershipGroupBy { + omq.ctx.Fields = append([]string{field}, fields...) + grbuild := &OrgMembershipGroupBy{build: omq} + grbuild.flds = &omq.ctx.Fields + grbuild.label = orgmembership.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Role enums.Role `json:"role,omitempty"` +// } +// +// client.OrgMembership.Query(). +// Select(orgmembership.FieldRole). +// Scan(ctx, &v) +func (omq *OrgMembershipQuery) Select(fields ...string) *OrgMembershipSelect { + omq.ctx.Fields = append(omq.ctx.Fields, fields...) + sbuild := &OrgMembershipSelect{OrgMembershipQuery: omq} + sbuild.label = orgmembership.Label + sbuild.flds, sbuild.scan = &omq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a OrgMembershipSelect configured with the given aggregations. +func (omq *OrgMembershipQuery) Aggregate(fns ...AggregateFunc) *OrgMembershipSelect { + return omq.Select().Aggregate(fns...) +} + +func (omq *OrgMembershipQuery) prepareQuery(ctx context.Context) error { + for _, inter := range omq.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, omq); err != nil { + return err + } + } + } + for _, f := range omq.ctx.Fields { + if !orgmembership.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if omq.path != nil { + prev, err := omq.path(ctx) + if err != nil { + return err + } + omq.sql = prev + } + if orgmembership.Policy == nil { + return errors.New("ent: uninitialized orgmembership.Policy (forgotten import ent/runtime?)") + } + if err := orgmembership.Policy.EvalQuery(ctx, omq); err != nil { + return err + } + return nil +} + +func (omq *OrgMembershipQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*OrgMembership, error) { + var ( + nodes = []*OrgMembership{} + _spec = omq.querySpec() + loadedTypes = [1]bool{ + omq.withOrganization != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*OrgMembership).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &OrgMembership{config: omq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(omq.modifiers) > 0 { + _spec.Modifiers = omq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, omq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := omq.withOrganization; query != nil { + if err := omq.loadOrganization(ctx, query, nodes, nil, + func(n *OrgMembership, e *Organization) { n.Edges.Organization = e }); err != nil { + return nil, err + } + } + for i := range omq.loadTotal { + if err := omq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (omq *OrgMembershipQuery) loadOrganization(ctx context.Context, query *OrganizationQuery, nodes []*OrgMembership, init func(*OrgMembership), assign func(*OrgMembership, *Organization)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*OrgMembership) + for i := range nodes { + fk := nodes[i].OrganizationID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(organization.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "organization_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (omq *OrgMembershipQuery) sqlCount(ctx context.Context) (int, error) { + _spec := omq.querySpec() + if len(omq.modifiers) > 0 { + _spec.Modifiers = omq.modifiers + } + _spec.Node.Columns = omq.ctx.Fields + if len(omq.ctx.Fields) > 0 { + _spec.Unique = omq.ctx.Unique != nil && *omq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, omq.driver, _spec) +} + +func (omq *OrgMembershipQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(orgmembership.Table, orgmembership.Columns, sqlgraph.NewFieldSpec(orgmembership.FieldID, field.TypeString)) + _spec.From = omq.sql + if unique := omq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if omq.path != nil { + _spec.Unique = true + } + if fields := omq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, orgmembership.FieldID) + for i := range fields { + if fields[i] != orgmembership.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if omq.withOrganization != nil { + _spec.Node.AddColumnOnce(orgmembership.FieldOrganizationID) + } + } + if ps := omq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := omq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := omq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := omq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (omq *OrgMembershipQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(omq.driver.Dialect()) + t1 := builder.Table(orgmembership.Table) + columns := omq.ctx.Fields + if len(columns) == 0 { + columns = orgmembership.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if omq.sql != nil { + selector = omq.sql + selector.Select(selector.Columns(columns...)...) + } + if omq.ctx.Unique != nil && *omq.ctx.Unique { + selector.Distinct() + } + for _, p := range omq.predicates { + p(selector) + } + for _, p := range omq.order { + p(selector) + } + if offset := omq.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := omq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// OrgMembershipGroupBy is the group-by builder for OrgMembership entities. +type OrgMembershipGroupBy struct { + selector + build *OrgMembershipQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (omgb *OrgMembershipGroupBy) Aggregate(fns ...AggregateFunc) *OrgMembershipGroupBy { + omgb.fns = append(omgb.fns, fns...) + return omgb +} + +// Scan applies the selector query and scans the result into the given value. +func (omgb *OrgMembershipGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, omgb.build.ctx, "GroupBy") + if err := omgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OrgMembershipQuery, *OrgMembershipGroupBy](ctx, omgb.build, omgb, omgb.build.inters, v) +} + +func (omgb *OrgMembershipGroupBy) sqlScan(ctx context.Context, root *OrgMembershipQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(omgb.fns)) + for _, fn := range omgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*omgb.flds)+len(omgb.fns)) + for _, f := range *omgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*omgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := omgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// OrgMembershipSelect is the builder for selecting fields of OrgMembership entities. +type OrgMembershipSelect struct { + *OrgMembershipQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (oms *OrgMembershipSelect) Aggregate(fns ...AggregateFunc) *OrgMembershipSelect { + oms.fns = append(oms.fns, fns...) + return oms +} + +// Scan applies the selector query and scans the result into the given value. +func (oms *OrgMembershipSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, oms.ctx, "Select") + if err := oms.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OrgMembershipQuery, *OrgMembershipSelect](ctx, oms.OrgMembershipQuery, oms, oms.inters, v) +} + +func (oms *OrgMembershipSelect) sqlScan(ctx context.Context, root *OrgMembershipQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(oms.fns)) + for _, fn := range oms.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*oms.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := oms.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/entfga/_examples/basic/ent/orgmembership_update.go b/entfga/_examples/basic/ent/orgmembership_update.go new file mode 100644 index 0000000..529ad58 --- /dev/null +++ b/entfga/_examples/basic/ent/orgmembership_update.go @@ -0,0 +1,242 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/predicate" +) + +// OrgMembershipUpdate is the builder for updating OrgMembership entities. +type OrgMembershipUpdate struct { + config + hooks []Hook + mutation *OrgMembershipMutation +} + +// Where appends a list predicates to the OrgMembershipUpdate builder. +func (omu *OrgMembershipUpdate) Where(ps ...predicate.OrgMembership) *OrgMembershipUpdate { + omu.mutation.Where(ps...) + return omu +} + +// SetRole sets the "role" field. +func (omu *OrgMembershipUpdate) SetRole(e enums.Role) *OrgMembershipUpdate { + omu.mutation.SetRole(e) + return omu +} + +// SetNillableRole sets the "role" field if the given value is not nil. +func (omu *OrgMembershipUpdate) SetNillableRole(e *enums.Role) *OrgMembershipUpdate { + if e != nil { + omu.SetRole(*e) + } + return omu +} + +// Mutation returns the OrgMembershipMutation object of the builder. +func (omu *OrgMembershipUpdate) Mutation() *OrgMembershipMutation { + return omu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (omu *OrgMembershipUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, omu.sqlSave, omu.mutation, omu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (omu *OrgMembershipUpdate) SaveX(ctx context.Context) int { + affected, err := omu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (omu *OrgMembershipUpdate) Exec(ctx context.Context) error { + _, err := omu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (omu *OrgMembershipUpdate) ExecX(ctx context.Context) { + if err := omu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (omu *OrgMembershipUpdate) check() error { + if v, ok := omu.mutation.Role(); ok { + if err := orgmembership.RoleValidator(v); err != nil { + return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "OrgMembership.role": %w`, err)} + } + } + if _, ok := omu.mutation.OrganizationID(); omu.mutation.OrganizationCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "OrgMembership.organization"`) + } + return nil +} + +func (omu *OrgMembershipUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := omu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(orgmembership.Table, orgmembership.Columns, sqlgraph.NewFieldSpec(orgmembership.FieldID, field.TypeString)) + if ps := omu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := omu.mutation.Role(); ok { + _spec.SetField(orgmembership.FieldRole, field.TypeEnum, value) + } + if n, err = sqlgraph.UpdateNodes(ctx, omu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{orgmembership.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + omu.mutation.done = true + return n, nil +} + +// OrgMembershipUpdateOne is the builder for updating a single OrgMembership entity. +type OrgMembershipUpdateOne struct { + config + fields []string + hooks []Hook + mutation *OrgMembershipMutation +} + +// SetRole sets the "role" field. +func (omuo *OrgMembershipUpdateOne) SetRole(e enums.Role) *OrgMembershipUpdateOne { + omuo.mutation.SetRole(e) + return omuo +} + +// SetNillableRole sets the "role" field if the given value is not nil. +func (omuo *OrgMembershipUpdateOne) SetNillableRole(e *enums.Role) *OrgMembershipUpdateOne { + if e != nil { + omuo.SetRole(*e) + } + return omuo +} + +// Mutation returns the OrgMembershipMutation object of the builder. +func (omuo *OrgMembershipUpdateOne) Mutation() *OrgMembershipMutation { + return omuo.mutation +} + +// Where appends a list predicates to the OrgMembershipUpdate builder. +func (omuo *OrgMembershipUpdateOne) Where(ps ...predicate.OrgMembership) *OrgMembershipUpdateOne { + omuo.mutation.Where(ps...) + return omuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (omuo *OrgMembershipUpdateOne) Select(field string, fields ...string) *OrgMembershipUpdateOne { + omuo.fields = append([]string{field}, fields...) + return omuo +} + +// Save executes the query and returns the updated OrgMembership entity. +func (omuo *OrgMembershipUpdateOne) Save(ctx context.Context) (*OrgMembership, error) { + return withHooks(ctx, omuo.sqlSave, omuo.mutation, omuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (omuo *OrgMembershipUpdateOne) SaveX(ctx context.Context) *OrgMembership { + node, err := omuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (omuo *OrgMembershipUpdateOne) Exec(ctx context.Context) error { + _, err := omuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (omuo *OrgMembershipUpdateOne) ExecX(ctx context.Context) { + if err := omuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (omuo *OrgMembershipUpdateOne) check() error { + if v, ok := omuo.mutation.Role(); ok { + if err := orgmembership.RoleValidator(v); err != nil { + return &ValidationError{Name: "role", err: fmt.Errorf(`ent: validator failed for field "OrgMembership.role": %w`, err)} + } + } + if _, ok := omuo.mutation.OrganizationID(); omuo.mutation.OrganizationCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "OrgMembership.organization"`) + } + return nil +} + +func (omuo *OrgMembershipUpdateOne) sqlSave(ctx context.Context) (_node *OrgMembership, err error) { + if err := omuo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(orgmembership.Table, orgmembership.Columns, sqlgraph.NewFieldSpec(orgmembership.FieldID, field.TypeString)) + id, ok := omuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "OrgMembership.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := omuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, orgmembership.FieldID) + for _, f := range fields { + if !orgmembership.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != orgmembership.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := omuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := omuo.mutation.Role(); ok { + _spec.SetField(orgmembership.FieldRole, field.TypeEnum, value) + } + _node = &OrgMembership{config: omuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, omuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{orgmembership.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + omuo.mutation.done = true + return _node, nil +} diff --git a/entfga/_examples/basic/ent/predicate/predicate.go b/entfga/_examples/basic/ent/predicate/predicate.go new file mode 100644 index 0000000..8ba1068 --- /dev/null +++ b/entfga/_examples/basic/ent/predicate/predicate.go @@ -0,0 +1,13 @@ +// Code generated by ent, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// OrgMembership is the predicate function for orgmembership builders. +type OrgMembership func(*sql.Selector) + +// Organization is the predicate function for organization builders. +type Organization func(*sql.Selector) diff --git a/entfga/_examples/basic/ent/privacy/privacy.go b/entfga/_examples/basic/ent/privacy/privacy.go new file mode 100644 index 0000000..9d4cb17 --- /dev/null +++ b/entfga/_examples/basic/ent/privacy/privacy.go @@ -0,0 +1,159 @@ +// Code generated by ent, DO NOT EDIT. + +package privacy + +import ( + "context" + + "github.com/theopenlane/iam/entfga/_examples/basic/ent" + + "entgo.io/ent/privacy" +) + +var ( + // Allow may be returned by rules to indicate that the policy + // evaluation should terminate with allow decision. + Allow = privacy.Allow + + // Deny may be returned by rules to indicate that the policy + // evaluation should terminate with deny decision. + Deny = privacy.Deny + + // Skip may be returned by rules to indicate that the policy + // evaluation should continue to the next rule. + Skip = privacy.Skip +) + +// Allowf returns a formatted wrapped Allow decision. +func Allowf(format string, a ...any) error { + return privacy.Allowf(format, a...) +} + +// Denyf returns a formatted wrapped Deny decision. +func Denyf(format string, a ...any) error { + return privacy.Denyf(format, a...) +} + +// Skipf returns a formatted wrapped Skip decision. +func Skipf(format string, a ...any) error { + return privacy.Skipf(format, a...) +} + +// DecisionContext creates a new context from the given parent context with +// a policy decision attach to it. +func DecisionContext(parent context.Context, decision error) context.Context { + return privacy.DecisionContext(parent, decision) +} + +// DecisionFromContext retrieves the policy decision from the context. +func DecisionFromContext(ctx context.Context) (error, bool) { + return privacy.DecisionFromContext(ctx) +} + +type ( + // Policy groups query and mutation policies. + Policy = privacy.Policy + + // QueryRule defines the interface deciding whether a + // query is allowed and optionally modify it. + QueryRule = privacy.QueryRule + // QueryPolicy combines multiple query rules into a single policy. + QueryPolicy = privacy.QueryPolicy + + // MutationRule defines the interface which decides whether a + // mutation is allowed and optionally modifies it. + MutationRule = privacy.MutationRule + // MutationPolicy combines multiple mutation rules into a single policy. + MutationPolicy = privacy.MutationPolicy + // MutationRuleFunc type is an adapter which allows the use of + // ordinary functions as mutation rules. + MutationRuleFunc = privacy.MutationRuleFunc + + // QueryMutationRule is an interface which groups query and mutation rules. + QueryMutationRule = privacy.QueryMutationRule +) + +// QueryRuleFunc type is an adapter to allow the use of +// ordinary functions as query rules. +type QueryRuleFunc func(context.Context, ent.Query) error + +// Eval returns f(ctx, q). +func (f QueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { + return f(ctx, q) +} + +// AlwaysAllowRule returns a rule that returns an allow decision. +func AlwaysAllowRule() QueryMutationRule { + return privacy.AlwaysAllowRule() +} + +// AlwaysDenyRule returns a rule that returns a deny decision. +func AlwaysDenyRule() QueryMutationRule { + return privacy.AlwaysDenyRule() +} + +// ContextQueryMutationRule creates a query/mutation rule from a context eval func. +func ContextQueryMutationRule(eval func(context.Context) error) QueryMutationRule { + return privacy.ContextQueryMutationRule(eval) +} + +// OnMutationOperation evaluates the given rule only on a given mutation operation. +func OnMutationOperation(rule MutationRule, op ent.Op) MutationRule { + return privacy.OnMutationOperation(rule, op) +} + +// DenyMutationOperationRule returns a rule denying specified mutation operation. +func DenyMutationOperationRule(op ent.Op) MutationRule { + rule := MutationRuleFunc(func(_ context.Context, m ent.Mutation) error { + return Denyf("ent/privacy: operation %s is not allowed", m.Op()) + }) + return OnMutationOperation(rule, op) +} + +// The OrgMembershipQueryRuleFunc type is an adapter to allow the use of ordinary +// functions as a query rule. +type OrgMembershipQueryRuleFunc func(context.Context, *ent.OrgMembershipQuery) error + +// EvalQuery return f(ctx, q). +func (f OrgMembershipQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.OrgMembershipQuery); ok { + return f(ctx, q) + } + return Denyf("ent/privacy: unexpected query type %T, expect *ent.OrgMembershipQuery", q) +} + +// The OrgMembershipMutationRuleFunc type is an adapter to allow the use of ordinary +// functions as a mutation rule. +type OrgMembershipMutationRuleFunc func(context.Context, *ent.OrgMembershipMutation) error + +// EvalMutation calls f(ctx, m). +func (f OrgMembershipMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { + if m, ok := m.(*ent.OrgMembershipMutation); ok { + return f(ctx, m) + } + return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.OrgMembershipMutation", m) +} + +// The OrganizationQueryRuleFunc type is an adapter to allow the use of ordinary +// functions as a query rule. +type OrganizationQueryRuleFunc func(context.Context, *ent.OrganizationQuery) error + +// EvalQuery return f(ctx, q). +func (f OrganizationQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { + if q, ok := q.(*ent.OrganizationQuery); ok { + return f(ctx, q) + } + return Denyf("ent/privacy: unexpected query type %T, expect *ent.OrganizationQuery", q) +} + +// The OrganizationMutationRuleFunc type is an adapter to allow the use of ordinary +// functions as a mutation rule. +type OrganizationMutationRuleFunc func(context.Context, *ent.OrganizationMutation) error + +// EvalMutation calls f(ctx, m). +func (f OrganizationMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { + if m, ok := m.(*ent.OrganizationMutation); ok { + return f(ctx, m) + } + return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.OrganizationMutation", m) +} diff --git a/entfga/_examples/basic/ent/runtime.go b/entfga/_examples/basic/ent/runtime.go new file mode 100644 index 0000000..25ecbfb --- /dev/null +++ b/entfga/_examples/basic/ent/runtime.go @@ -0,0 +1,5 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +// The schema-stitching logic is generated in github.com/theopenlane/iam/entfga/_examples/basic/ent/runtime/runtime.go diff --git a/entfga/_examples/basic/ent/runtime/runtime.go b/entfga/_examples/basic/ent/runtime/runtime.go new file mode 100644 index 0000000..657660f --- /dev/null +++ b/entfga/_examples/basic/ent/runtime/runtime.go @@ -0,0 +1,51 @@ +// Code generated by ent, DO NOT EDIT. + +package runtime + +import ( + "context" + + "github.com/theopenlane/iam/entfga/_examples/basic/ent/organization" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/orgmembership" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/schema" + + "entgo.io/ent" + "entgo.io/ent/privacy" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + orgmembership.Policy = privacy.NewPolicies(schema.OrgMembership{}) + orgmembership.Hooks[0] = func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if err := orgmembership.Policy.EvalMutation(ctx, m); err != nil { + return nil, err + } + return next.Mutate(ctx, m) + }) + } + orgmembershipFields := schema.OrgMembership{}.Fields() + _ = orgmembershipFields + organization.Policy = privacy.NewPolicies(schema.Organization{}) + organization.Hooks[0] = func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if err := organization.Policy.EvalMutation(ctx, m); err != nil { + return nil, err + } + return next.Mutate(ctx, m) + }) + } + organizationFields := schema.Organization{}.Fields() + _ = organizationFields + // organizationDescName is the schema descriptor for name field. + organizationDescName := organizationFields[1].Descriptor() + // organization.NameValidator is a validator for the "name" field. It is called by the builders before save. + organization.NameValidator = organizationDescName.Validators[0].(func(string) error) +} + +const ( + Version = "v0.13.1" // Version of ent codegen. + Sum = "h1:uD8QwN1h6SNphdCCzmkMN3feSUzNnVvV/WIkHKMbzOE=" // Sum of ent codegen. +) diff --git a/entfga/_examples/basic/ent/schema/organization.go b/entfga/_examples/basic/ent/schema/organization.go new file mode 100644 index 0000000..843cb40 --- /dev/null +++ b/entfga/_examples/basic/ent/schema/organization.go @@ -0,0 +1,64 @@ +package schema + +import ( + "context" + + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/theopenlane/iam/entfga" + + generated "github.com/theopenlane/iam/entfga/_examples/basic/ent" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/privacy" +) + +// Organization holds the schema definition for the Organization entity +type Organization struct { + ent.Schema +} + +// Fields of the Organization +func (Organization) Fields() []ent.Field { + return []ent.Field{ + field.String("id"). + Immutable(), + field.String("name"). + Comment("the name of the organization"). + NotEmpty(), + field.String("description"). + Comment("An optional description of the organization"). + Optional(), + } +} + +func (Organization) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("name"). + Unique(), + } +} + +// Annotations of the Organization +func (Organization) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.Mutations(entgql.MutationCreate(), entgql.MutationUpdate()), + entfga.Annotations{ + ObjectType: "organization", + IncludeHooks: false, + }, + } +} + +// Policy defines the privacy policy of the Organization. +func (Organization) Policy() ent.Policy { + return privacy.Policy{ + Query: privacy.QueryPolicy{ + privacy.OrganizationQueryRuleFunc(func(ctx context.Context, q *generated.OrganizationQuery) error { + return q.CheckAccess(ctx) + }), + privacy.AlwaysDenyRule(), // Deny all other users + }, + } +} diff --git a/entfga/_examples/basic/ent/schema/organization_members.go b/entfga/_examples/basic/ent/schema/organization_members.go new file mode 100644 index 0000000..8568aa7 --- /dev/null +++ b/entfga/_examples/basic/ent/schema/organization_members.go @@ -0,0 +1,85 @@ +package schema + +import ( + "context" + + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/theopenlane/iam/entfga" + + generated "github.com/theopenlane/iam/entfga/_examples/basic/ent" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/privacy" +) + +// OrgMembership holds the schema definition for the OrgMembership entity +type OrgMembership struct { + ent.Schema +} + +// Fields of the OrgMembership +func (OrgMembership) Fields() []ent.Field { + return []ent.Field{ + field.String("id"). + Immutable(), + field.Enum("role"). + GoType(enums.Role("")). + Default(string(enums.RoleMember)). + Values(string(enums.RoleOwner)), // adds owner to possible values + field.String("organization_id").Immutable(), + field.String("user_id").Immutable(), + } +} + +// Edges of the OrgMembership +func (OrgMembership) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("organization", Organization.Type). + Field("organization_id"). + Required(). + Unique(). + Immutable(), + } +} + +// Annotations of the OrgMembership +func (OrgMembership) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.Mutations(entgql.MutationCreate(), entgql.MutationUpdate()), + entfga.Annotations{ + ObjectType: "organization", + IncludeHooks: true, + OrgOwnedField: true, + IDField: "OrganizationID", + }, + } +} + +func (OrgMembership) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("user_id", "organization_id"). + Unique(), + } +} + +// Policy of the OrgMembership +func (OrgMembership) Policy() ent.Policy { + return privacy.Policy{ + Mutation: privacy.MutationPolicy{ + privacy.OrgMembershipMutationRuleFunc(func(ctx context.Context, m *generated.OrgMembershipMutation) error { + return m.CheckAccessForEdit(ctx) + }), + privacy.AlwaysDenyRule(), + }, + Query: privacy.QueryPolicy{ + privacy.OrgMembershipQueryRuleFunc(func(ctx context.Context, q *generated.OrgMembershipQuery) error { + return q.CheckAccess(ctx) + }), + privacy.AlwaysDenyRule(), + }, + } +} diff --git a/entfga/_examples/basic/ent/tx.go b/entfga/_examples/basic/ent/tx.go new file mode 100644 index 0000000..35ea623 --- /dev/null +++ b/entfga/_examples/basic/ent/tx.go @@ -0,0 +1,213 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // OrgMembership is the client for interacting with the OrgMembership builders. + OrgMembership *OrgMembershipClient + // Organization is the client for interacting with the Organization builders. + Organization *OrganizationClient + + // lazily loaded. + client *Client + clientOnce sync.Once + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.OrgMembership = NewOrgMembershipClient(tx.config) + tx.Organization = NewOrganizationClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: OrgMembership.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/entfga/_examples/basic/gen_schema.go b/entfga/_examples/basic/gen_schema.go new file mode 100644 index 0000000..ee0ae72 --- /dev/null +++ b/entfga/_examples/basic/gen_schema.go @@ -0,0 +1,26 @@ +//go:build ignore + +package main + +import ( + "log" + "os" + + "github.com/theopenlane/iam/entfga/_examples/basic/graphapi" + "github.com/vektah/gqlparser/v2/formatter" +) + +// read in schema from internal package and save it to the schema file +func main() { + execSchema := graphapi.NewExecutableSchema(graphapi.Config{}) + schema := execSchema.Schema() + + f, err := os.Create("schema.graphql") + if err != nil { + log.Fatal(err) + } + defer f.Close() + fmtr := formatter.NewFormatter(f) + + fmtr.FormatSchema(schema) +} diff --git a/entfga/_examples/basic/gqlgen.yml b/entfga/_examples/basic/gqlgen.yml new file mode 100644 index 0000000..857d194 --- /dev/null +++ b/entfga/_examples/basic/gqlgen.yml @@ -0,0 +1,74 @@ +# Where are all the schema files located? globs are supported eg src/**/*.graphqls +schema: + - schema/*.graphql + +# Where should the generated server code go? +exec: + filename: graphapi/gen_server.go + package: graphapi + +# # Uncomment to enable federation +# federation: +# filename: internal/graphapi/federation.go +# package: graphapi + +# Where should any generated models go? +model: + filename: graphapi/gen_models.go + package: graphapi + + +# Optional: turn on use ` + "`" + `gqlgen:"fieldName"` + "`" + ` tags in your models +# struct_tag: json + +# Optional: turn on to use []Thing instead of []*Thing +# omit_slice_element_pointers: false + +# Optional: turn on to omit Is() methods to interface and unions +# omit_interface_checks : true + +# Optional: turn on to skip generation of ComplexityRoot struct content and Complexity function +# omit_complexity: false + +# Optional: turn on to not generate any file notice comments in generated files +# omit_gqlgen_file_notice: false + +# Optional: turn on to exclude the gqlgen version in the generated file notice. No effect if `omit_gqlgen_file_notice` is true. +omit_gqlgen_version_in_file_notice: true + +# Optional: turn off to make struct-type struct fields not use pointers +# e.g. type Thing struct { FieldA OtherThing } instead of { FieldA *OtherThing } +# struct_fields_always_pointers: true + +# Optional: turn off to make resolvers return values instead of pointers for structs +# resolvers_always_return_pointers: true + +# Optional: turn on to return pointers instead of values in unmarshalInput +# return_pointers_in_unmarshalinput: false + +# Optional: wrap nullable input fields with Omittable +# nullable_input_omittable: true + +# Optional: set to speed up generation time by not performing a final validation pass. +# skip_validation: true + +# Optional: set to skip running `go mod tidy` when generating server code +# skip_mod_tidy: true + +# gqlgen will search for any type names in the schema in these go packages +# if they match it will use them, otherwise it will generate them. +autobind: + - "github.com/theopenlane/iam/entfga/_examples/basic/ent" + +# This section declares type mapping between the GraphQL and go type systems +# +# The first line in each type will be used as defaults for resolver arguments and +# modelgen, the others will be allowed when binding to fields. Configure them to +# your liking +models: + ID: + model: + - github.com/99designs/gqlgen/graphql.String + Node: + model: + - github.com/theopenlane/iam/entfga/_examples/basic/ent.Noder diff --git a/entfga/_examples/basic/graphapi/gen_server.go b/entfga/_examples/basic/graphapi/gen_server.go new file mode 100644 index 0000000..ba825d3 --- /dev/null +++ b/entfga/_examples/basic/graphapi/gen_server.go @@ -0,0 +1,5516 @@ +// Code generated by github.com/99designs/gqlgen, DO NOT EDIT. + +package graphapi + +import ( + "bytes" + "context" + "errors" + "fmt" + "strconv" + "sync" + "sync/atomic" + + "entgo.io/contrib/entgql" + "github.com/99designs/gqlgen/graphql" + "github.com/99designs/gqlgen/graphql/introspection" + "github.com/theopenlane/iam/entfga/_examples/basic/ent" + "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums" + gqlparser "github.com/vektah/gqlparser/v2" + "github.com/vektah/gqlparser/v2/ast" +) + +// region ************************** generated!.gotpl ************************** + +// NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface. +func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { + return &executableSchema{ + schema: cfg.Schema, + resolvers: cfg.Resolvers, + directives: cfg.Directives, + complexity: cfg.Complexity, + } +} + +type Config struct { + Schema *ast.Schema + Resolvers ResolverRoot + Directives DirectiveRoot + Complexity ComplexityRoot +} + +type ResolverRoot interface { + Query() QueryResolver +} + +type DirectiveRoot struct { +} + +type ComplexityRoot struct { + OrgMembership struct { + ID func(childComplexity int) int + Organization func(childComplexity int) int + OrganizationID func(childComplexity int) int + Role func(childComplexity int) int + UserID func(childComplexity int) int + } + + Organization struct { + Description func(childComplexity int) int + ID func(childComplexity int) int + Name func(childComplexity int) int + } + + PageInfo struct { + EndCursor func(childComplexity int) int + HasNextPage func(childComplexity int) int + HasPreviousPage func(childComplexity int) int + StartCursor func(childComplexity int) int + } + + Query struct { + Node func(childComplexity int, id string) int + Nodes func(childComplexity int, ids []string) int + } +} + +type QueryResolver interface { + Node(ctx context.Context, id string) (ent.Noder, error) + Nodes(ctx context.Context, ids []string) ([]ent.Noder, error) +} + +type executableSchema struct { + schema *ast.Schema + resolvers ResolverRoot + directives DirectiveRoot + complexity ComplexityRoot +} + +func (e *executableSchema) Schema() *ast.Schema { + if e.schema != nil { + return e.schema + } + return parsedSchema +} + +func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]interface{}) (int, bool) { + ec := executionContext{nil, e, 0, 0, nil} + _ = ec + switch typeName + "." + field { + + case "OrgMembership.id": + if e.complexity.OrgMembership.ID == nil { + break + } + + return e.complexity.OrgMembership.ID(childComplexity), true + + case "OrgMembership.organization": + if e.complexity.OrgMembership.Organization == nil { + break + } + + return e.complexity.OrgMembership.Organization(childComplexity), true + + case "OrgMembership.organizationID": + if e.complexity.OrgMembership.OrganizationID == nil { + break + } + + return e.complexity.OrgMembership.OrganizationID(childComplexity), true + + case "OrgMembership.role": + if e.complexity.OrgMembership.Role == nil { + break + } + + return e.complexity.OrgMembership.Role(childComplexity), true + + case "OrgMembership.userID": + if e.complexity.OrgMembership.UserID == nil { + break + } + + return e.complexity.OrgMembership.UserID(childComplexity), true + + case "Organization.description": + if e.complexity.Organization.Description == nil { + break + } + + return e.complexity.Organization.Description(childComplexity), true + + case "Organization.id": + if e.complexity.Organization.ID == nil { + break + } + + return e.complexity.Organization.ID(childComplexity), true + + case "Organization.name": + if e.complexity.Organization.Name == nil { + break + } + + return e.complexity.Organization.Name(childComplexity), true + + case "PageInfo.endCursor": + if e.complexity.PageInfo.EndCursor == nil { + break + } + + return e.complexity.PageInfo.EndCursor(childComplexity), true + + case "PageInfo.hasNextPage": + if e.complexity.PageInfo.HasNextPage == nil { + break + } + + return e.complexity.PageInfo.HasNextPage(childComplexity), true + + case "PageInfo.hasPreviousPage": + if e.complexity.PageInfo.HasPreviousPage == nil { + break + } + + return e.complexity.PageInfo.HasPreviousPage(childComplexity), true + + case "PageInfo.startCursor": + if e.complexity.PageInfo.StartCursor == nil { + break + } + + return e.complexity.PageInfo.StartCursor(childComplexity), true + + case "Query.node": + if e.complexity.Query.Node == nil { + break + } + + args, err := ec.field_Query_node_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.Node(childComplexity, args["id"].(string)), true + + case "Query.nodes": + if e.complexity.Query.Nodes == nil { + break + } + + args, err := ec.field_Query_nodes_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.Nodes(childComplexity, args["ids"].([]string)), true + + } + return 0, false +} + +func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { + rc := graphql.GetOperationContext(ctx) + ec := executionContext{rc, e, 0, 0, make(chan graphql.DeferredResult)} + inputUnmarshalMap := graphql.BuildUnmarshalerMap( + ec.unmarshalInputCreateOrgMembershipInput, + ec.unmarshalInputCreateOrganizationInput, + ec.unmarshalInputOrgMembershipWhereInput, + ec.unmarshalInputOrganizationWhereInput, + ec.unmarshalInputUpdateOrgMembershipInput, + ec.unmarshalInputUpdateOrganizationInput, + ) + first := true + + switch rc.Operation.Operation { + case ast.Query: + return func(ctx context.Context) *graphql.Response { + var response graphql.Response + var data graphql.Marshaler + if first { + first = false + ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) + data = ec._Query(ctx, rc.Operation.SelectionSet) + } else { + if atomic.LoadInt32(&ec.pendingDeferred) > 0 { + result := <-ec.deferredResults + atomic.AddInt32(&ec.pendingDeferred, -1) + data = result.Result + response.Path = result.Path + response.Label = result.Label + response.Errors = result.Errors + } else { + return nil + } + } + var buf bytes.Buffer + data.MarshalGQL(&buf) + response.Data = buf.Bytes() + if atomic.LoadInt32(&ec.deferred) > 0 { + hasNext := atomic.LoadInt32(&ec.pendingDeferred) > 0 + response.HasNext = &hasNext + } + + return &response + } + + default: + return graphql.OneShot(graphql.ErrorResponse(ctx, "unsupported GraphQL operation")) + } +} + +type executionContext struct { + *graphql.OperationContext + *executableSchema + deferred int32 + pendingDeferred int32 + deferredResults chan graphql.DeferredResult +} + +func (ec *executionContext) processDeferredGroup(dg graphql.DeferredGroup) { + atomic.AddInt32(&ec.pendingDeferred, 1) + go func() { + ctx := graphql.WithFreshResponseContext(dg.Context) + dg.FieldSet.Dispatch(ctx) + ds := graphql.DeferredResult{ + Path: dg.Path, + Label: dg.Label, + Result: dg.FieldSet, + Errors: graphql.GetErrors(ctx), + } + // null fields should bubble up + if dg.FieldSet.Invalids > 0 { + ds.Result = graphql.Null + } + ec.deferredResults <- ds + }() +} + +func (ec *executionContext) introspectSchema() (*introspection.Schema, error) { + if ec.DisableIntrospection { + return nil, errors.New("introspection disabled") + } + return introspection.WrapSchema(ec.Schema()), nil +} + +func (ec *executionContext) introspectType(name string) (*introspection.Type, error) { + if ec.DisableIntrospection { + return nil, errors.New("introspection disabled") + } + return introspection.WrapTypeFromDef(ec.Schema(), ec.Schema().Types[name]), nil +} + +var sources = []*ast.Source{ + {Name: "../schema/ent.graphql", Input: `directive @goField(forceResolver: Boolean, name: String, omittable: Boolean) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION +directive @goModel(model: String, models: [String!], forceGenerate: Boolean) on OBJECT | INPUT_OBJECT | SCALAR | ENUM | INTERFACE | UNION +""" +CreateOrgMembershipInput is used for create OrgMembership object. +Input was generated by ent. +""" +input CreateOrgMembershipInput { + role: OrgMembershipRole + userID: String! + organizationID: ID! +} +""" +CreateOrganizationInput is used for create Organization object. +Input was generated by ent. +""" +input CreateOrganizationInput { + """ + the name of the organization + """ + name: String! + """ + An optional description of the organization + """ + description: String +} +""" +Define a Relay Cursor type: +https://relay.dev/graphql/connections.htm#sec-Cursor +""" +scalar Cursor +""" +An object with an ID. +Follows the [Relay Global Object Identification Specification](https://relay.dev/graphql/objectidentification.htm) +""" +interface Node @goModel(model: "github.com/theopenlane/iam/entfga/_examples/basic/ent.Noder") { + """ + The id of the object. + """ + id: ID! +} +""" +Possible directions in which to order a list of items when provided an ` + "`" + `orderBy` + "`" + ` argument. +""" +enum OrderDirection { + """ + Specifies an ascending order for a given ` + "`" + `orderBy` + "`" + ` argument. + """ + ASC + """ + Specifies a descending order for a given ` + "`" + `orderBy` + "`" + ` argument. + """ + DESC +} +type OrgMembership implements Node { + id: ID! + role: OrgMembershipRole! + organizationID: ID! + userID: String! + organization: Organization! +} +""" +OrgMembershipRole is enum for the field role +""" +enum OrgMembershipRole @goModel(model: "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums.Role") { + ADMIN + MEMBER + OWNER +} +""" +OrgMembershipWhereInput is used for filtering OrgMembership objects. +Input was generated by ent. +""" +input OrgMembershipWhereInput { + not: OrgMembershipWhereInput + and: [OrgMembershipWhereInput!] + or: [OrgMembershipWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + idEqualFold: ID + idContainsFold: ID + """ + role field predicates + """ + role: OrgMembershipRole + roleNEQ: OrgMembershipRole + roleIn: [OrgMembershipRole!] + roleNotIn: [OrgMembershipRole!] + """ + organization_id field predicates + """ + organizationID: ID + organizationIDNEQ: ID + organizationIDIn: [ID!] + organizationIDNotIn: [ID!] + organizationIDGT: ID + organizationIDGTE: ID + organizationIDLT: ID + organizationIDLTE: ID + organizationIDContains: ID + organizationIDHasPrefix: ID + organizationIDHasSuffix: ID + organizationIDEqualFold: ID + organizationIDContainsFold: ID + """ + user_id field predicates + """ + userID: String + userIDNEQ: String + userIDIn: [String!] + userIDNotIn: [String!] + userIDGT: String + userIDGTE: String + userIDLT: String + userIDLTE: String + userIDContains: String + userIDHasPrefix: String + userIDHasSuffix: String + userIDEqualFold: String + userIDContainsFold: String + """ + organization edge predicates + """ + hasOrganization: Boolean + hasOrganizationWith: [OrganizationWhereInput!] +} +type Organization implements Node { + id: ID! + """ + the name of the organization + """ + name: String! + """ + An optional description of the organization + """ + description: String +} +""" +OrganizationWhereInput is used for filtering Organization objects. +Input was generated by ent. +""" +input OrganizationWhereInput { + not: OrganizationWhereInput + and: [OrganizationWhereInput!] + or: [OrganizationWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + idEqualFold: ID + idContainsFold: ID + """ + name field predicates + """ + name: String + nameNEQ: String + nameIn: [String!] + nameNotIn: [String!] + nameGT: String + nameGTE: String + nameLT: String + nameLTE: String + nameContains: String + nameHasPrefix: String + nameHasSuffix: String + nameEqualFold: String + nameContainsFold: String + """ + description field predicates + """ + description: String + descriptionNEQ: String + descriptionIn: [String!] + descriptionNotIn: [String!] + descriptionGT: String + descriptionGTE: String + descriptionLT: String + descriptionLTE: String + descriptionContains: String + descriptionHasPrefix: String + descriptionHasSuffix: String + descriptionIsNil: Boolean + descriptionNotNil: Boolean + descriptionEqualFold: String + descriptionContainsFold: String +} +""" +Information about pagination in a connection. +https://relay.dev/graphql/connections.htm#sec-undefined.PageInfo +""" +type PageInfo { + """ + When paginating forwards, are there more items? + """ + hasNextPage: Boolean! + """ + When paginating backwards, are there more items? + """ + hasPreviousPage: Boolean! + """ + When paginating backwards, the cursor to continue. + """ + startCursor: Cursor + """ + When paginating forwards, the cursor to continue. + """ + endCursor: Cursor +} +type Query { + """ + Fetches an object given its ID. + """ + node( + """ + ID of the object. + """ + id: ID! + ): Node + """ + Lookup nodes by a list of IDs. + """ + nodes( + """ + The list of node IDs. + """ + ids: [ID!]! + ): [Node]! +} +""" +UpdateOrgMembershipInput is used for update OrgMembership object. +Input was generated by ent. +""" +input UpdateOrgMembershipInput { + role: OrgMembershipRole +} +""" +UpdateOrganizationInput is used for update Organization object. +Input was generated by ent. +""" +input UpdateOrganizationInput { + """ + the name of the organization + """ + name: String + """ + An optional description of the organization + """ + description: String + clearDescription: Boolean +} +`, BuiltIn: false}, +} +var parsedSchema = gqlparser.MustLoadSchema(sources...) + +// endregion ************************** generated!.gotpl ************************** + +// region ***************************** args.gotpl ***************************** + +func (ec *executionContext) field_Query___type_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { + var err error + args := map[string]interface{}{} + var arg0 string + if tmp, ok := rawArgs["name"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + arg0, err = ec.unmarshalNString2string(ctx, tmp) + if err != nil { + return nil, err + } + } + args["name"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Query_node_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { + var err error + args := map[string]interface{}{} + var arg0 string + if tmp, ok := rawArgs["id"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + arg0, err = ec.unmarshalNID2string(ctx, tmp) + if err != nil { + return nil, err + } + } + args["id"] = arg0 + return args, nil +} + +func (ec *executionContext) field_Query_nodes_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { + var err error + args := map[string]interface{}{} + var arg0 []string + if tmp, ok := rawArgs["ids"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("ids")) + arg0, err = ec.unmarshalNID2ᚕstringᚄ(ctx, tmp) + if err != nil { + return nil, err + } + } + args["ids"] = arg0 + return args, nil +} + +func (ec *executionContext) field___Type_enumValues_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { + var err error + args := map[string]interface{}{} + var arg0 bool + if tmp, ok := rawArgs["includeDeprecated"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) + arg0, err = ec.unmarshalOBoolean2bool(ctx, tmp) + if err != nil { + return nil, err + } + } + args["includeDeprecated"] = arg0 + return args, nil +} + +func (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) { + var err error + args := map[string]interface{}{} + var arg0 bool + if tmp, ok := rawArgs["includeDeprecated"]; ok { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) + arg0, err = ec.unmarshalOBoolean2bool(ctx, tmp) + if err != nil { + return nil, err + } + } + args["includeDeprecated"] = arg0 + return args, nil +} + +// endregion ***************************** args.gotpl ***************************** + +// region ************************** directives.gotpl ************************** + +// endregion ************************** directives.gotpl ************************** + +// region **************************** field.gotpl ***************************** + +func (ec *executionContext) _OrgMembership_id(ctx context.Context, field graphql.CollectedField, obj *ent.OrgMembership) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OrgMembership_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNID2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OrgMembership_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OrgMembership", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _OrgMembership_role(ctx context.Context, field graphql.CollectedField, obj *ent.OrgMembership) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OrgMembership_role(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Role, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(enums.Role) + fc.Result = res + return ec.marshalNOrgMembershipRole2githubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OrgMembership_role(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OrgMembership", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type OrgMembershipRole does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _OrgMembership_organizationID(ctx context.Context, field graphql.CollectedField, obj *ent.OrgMembership) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OrgMembership_organizationID(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.OrganizationID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNID2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OrgMembership_organizationID(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OrgMembership", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _OrgMembership_userID(ctx context.Context, field graphql.CollectedField, obj *ent.OrgMembership) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OrgMembership_userID(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.UserID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OrgMembership_userID(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OrgMembership", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _OrgMembership_organization(ctx context.Context, field graphql.CollectedField, obj *ent.OrgMembership) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OrgMembership_organization(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Organization(ctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.Organization) + fc.Result = res + return ec.marshalNOrganization2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrganization(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OrgMembership_organization(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OrgMembership", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Organization_id(ctx, field) + case "name": + return ec.fieldContext_Organization_name(ctx, field) + case "description": + return ec.fieldContext_Organization_description(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Organization", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Organization_id(ctx context.Context, field graphql.CollectedField, obj *ent.Organization) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Organization_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNID2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Organization_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Organization", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Organization_name(ctx context.Context, field graphql.CollectedField, obj *ent.Organization) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Organization_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Organization_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Organization", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Organization_description(ctx context.Context, field graphql.CollectedField, obj *ent.Organization) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Organization_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalOString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Organization_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Organization", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _PageInfo_hasNextPage(ctx context.Context, field graphql.CollectedField, obj *entgql.PageInfo[string]) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_PageInfo_hasNextPage(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.HasNextPage, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalNBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_PageInfo_hasNextPage(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "PageInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _PageInfo_hasPreviousPage(ctx context.Context, field graphql.CollectedField, obj *entgql.PageInfo[string]) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_PageInfo_hasPreviousPage(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.HasPreviousPage, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalNBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_PageInfo_hasPreviousPage(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "PageInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _PageInfo_startCursor(ctx context.Context, field graphql.CollectedField, obj *entgql.PageInfo[string]) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_PageInfo_startCursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.StartCursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*entgql.Cursor[string]) + fc.Result = res + return ec.marshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_PageInfo_startCursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "PageInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Cursor does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _PageInfo_endCursor(ctx context.Context, field graphql.CollectedField, obj *entgql.PageInfo[string]) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_PageInfo_endCursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.EndCursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*entgql.Cursor[string]) + fc.Result = res + return ec.marshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_PageInfo_endCursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "PageInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Cursor does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_node(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_node(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Node(rctx, fc.Args["id"].(string)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(ent.Noder) + fc.Result = res + return ec.marshalONode2githubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐNoder(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_node(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("FieldContext.Child cannot be called on type INTERFACE") + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_node_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_nodes(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_nodes(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Nodes(rctx, fc.Args["ids"].([]string)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]ent.Noder) + fc.Result = res + return ec.marshalNNode2ᚕgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐNoder(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_nodes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("FieldContext.Child cannot be called on type INTERFACE") + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_nodes_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query___type(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return ec.introspectType(fc.Args["name"].(string)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query___type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query___type_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query___schema(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query___schema(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return ec.introspectSchema() + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*introspection.Schema) + fc.Result = res + return ec.marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query___schema(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "description": + return ec.fieldContext___Schema_description(ctx, field) + case "types": + return ec.fieldContext___Schema_types(ctx, field) + case "queryType": + return ec.fieldContext___Schema_queryType(ctx, field) + case "mutationType": + return ec.fieldContext___Schema_mutationType(ctx, field) + case "subscriptionType": + return ec.fieldContext___Schema_subscriptionType(ctx, field) + case "directives": + return ec.fieldContext___Schema_directives(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Schema", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Directive_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Directive_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Directive_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Directive", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Directive_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Directive_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Directive_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Directive", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Directive_locations(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Directive_locations(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Locations, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]string) + fc.Result = res + return ec.marshalN__DirectiveLocation2ᚕstringᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Directive_locations(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Directive", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type __DirectiveLocation does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Directive_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Directive_args(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Args, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]introspection.InputValue) + fc.Result = res + return ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Directive_args(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Directive", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___InputValue_name(ctx, field) + case "description": + return ec.fieldContext___InputValue_description(ctx, field) + case "type": + return ec.fieldContext___InputValue_type(ctx, field) + case "defaultValue": + return ec.fieldContext___InputValue_defaultValue(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Directive_isRepeatable(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Directive_isRepeatable(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.IsRepeatable, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalNBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Directive_isRepeatable(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Directive", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___EnumValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___EnumValue_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___EnumValue_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__EnumValue", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___EnumValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___EnumValue_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___EnumValue_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__EnumValue", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___EnumValue_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___EnumValue_isDeprecated(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.IsDeprecated(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalNBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___EnumValue_isDeprecated(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__EnumValue", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___EnumValue_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___EnumValue_deprecationReason(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.DeprecationReason(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___EnumValue_deprecationReason(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__EnumValue", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_args(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Args, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]introspection.InputValue) + fc.Result = res + return ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_args(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___InputValue_name(ctx, field) + case "description": + return ec.fieldContext___InputValue_description(ctx, field) + case "type": + return ec.fieldContext___InputValue_type(ctx, field) + case "defaultValue": + return ec.fieldContext___InputValue_defaultValue(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_type(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_type(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Type, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_isDeprecated(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.IsDeprecated(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalNBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_isDeprecated(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_deprecationReason(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.DeprecationReason(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_deprecationReason(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___InputValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___InputValue_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___InputValue_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__InputValue", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___InputValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___InputValue_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___InputValue_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__InputValue", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___InputValue_type(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___InputValue_type(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Type, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___InputValue_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__InputValue", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___InputValue_defaultValue(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___InputValue_defaultValue(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.DefaultValue, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___InputValue_defaultValue(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__InputValue", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_types(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_types(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Types(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]introspection.Type) + fc.Result = res + return ec.marshalN__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_types(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_queryType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_queryType(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.QueryType(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_queryType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_mutationType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_mutationType(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.MutationType(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_mutationType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_subscriptionType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_subscriptionType(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.SubscriptionType(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_subscriptionType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_directives(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_directives(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Directives(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]introspection.Directive) + fc.Result = res + return ec.marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirectiveᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_directives(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___Directive_name(ctx, field) + case "description": + return ec.fieldContext___Directive_description(ctx, field) + case "locations": + return ec.fieldContext___Directive_locations(ctx, field) + case "args": + return ec.fieldContext___Directive_args(ctx, field) + case "isRepeatable": + return ec.fieldContext___Directive_isRepeatable(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Directive", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_kind(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_kind(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Kind(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalN__TypeKind2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_kind(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type __TypeKind does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_fields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_fields(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Fields(fc.Args["includeDeprecated"].(bool)), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]introspection.Field) + fc.Result = res + return ec.marshalO__Field2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐFieldᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_fields(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___Field_name(ctx, field) + case "description": + return ec.fieldContext___Field_description(ctx, field) + case "args": + return ec.fieldContext___Field_args(ctx, field) + case "type": + return ec.fieldContext___Field_type(ctx, field) + case "isDeprecated": + return ec.fieldContext___Field_isDeprecated(ctx, field) + case "deprecationReason": + return ec.fieldContext___Field_deprecationReason(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Field", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field___Type_fields_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) ___Type_interfaces(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_interfaces(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.Interfaces(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_interfaces(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_possibleTypes(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_possibleTypes(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.PossibleTypes(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_possibleTypes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_enumValues(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_enumValues(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.EnumValues(fc.Args["includeDeprecated"].(bool)), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]introspection.EnumValue) + fc.Result = res + return ec.marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_enumValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___EnumValue_name(ctx, field) + case "description": + return ec.fieldContext___EnumValue_description(ctx, field) + case "isDeprecated": + return ec.fieldContext___EnumValue_isDeprecated(ctx, field) + case "deprecationReason": + return ec.fieldContext___EnumValue_deprecationReason(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __EnumValue", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field___Type_enumValues_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) ___Type_inputFields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_inputFields(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.InputFields(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]introspection.InputValue) + fc.Result = res + return ec.marshalO__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_inputFields(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___InputValue_name(ctx, field) + case "description": + return ec.fieldContext___InputValue_description(ctx, field) + case "type": + return ec.fieldContext___InputValue_type(ctx, field) + case "defaultValue": + return ec.fieldContext___InputValue_defaultValue(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_ofType(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_ofType(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.OfType(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_ofType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_specifiedByURL(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_specifiedByURL(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) { + ctx = rctx // use context from middleware stack in children + return obj.SpecifiedByURL(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_specifiedByURL(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +// endregion **************************** field.gotpl ***************************** + +// region **************************** input.gotpl ***************************** + +func (ec *executionContext) unmarshalInputCreateOrgMembershipInput(ctx context.Context, obj interface{}) (ent.CreateOrgMembershipInput, error) { + var it ent.CreateOrgMembershipInput + asMap := map[string]interface{}{} + for k, v := range obj.(map[string]interface{}) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"role", "userID", "organizationID"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "role": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("role")) + data, err := ec.unmarshalOOrgMembershipRole2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx, v) + if err != nil { + return it, err + } + it.Role = data + case "userID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userID")) + data, err := ec.unmarshalNString2string(ctx, v) + if err != nil { + return it, err + } + it.UserID = data + case "organizationID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationID")) + data, err := ec.unmarshalNID2string(ctx, v) + if err != nil { + return it, err + } + it.OrganizationID = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputCreateOrganizationInput(ctx context.Context, obj interface{}) (ent.CreateOrganizationInput, error) { + var it ent.CreateOrganizationInput + asMap := map[string]interface{}{} + for k, v := range obj.(map[string]interface{}) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"name", "description"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "name": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + data, err := ec.unmarshalNString2string(ctx, v) + if err != nil { + return it, err + } + it.Name = data + case "description": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Description = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputOrgMembershipWhereInput(ctx context.Context, obj interface{}) (ent.OrgMembershipWhereInput, error) { + var it ent.OrgMembershipWhereInput + asMap := map[string]interface{}{} + for k, v := range obj.(map[string]interface{}) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "idEqualFold", "idContainsFold", "role", "roleNEQ", "roleIn", "roleNotIn", "organizationID", "organizationIDNEQ", "organizationIDIn", "organizationIDNotIn", "organizationIDGT", "organizationIDGTE", "organizationIDLT", "organizationIDLTE", "organizationIDContains", "organizationIDHasPrefix", "organizationIDHasSuffix", "organizationIDEqualFold", "organizationIDContainsFold", "userID", "userIDNEQ", "userIDIn", "userIDNotIn", "userIDGT", "userIDGTE", "userIDLT", "userIDLTE", "userIDContains", "userIDHasPrefix", "userIDHasSuffix", "userIDEqualFold", "userIDContainsFold", "hasOrganization", "hasOrganizationWith"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOOrgMembershipWhereInput2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrgMembershipWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOOrgMembershipWhereInput2ᚕᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrgMembershipWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOOrgMembershipWhereInput2ᚕᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrgMembershipWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "idEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idEqualFold")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDEqualFold = data + case "idContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idContainsFold")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDContainsFold = data + case "role": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("role")) + data, err := ec.unmarshalOOrgMembershipRole2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx, v) + if err != nil { + return it, err + } + it.Role = data + case "roleNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleNEQ")) + data, err := ec.unmarshalOOrgMembershipRole2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx, v) + if err != nil { + return it, err + } + it.RoleNEQ = data + case "roleIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleIn")) + data, err := ec.unmarshalOOrgMembershipRole2ᚕgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRoleᚄ(ctx, v) + if err != nil { + return it, err + } + it.RoleIn = data + case "roleNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("roleNotIn")) + data, err := ec.unmarshalOOrgMembershipRole2ᚕgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRoleᚄ(ctx, v) + if err != nil { + return it, err + } + it.RoleNotIn = data + case "organizationID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationID")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationID = data + case "organizationIDNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDNEQ")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDNEQ = data + case "organizationIDIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDIn")) + data, err := ec.unmarshalOID2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDIn = data + case "organizationIDNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDNotIn")) + data, err := ec.unmarshalOID2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDNotIn = data + case "organizationIDGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDGT")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDGT = data + case "organizationIDGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDGTE")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDGTE = data + case "organizationIDLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDLT")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDLT = data + case "organizationIDLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDLTE")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDLTE = data + case "organizationIDContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDContains")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDContains = data + case "organizationIDHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDHasPrefix")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDHasPrefix = data + case "organizationIDHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDHasSuffix")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDHasSuffix = data + case "organizationIDEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDEqualFold")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDEqualFold = data + case "organizationIDContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("organizationIDContainsFold")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.OrganizationIDContainsFold = data + case "userID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userID")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserID = data + case "userIDNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDNEQ = data + case "userIDIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.UserIDIn = data + case "userIDNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.UserIDNotIn = data + case "userIDGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDGT = data + case "userIDGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDGTE = data + case "userIDLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDLT = data + case "userIDLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDLTE = data + case "userIDContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDContains = data + case "userIDHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDHasPrefix = data + case "userIDHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDHasSuffix = data + case "userIDEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDEqualFold = data + case "userIDContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userIDContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.UserIDContainsFold = data + case "hasOrganization": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasOrganization")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasOrganization = data + case "hasOrganizationWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasOrganizationWith")) + data, err := ec.unmarshalOOrganizationWhereInput2ᚕᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrganizationWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasOrganizationWith = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputOrganizationWhereInput(ctx context.Context, obj interface{}) (ent.OrganizationWhereInput, error) { + var it ent.OrganizationWhereInput + asMap := map[string]interface{}{} + for k, v := range obj.(map[string]interface{}) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "idEqualFold", "idContainsFold", "name", "nameNEQ", "nameIn", "nameNotIn", "nameGT", "nameGTE", "nameLT", "nameLTE", "nameContains", "nameHasPrefix", "nameHasSuffix", "nameEqualFold", "nameContainsFold", "description", "descriptionNEQ", "descriptionIn", "descriptionNotIn", "descriptionGT", "descriptionGTE", "descriptionLT", "descriptionLTE", "descriptionContains", "descriptionHasPrefix", "descriptionHasSuffix", "descriptionIsNil", "descriptionNotNil", "descriptionEqualFold", "descriptionContainsFold"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOOrganizationWhereInput2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrganizationWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOOrganizationWhereInput2ᚕᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrganizationWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOOrganizationWhereInput2ᚕᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrganizationWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "idEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idEqualFold")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDEqualFold = data + case "idContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idContainsFold")) + data, err := ec.unmarshalOID2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.IDContainsFold = data + case "name": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Name = data + case "nameNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameNEQ = data + case "nameIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameIn = data + case "nameNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameNotIn = data + case "nameGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGT = data + case "nameGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGTE = data + case "nameLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLT = data + case "nameLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLTE = data + case "nameContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContains = data + case "nameHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasPrefix = data + case "nameHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasSuffix = data + case "nameEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameEqualFold = data + case "nameContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContainsFold = data + case "description": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Description = data + case "descriptionNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.DescriptionNEQ = data + case "descriptionIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.DescriptionIn = data + case "descriptionNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.DescriptionNotIn = data + case "descriptionGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.DescriptionGT = data + case "descriptionGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.DescriptionGTE = data + case "descriptionLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.DescriptionLT = data + case "descriptionLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.DescriptionLTE = data + case "descriptionContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.DescriptionContains = data + case "descriptionHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.DescriptionHasPrefix = data + case "descriptionHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.DescriptionHasSuffix = data + case "descriptionIsNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionIsNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.DescriptionIsNil = data + case "descriptionNotNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionNotNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.DescriptionNotNil = data + case "descriptionEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.DescriptionEqualFold = data + case "descriptionContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("descriptionContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.DescriptionContainsFold = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputUpdateOrgMembershipInput(ctx context.Context, obj interface{}) (ent.UpdateOrgMembershipInput, error) { + var it ent.UpdateOrgMembershipInput + asMap := map[string]interface{}{} + for k, v := range obj.(map[string]interface{}) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"role"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "role": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("role")) + data, err := ec.unmarshalOOrgMembershipRole2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx, v) + if err != nil { + return it, err + } + it.Role = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputUpdateOrganizationInput(ctx context.Context, obj interface{}) (ent.UpdateOrganizationInput, error) { + var it ent.UpdateOrganizationInput + asMap := map[string]interface{}{} + for k, v := range obj.(map[string]interface{}) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"name", "description", "clearDescription"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "name": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Name = data + case "description": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("description")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Description = data + case "clearDescription": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearDescription")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearDescription = data + } + } + + return it, nil +} + +// endregion **************************** input.gotpl ***************************** + +// region ************************** interface.gotpl *************************** + +func (ec *executionContext) _Node(ctx context.Context, sel ast.SelectionSet, obj ent.Noder) graphql.Marshaler { + switch obj := (obj).(type) { + case nil: + return graphql.Null + case *ent.OrgMembership: + if obj == nil { + return graphql.Null + } + return ec._OrgMembership(ctx, sel, obj) + case *ent.Organization: + if obj == nil { + return graphql.Null + } + return ec._Organization(ctx, sel, obj) + default: + panic(fmt.Errorf("unexpected type %T", obj)) + } +} + +// endregion ************************** interface.gotpl *************************** + +// region **************************** object.gotpl **************************** + +var orgMembershipImplementors = []string{"OrgMembership", "Node"} + +func (ec *executionContext) _OrgMembership(ctx context.Context, sel ast.SelectionSet, obj *ent.OrgMembership) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, orgMembershipImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("OrgMembership") + case "id": + out.Values[i] = ec._OrgMembership_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "role": + out.Values[i] = ec._OrgMembership_role(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "organizationID": + out.Values[i] = ec._OrgMembership_organizationID(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "userID": + out.Values[i] = ec._OrgMembership_userID(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "organization": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._OrgMembership_organization(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var organizationImplementors = []string{"Organization", "Node"} + +func (ec *executionContext) _Organization(ctx context.Context, sel ast.SelectionSet, obj *ent.Organization) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, organizationImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Organization") + case "id": + out.Values[i] = ec._Organization_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "name": + out.Values[i] = ec._Organization_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec._Organization_description(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var pageInfoImplementors = []string{"PageInfo"} + +func (ec *executionContext) _PageInfo(ctx context.Context, sel ast.SelectionSet, obj *entgql.PageInfo[string]) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, pageInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("PageInfo") + case "hasNextPage": + out.Values[i] = ec._PageInfo_hasNextPage(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "hasPreviousPage": + out.Values[i] = ec._PageInfo_hasPreviousPage(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "startCursor": + out.Values[i] = ec._PageInfo_startCursor(ctx, field, obj) + case "endCursor": + out.Values[i] = ec._PageInfo_endCursor(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var queryImplementors = []string{"Query"} + +func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, queryImplementors) + ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ + Object: "Query", + }) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ + Object: field.Name, + Field: field, + }) + + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Query") + case "node": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_node(ctx, field) + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "nodes": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_nodes(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "__type": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Query___type(ctx, field) + }) + case "__schema": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Query___schema(ctx, field) + }) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __DirectiveImplementors = []string{"__Directive"} + +func (ec *executionContext) ___Directive(ctx context.Context, sel ast.SelectionSet, obj *introspection.Directive) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __DirectiveImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__Directive") + case "name": + out.Values[i] = ec.___Directive_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec.___Directive_description(ctx, field, obj) + case "locations": + out.Values[i] = ec.___Directive_locations(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "args": + out.Values[i] = ec.___Directive_args(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "isRepeatable": + out.Values[i] = ec.___Directive_isRepeatable(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __EnumValueImplementors = []string{"__EnumValue"} + +func (ec *executionContext) ___EnumValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.EnumValue) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __EnumValueImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__EnumValue") + case "name": + out.Values[i] = ec.___EnumValue_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec.___EnumValue_description(ctx, field, obj) + case "isDeprecated": + out.Values[i] = ec.___EnumValue_isDeprecated(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "deprecationReason": + out.Values[i] = ec.___EnumValue_deprecationReason(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __FieldImplementors = []string{"__Field"} + +func (ec *executionContext) ___Field(ctx context.Context, sel ast.SelectionSet, obj *introspection.Field) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __FieldImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__Field") + case "name": + out.Values[i] = ec.___Field_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec.___Field_description(ctx, field, obj) + case "args": + out.Values[i] = ec.___Field_args(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "type": + out.Values[i] = ec.___Field_type(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "isDeprecated": + out.Values[i] = ec.___Field_isDeprecated(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "deprecationReason": + out.Values[i] = ec.___Field_deprecationReason(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __InputValueImplementors = []string{"__InputValue"} + +func (ec *executionContext) ___InputValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.InputValue) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __InputValueImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__InputValue") + case "name": + out.Values[i] = ec.___InputValue_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec.___InputValue_description(ctx, field, obj) + case "type": + out.Values[i] = ec.___InputValue_type(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "defaultValue": + out.Values[i] = ec.___InputValue_defaultValue(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __SchemaImplementors = []string{"__Schema"} + +func (ec *executionContext) ___Schema(ctx context.Context, sel ast.SelectionSet, obj *introspection.Schema) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __SchemaImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__Schema") + case "description": + out.Values[i] = ec.___Schema_description(ctx, field, obj) + case "types": + out.Values[i] = ec.___Schema_types(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "queryType": + out.Values[i] = ec.___Schema_queryType(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "mutationType": + out.Values[i] = ec.___Schema_mutationType(ctx, field, obj) + case "subscriptionType": + out.Values[i] = ec.___Schema_subscriptionType(ctx, field, obj) + case "directives": + out.Values[i] = ec.___Schema_directives(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __TypeImplementors = []string{"__Type"} + +func (ec *executionContext) ___Type(ctx context.Context, sel ast.SelectionSet, obj *introspection.Type) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __TypeImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__Type") + case "kind": + out.Values[i] = ec.___Type_kind(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "name": + out.Values[i] = ec.___Type_name(ctx, field, obj) + case "description": + out.Values[i] = ec.___Type_description(ctx, field, obj) + case "fields": + out.Values[i] = ec.___Type_fields(ctx, field, obj) + case "interfaces": + out.Values[i] = ec.___Type_interfaces(ctx, field, obj) + case "possibleTypes": + out.Values[i] = ec.___Type_possibleTypes(ctx, field, obj) + case "enumValues": + out.Values[i] = ec.___Type_enumValues(ctx, field, obj) + case "inputFields": + out.Values[i] = ec.___Type_inputFields(ctx, field, obj) + case "ofType": + out.Values[i] = ec.___Type_ofType(ctx, field, obj) + case "specifiedByURL": + out.Values[i] = ec.___Type_specifiedByURL(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +// endregion **************************** object.gotpl **************************** + +// region ***************************** type.gotpl ***************************** + +func (ec *executionContext) unmarshalNBoolean2bool(ctx context.Context, v interface{}) (bool, error) { + res, err := graphql.UnmarshalBoolean(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { + res := graphql.MarshalBoolean(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalNID2string(ctx context.Context, v interface{}) (string, error) { + res, err := graphql.UnmarshalString(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNID2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + res := graphql.MarshalString(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalNID2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { + var vSlice []interface{} + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]string, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNID2string(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalNID2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNID2string(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalNNode2ᚕgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐNoder(ctx context.Context, sel ast.SelectionSet, v []ent.Noder) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalONode2githubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐNoder(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + return ret +} + +func (ec *executionContext) unmarshalNOrgMembershipRole2githubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx context.Context, v interface{}) (enums.Role, error) { + var res enums.Role + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNOrgMembershipRole2githubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx context.Context, sel ast.SelectionSet, v enums.Role) graphql.Marshaler { + return v +} + +func (ec *executionContext) unmarshalNOrgMembershipWhereInput2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrgMembershipWhereInput(ctx context.Context, v interface{}) (*ent.OrgMembershipWhereInput, error) { + res, err := ec.unmarshalInputOrgMembershipWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNOrganization2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrganization(ctx context.Context, sel ast.SelectionSet, v *ent.Organization) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._Organization(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNOrganizationWhereInput2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrganizationWhereInput(ctx context.Context, v interface{}) (*ent.OrganizationWhereInput, error) { + res, err := ec.unmarshalInputOrganizationWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNString2string(ctx context.Context, v interface{}) (string, error) { + res, err := graphql.UnmarshalString(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNString2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + res := graphql.MarshalString(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) marshalN__Directive2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirective(ctx context.Context, sel ast.SelectionSet, v introspection.Directive) graphql.Marshaler { + return ec.___Directive(ctx, sel, &v) +} + +func (ec *executionContext) marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirectiveᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Directive) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__Directive2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirective(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalN__DirectiveLocation2string(ctx context.Context, v interface{}) (string, error) { + res, err := graphql.UnmarshalString(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalN__DirectiveLocation2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + res := graphql.MarshalString(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalN__DirectiveLocation2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { + var vSlice []interface{} + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]string, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalN__DirectiveLocation2string(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalN__DirectiveLocation2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__DirectiveLocation2string(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalN__EnumValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValue(ctx context.Context, sel ast.SelectionSet, v introspection.EnumValue) graphql.Marshaler { + return ec.___EnumValue(ctx, sel, &v) +} + +func (ec *executionContext) marshalN__Field2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐField(ctx context.Context, sel ast.SelectionSet, v introspection.Field) graphql.Marshaler { + return ec.___Field(ctx, sel, &v) +} + +func (ec *executionContext) marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx context.Context, sel ast.SelectionSet, v introspection.InputValue) graphql.Marshaler { + return ec.___InputValue(ctx, sel, &v) +} + +func (ec *executionContext) marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.InputValue) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v introspection.Type) graphql.Marshaler { + return ec.___Type(ctx, sel, &v) +} + +func (ec *executionContext) marshalN__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Type) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v *introspection.Type) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec.___Type(ctx, sel, v) +} + +func (ec *executionContext) unmarshalN__TypeKind2string(ctx context.Context, v interface{}) (string, error) { + res, err := graphql.UnmarshalString(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalN__TypeKind2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + res := graphql.MarshalString(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalOBoolean2bool(ctx context.Context, v interface{}) (bool, error) { + res, err := graphql.UnmarshalBoolean(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { + res := graphql.MarshalBoolean(v) + return res +} + +func (ec *executionContext) unmarshalOBoolean2ᚖbool(ctx context.Context, v interface{}) (*bool, error) { + if v == nil { + return nil, nil + } + res, err := graphql.UnmarshalBoolean(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOBoolean2ᚖbool(ctx context.Context, sel ast.SelectionSet, v *bool) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := graphql.MarshalBoolean(*v) + return res +} + +func (ec *executionContext) unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx context.Context, v interface{}) (*entgql.Cursor[string], error) { + if v == nil { + return nil, nil + } + var res = new(entgql.Cursor[string]) + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx context.Context, sel ast.SelectionSet, v *entgql.Cursor[string]) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return v +} + +func (ec *executionContext) unmarshalOID2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { + if v == nil { + return nil, nil + } + var vSlice []interface{} + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]string, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNID2string(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOID2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNID2string(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOID2ᚖstring(ctx context.Context, v interface{}) (*string, error) { + if v == nil { + return nil, nil + } + res, err := graphql.UnmarshalString(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOID2ᚖstring(ctx context.Context, sel ast.SelectionSet, v *string) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := graphql.MarshalString(*v) + return res +} + +func (ec *executionContext) marshalONode2githubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐNoder(ctx context.Context, sel ast.SelectionSet, v ent.Noder) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._Node(ctx, sel, v) +} + +func (ec *executionContext) unmarshalOOrgMembershipRole2ᚕgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRoleᚄ(ctx context.Context, v interface{}) ([]enums.Role, error) { + if v == nil { + return nil, nil + } + var vSlice []interface{} + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]enums.Role, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNOrgMembershipRole2githubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOOrgMembershipRole2ᚕgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRoleᚄ(ctx context.Context, sel ast.SelectionSet, v []enums.Role) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNOrgMembershipRole2githubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOOrgMembershipRole2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx context.Context, v interface{}) (*enums.Role, error) { + if v == nil { + return nil, nil + } + var res = new(enums.Role) + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOOrgMembershipRole2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚋenumsᚐRole(ctx context.Context, sel ast.SelectionSet, v *enums.Role) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return v +} + +func (ec *executionContext) unmarshalOOrgMembershipWhereInput2ᚕᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrgMembershipWhereInputᚄ(ctx context.Context, v interface{}) ([]*ent.OrgMembershipWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []interface{} + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.OrgMembershipWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNOrgMembershipWhereInput2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrgMembershipWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOOrgMembershipWhereInput2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrgMembershipWhereInput(ctx context.Context, v interface{}) (*ent.OrgMembershipWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputOrgMembershipWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOOrganizationWhereInput2ᚕᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrganizationWhereInputᚄ(ctx context.Context, v interface{}) ([]*ent.OrganizationWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []interface{} + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.OrganizationWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNOrganizationWhereInput2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrganizationWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOOrganizationWhereInput2ᚖgithubᚗcomᚋtheopenlaneᚋfgaxᚋentfgaᚋ_examplesᚋbasicᚋentᚐOrganizationWhereInput(ctx context.Context, v interface{}) (*ent.OrganizationWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputOrganizationWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOString2string(ctx context.Context, v interface{}) (string, error) { + res, err := graphql.UnmarshalString(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOString2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + res := graphql.MarshalString(v) + return res +} + +func (ec *executionContext) unmarshalOString2ᚕstringᚄ(ctx context.Context, v interface{}) ([]string, error) { + if v == nil { + return nil, nil + } + var vSlice []interface{} + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]string, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNString2string(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOString2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNString2string(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOString2ᚖstring(ctx context.Context, v interface{}) (*string, error) { + if v == nil { + return nil, nil + } + res, err := graphql.UnmarshalString(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOString2ᚖstring(ctx context.Context, sel ast.SelectionSet, v *string) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := graphql.MarshalString(*v) + return res +} + +func (ec *executionContext) marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.EnumValue) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__EnumValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValue(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalO__Field2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐFieldᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Field) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__Field2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐField(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalO__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.InputValue) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx context.Context, sel ast.SelectionSet, v *introspection.Schema) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec.___Schema(ctx, sel, v) +} + +func (ec *executionContext) marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Type) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v *introspection.Type) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec.___Type(ctx, sel, v) +} + +// endregion ***************************** type.gotpl ***************************** diff --git a/entfga/_examples/basic/schema.graphql b/entfga/_examples/basic/schema.graphql new file mode 100644 index 0000000..52f2a38 --- /dev/null +++ b/entfga/_examples/basic/schema.graphql @@ -0,0 +1,265 @@ +directive @goField(forceResolver: Boolean, name: String, omittable: Boolean) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION +directive @goModel(model: String, models: [String!], forceGenerate: Boolean) on OBJECT | INPUT_OBJECT | SCALAR | ENUM | INTERFACE | UNION +""" +CreateOrgMembershipInput is used for create OrgMembership object. +Input was generated by ent. +""" +input CreateOrgMembershipInput { + role: OrgMembershipRole + userID: String! + organizationID: ID! +} +""" +CreateOrganizationInput is used for create Organization object. +Input was generated by ent. +""" +input CreateOrganizationInput { + """ + the name of the organization + """ + name: String! + """ + An optional description of the organization + """ + description: String +} +""" +Define a Relay Cursor type: +https://relay.dev/graphql/connections.htm#sec-Cursor +""" +scalar Cursor +""" +An object with an ID. +Follows the [Relay Global Object Identification Specification](https://relay.dev/graphql/objectidentification.htm) +""" +interface Node @goModel(model: "github.com/theopenlane/iam/entfga/_examples/basic/ent.Noder") { + """ + The id of the object. + """ + id: ID! +} +""" +Possible directions in which to order a list of items when provided an `orderBy` argument. +""" +enum OrderDirection { + """ + Specifies an ascending order for a given `orderBy` argument. + """ + ASC + """ + Specifies a descending order for a given `orderBy` argument. + """ + DESC +} +type OrgMembership implements Node { + id: ID! + role: OrgMembershipRole! + organizationID: ID! + userID: String! + organization: Organization! +} +""" +OrgMembershipRole is enum for the field role +""" +enum OrgMembershipRole @goModel(model: "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums.Role") { + ADMIN + MEMBER + OWNER +} +""" +OrgMembershipWhereInput is used for filtering OrgMembership objects. +Input was generated by ent. +""" +input OrgMembershipWhereInput { + not: OrgMembershipWhereInput + and: [OrgMembershipWhereInput!] + or: [OrgMembershipWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + idEqualFold: ID + idContainsFold: ID + """ + role field predicates + """ + role: OrgMembershipRole + roleNEQ: OrgMembershipRole + roleIn: [OrgMembershipRole!] + roleNotIn: [OrgMembershipRole!] + """ + organization_id field predicates + """ + organizationID: ID + organizationIDNEQ: ID + organizationIDIn: [ID!] + organizationIDNotIn: [ID!] + organizationIDGT: ID + organizationIDGTE: ID + organizationIDLT: ID + organizationIDLTE: ID + organizationIDContains: ID + organizationIDHasPrefix: ID + organizationIDHasSuffix: ID + organizationIDEqualFold: ID + organizationIDContainsFold: ID + """ + user_id field predicates + """ + userID: String + userIDNEQ: String + userIDIn: [String!] + userIDNotIn: [String!] + userIDGT: String + userIDGTE: String + userIDLT: String + userIDLTE: String + userIDContains: String + userIDHasPrefix: String + userIDHasSuffix: String + userIDEqualFold: String + userIDContainsFold: String + """ + organization edge predicates + """ + hasOrganization: Boolean + hasOrganizationWith: [OrganizationWhereInput!] +} +type Organization implements Node { + id: ID! + """ + the name of the organization + """ + name: String! + """ + An optional description of the organization + """ + description: String +} +""" +OrganizationWhereInput is used for filtering Organization objects. +Input was generated by ent. +""" +input OrganizationWhereInput { + not: OrganizationWhereInput + and: [OrganizationWhereInput!] + or: [OrganizationWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + idEqualFold: ID + idContainsFold: ID + """ + name field predicates + """ + name: String + nameNEQ: String + nameIn: [String!] + nameNotIn: [String!] + nameGT: String + nameGTE: String + nameLT: String + nameLTE: String + nameContains: String + nameHasPrefix: String + nameHasSuffix: String + nameEqualFold: String + nameContainsFold: String + """ + description field predicates + """ + description: String + descriptionNEQ: String + descriptionIn: [String!] + descriptionNotIn: [String!] + descriptionGT: String + descriptionGTE: String + descriptionLT: String + descriptionLTE: String + descriptionContains: String + descriptionHasPrefix: String + descriptionHasSuffix: String + descriptionIsNil: Boolean + descriptionNotNil: Boolean + descriptionEqualFold: String + descriptionContainsFold: String +} +""" +Information about pagination in a connection. +https://relay.dev/graphql/connections.htm#sec-undefined.PageInfo +""" +type PageInfo { + """ + When paginating forwards, are there more items? + """ + hasNextPage: Boolean! + """ + When paginating backwards, are there more items? + """ + hasPreviousPage: Boolean! + """ + When paginating backwards, the cursor to continue. + """ + startCursor: Cursor + """ + When paginating forwards, the cursor to continue. + """ + endCursor: Cursor +} +type Query { + """ + Fetches an object given its ID. + """ + node( + """ + ID of the object. + """ + id: ID! + ): Node + """ + Lookup nodes by a list of IDs. + """ + nodes( + """ + The list of node IDs. + """ + ids: [ID!]! + ): [Node]! +} +""" +UpdateOrgMembershipInput is used for update OrgMembership object. +Input was generated by ent. +""" +input UpdateOrgMembershipInput { + role: OrgMembershipRole +} +""" +UpdateOrganizationInput is used for update Organization object. +Input was generated by ent. +""" +input UpdateOrganizationInput { + """ + the name of the organization + """ + name: String + """ + An optional description of the organization + """ + description: String + clearDescription: Boolean +} diff --git a/entfga/_examples/basic/schema/ent.graphql b/entfga/_examples/basic/schema/ent.graphql new file mode 100644 index 0000000..f8ad994 --- /dev/null +++ b/entfga/_examples/basic/schema/ent.graphql @@ -0,0 +1,265 @@ +directive @goField(forceResolver: Boolean, name: String, omittable: Boolean) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION +directive @goModel(model: String, models: [String!], forceGenerate: Boolean) on OBJECT | INPUT_OBJECT | SCALAR | ENUM | INTERFACE | UNION +""" +CreateOrgMembershipInput is used for create OrgMembership object. +Input was generated by ent. +""" +input CreateOrgMembershipInput { + role: OrgMembershipRole + userID: String! + organizationID: ID! +} +""" +CreateOrganizationInput is used for create Organization object. +Input was generated by ent. +""" +input CreateOrganizationInput { + """ + the name of the organization + """ + name: String! + """ + An optional description of the organization + """ + description: String +} +""" +Define a Relay Cursor type: +https://relay.dev/graphql/connections.htm#sec-Cursor +""" +scalar Cursor +""" +An object with an ID. +Follows the [Relay Global Object Identification Specification](https://relay.dev/graphql/objectidentification.htm) +""" +interface Node @goModel(model: "github.com/theopenlane/iam/entfga/_examples/basic/ent.Noder") { + """ + The id of the object. + """ + id: ID! +} +""" +Possible directions in which to order a list of items when provided an `orderBy` argument. +""" +enum OrderDirection { + """ + Specifies an ascending order for a given `orderBy` argument. + """ + ASC + """ + Specifies a descending order for a given `orderBy` argument. + """ + DESC +} +type OrgMembership implements Node { + id: ID! + role: OrgMembershipRole! + organizationID: ID! + userID: String! + organization: Organization! +} +""" +OrgMembershipRole is enum for the field role +""" +enum OrgMembershipRole @goModel(model: "github.com/theopenlane/iam/entfga/_examples/basic/ent/enums.Role") { + ADMIN + MEMBER + OWNER +} +""" +OrgMembershipWhereInput is used for filtering OrgMembership objects. +Input was generated by ent. +""" +input OrgMembershipWhereInput { + not: OrgMembershipWhereInput + and: [OrgMembershipWhereInput!] + or: [OrgMembershipWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + idEqualFold: ID + idContainsFold: ID + """ + role field predicates + """ + role: OrgMembershipRole + roleNEQ: OrgMembershipRole + roleIn: [OrgMembershipRole!] + roleNotIn: [OrgMembershipRole!] + """ + organization_id field predicates + """ + organizationID: ID + organizationIDNEQ: ID + organizationIDIn: [ID!] + organizationIDNotIn: [ID!] + organizationIDGT: ID + organizationIDGTE: ID + organizationIDLT: ID + organizationIDLTE: ID + organizationIDContains: ID + organizationIDHasPrefix: ID + organizationIDHasSuffix: ID + organizationIDEqualFold: ID + organizationIDContainsFold: ID + """ + user_id field predicates + """ + userID: String + userIDNEQ: String + userIDIn: [String!] + userIDNotIn: [String!] + userIDGT: String + userIDGTE: String + userIDLT: String + userIDLTE: String + userIDContains: String + userIDHasPrefix: String + userIDHasSuffix: String + userIDEqualFold: String + userIDContainsFold: String + """ + organization edge predicates + """ + hasOrganization: Boolean + hasOrganizationWith: [OrganizationWhereInput!] +} +type Organization implements Node { + id: ID! + """ + the name of the organization + """ + name: String! + """ + An optional description of the organization + """ + description: String +} +""" +OrganizationWhereInput is used for filtering Organization objects. +Input was generated by ent. +""" +input OrganizationWhereInput { + not: OrganizationWhereInput + and: [OrganizationWhereInput!] + or: [OrganizationWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + idEqualFold: ID + idContainsFold: ID + """ + name field predicates + """ + name: String + nameNEQ: String + nameIn: [String!] + nameNotIn: [String!] + nameGT: String + nameGTE: String + nameLT: String + nameLTE: String + nameContains: String + nameHasPrefix: String + nameHasSuffix: String + nameEqualFold: String + nameContainsFold: String + """ + description field predicates + """ + description: String + descriptionNEQ: String + descriptionIn: [String!] + descriptionNotIn: [String!] + descriptionGT: String + descriptionGTE: String + descriptionLT: String + descriptionLTE: String + descriptionContains: String + descriptionHasPrefix: String + descriptionHasSuffix: String + descriptionIsNil: Boolean + descriptionNotNil: Boolean + descriptionEqualFold: String + descriptionContainsFold: String +} +""" +Information about pagination in a connection. +https://relay.dev/graphql/connections.htm#sec-undefined.PageInfo +""" +type PageInfo { + """ + When paginating forwards, are there more items? + """ + hasNextPage: Boolean! + """ + When paginating backwards, are there more items? + """ + hasPreviousPage: Boolean! + """ + When paginating backwards, the cursor to continue. + """ + startCursor: Cursor + """ + When paginating forwards, the cursor to continue. + """ + endCursor: Cursor +} +type Query { + """ + Fetches an object given its ID. + """ + node( + """ + ID of the object. + """ + id: ID! + ): Node + """ + Lookup nodes by a list of IDs. + """ + nodes( + """ + The list of node IDs. + """ + ids: [ID!]! + ): [Node]! +} +""" +UpdateOrgMembershipInput is used for update OrgMembership object. +Input was generated by ent. +""" +input UpdateOrgMembershipInput { + role: OrgMembershipRole +} +""" +UpdateOrganizationInput is used for update Organization object. +Input was generated by ent. +""" +input UpdateOrganizationInput { + """ + the name of the organization + """ + name: String + """ + An optional description of the organization + """ + description: String + clearDescription: Boolean +} diff --git a/entfga/annotations.go b/entfga/annotations.go new file mode 100644 index 0000000..fcf8e99 --- /dev/null +++ b/entfga/annotations.go @@ -0,0 +1,15 @@ +package entfga + +// Annotations of the fga extension +type Annotations struct { + ObjectType string `yaml:"ObjectType,omitempty"` // Object type for the fga relationship + IncludeHooks bool `yaml:"includeHooks,omitempty"` // Include hooks for the fga extension to add tuples to FGA + IDField string `yaml:"idField,omitempty"` // ID field for the object type + NillableIDField bool `yaml:"nillableIDField,omitempty"` // NillableIDField set to true if the id is optional field in the ent schema + OrgOwnedField bool `yaml:"orgOwnedField,omitempty"` // OrgOwnedField set to true if the field is an org owned field and org automatically set by the system +} + +// Name of the annotation +func (Annotations) Name() string { + return "Authz" +} diff --git a/entfga/doc.go b/entfga/doc.go new file mode 100644 index 0000000..330f3f1 --- /dev/null +++ b/entfga/doc.go @@ -0,0 +1,2 @@ +// Package entfga is an ent extension that creates hooks for OpenFGA relationships +package entfga diff --git a/entfga/entfga.go b/entfga/entfga.go new file mode 100644 index 0000000..cf16c8f --- /dev/null +++ b/entfga/entfga.go @@ -0,0 +1,130 @@ +package entfga + +import ( + "embed" + "fmt" + + "entgo.io/ent/entc" + "entgo.io/ent/entc/gen" +) + +var ( + //go:embed templates/* + _templates embed.FS +) + +const ( + defaultGeneratedPkg = "generated" + defaultGeneratedPath = "internal/ent/generated" + defaultSchemaPath = "./internal/ent/schema" +) + +type Config struct { + // SoftDeletes is used to determine if the schema uses soft deletes + SoftDeletes bool + // SchemaPath is the path to the schema directory + SchemaPath string + // GeneratedPath is the path to the generated directory + GeneratedPath string + // GeneratedPkg is the package that the generated code will be placed in + GeneratedPkg string +} + +func (c Config) Name() string { + return "AuthzConfig" +} + +// AuthzExtension implements entc.Extension. +type AuthzExtension struct { + entc.DefaultExtension + config *Config +} + +type ConfigOption = func(*Config) + +// New creates a new fga extension with the provided config options +func New(opts ...ConfigOption) *AuthzExtension { + extension := &AuthzExtension{ + // Set configuration defaults that can get overridden with ConfigOption + config: &Config{ + SoftDeletes: false, + GeneratedPkg: defaultGeneratedPkg, + GeneratedPath: defaultGeneratedPath, + SchemaPath: defaultSchemaPath, + }, + } + + // update the config with the options + for _, opt := range opts { + opt(extension.config) + } + + return extension +} + +// WithSoftDeletes ensure the delete hook is still used even when soft deletes +// change the Op to Update +func WithSoftDeletes() ConfigOption { + return func(c *Config) { + c.SoftDeletes = true + } +} + +// WithSchemaPath allows you to set an alternative schemaPath +// Defaults to "./schema" +func WithSchemaPath(schemaPath string) ConfigOption { + return func(c *Config) { + c.SchemaPath = schemaPath + } +} + +// WithGeneratedPath allows you to set an alternative ent generated path +// Defaults to "internal/ent/generated" +func WithGeneratedPath(generatedPath string) ConfigOption { + return func(c *Config) { + c.GeneratedPath = generatedPath + } +} + +// WithGeneratedPkg allows you to set an alternative generated package +// Defaults to "generated" +func WithGeneratedPkg(generatedPkg string) ConfigOption { + return func(c *Config) { + c.GeneratedPkg = generatedPkg + } +} + +// GenerateAuthzChecks generates the authz checks for the ent schema +// this is separate to allow the function to be called outside the entc generation +// due to dependencies between the ent policies and the authz checks +func (e *AuthzExtension) GenerateAuthzChecks() error { + graph, err := entc.LoadGraph(e.config.SchemaPath, &gen.Config{}) + if err != nil { + return fmt.Errorf("%w: failed loading ent graph: %v", ErrFailedToGenerateTemplate, err) + } + + info := templateInfo{ + Graph: *graph, + GeneratedPkg: e.config.GeneratedPkg, + GeneratedPath: e.config.GeneratedPath, + } + + return parseAuthzChecksTemplate(info) +} + +// Templates returns the generated templates which include the client and authz from mutation +func (e *AuthzExtension) Templates() []*gen.Template { + templates := []*gen.Template{ + parseTemplate("authzFromMutation", "templates/authzFromMutation.tmpl"), + parseTemplate("client", "templates/client.tmpl"), + } + + return templates +} + +// Annotations of the AuthzExtension +func (e *AuthzExtension) Annotations() []entc.Annotation { + return []entc.Annotation{ + e.config, + } +} diff --git a/entfga/errors.go b/entfga/errors.go new file mode 100644 index 0000000..cbab578 --- /dev/null +++ b/entfga/errors.go @@ -0,0 +1,19 @@ +package entfga + +import ( + "errors" +) + +var ( + // ErrUnsupportedType is returned when the object type is not supported + ErrUnsupportedType = errors.New("unsupported type") + + // ErrMissingRole is returned when an update request is made that contains no role + ErrMissingRole = errors.New("missing role in update") + + // ErrFailedToGenerateTemplate is returned when the template cannot be generated + ErrFailedToGenerateTemplate = errors.New("failed to generate template") + + // ErrFailedToWriteTemplate is returned when the template cannot be written + ErrFailedToWriteTemplate = errors.New("failed to write template") +) diff --git a/entfga/hooks.go b/entfga/hooks.go new file mode 100644 index 0000000..cb032ee --- /dev/null +++ b/entfga/hooks.go @@ -0,0 +1,77 @@ +package entfga + +import ( + "context" + + "entgo.io/ent" +) + +// AuthzHooks returns a list of authorization hooks for create, update, and delete +// operations on a specific type of mutation. +func AuthzHooks[T Mutation]() []ent.Hook { + return []ent.Hook{ + On(authzHookCreate[T](), ent.OpCreate), + On(authzHookUpdate[T](), ent.OpUpdate|ent.OpUpdateOne), + On(authzHookDelete[T](), ent.OpDelete|ent.OpDeleteOne), + } +} + +// authzHookCreate creates tuple relations in FGA after the mutation is executed +func authzHookCreate[T Mutation]() ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mutation, err := getTypedMutation[T](m) + if err != nil { + return nil, err + } + + value, err := next.Mutate(ctx, m) + if err != nil { + return nil, err + } + + err = mutation.CreateTuplesFromCreate(ctx) + if err != nil { + return nil, err + } + + return value, nil + }) + } +} + +// authzHookUpdate updates (involving a delete and create) tuple relations in FGA after the mutation is executed +func authzHookUpdate[T Mutation]() ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mutation, err := getTypedMutation[T](m) + if err != nil { + return nil, err + } + + if err = mutation.CreateTuplesFromUpdate(ctx); err != nil { + return nil, err + } + + return next.Mutate(ctx, m) + }) + } +} + +// authzHookDelete removes tuple relations in FGA after the mutation is executed +func authzHookDelete[T Mutation]() ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mutation, err := getTypedMutation[T](m) + if err != nil { + return nil, err + } + + if err = mutation.CreateTuplesFromDelete(ctx); err != nil { + return nil, err + } + + return next.Mutate(ctx, m) + }) + } +} diff --git a/entfga/opType.go b/entfga/opType.go new file mode 100644 index 0000000..2c693d7 --- /dev/null +++ b/entfga/opType.go @@ -0,0 +1,75 @@ +package entfga + +import ( + "database/sql/driver" + "io" + "strconv" +) + +// OpType is the ent operation type in string form +type OpType string + +const ( + // OpTypeInsert is the insert (create) operation + OpTypeInsert OpType = "INSERT" + // OpTypeUpdate is the update operation + OpTypeUpdate OpType = "UPDATE" + // OpTypeDelete is the delete operation + OpTypeDelete OpType = "DELETE" +) + +// opTypes are the possible values that can be used +var opTypes = []string{ + OpTypeInsert.String(), + OpTypeUpdate.String(), + OpTypeDelete.String(), +} + +// Values provides list valid values for Enum. +func (OpType) Values() (kinds []string) { + kinds = append(kinds, opTypes...) + return +} + +// Value of the operation type +func (op OpType) Value() (driver.Value, error) { + return op.String(), nil +} + +// String value of the operation +func (op OpType) String() string { + return string(op) +} + +// Scan implements the `database/sql.Scanner` interface for the `OpType` type +// and is used to convert a value from the database into an `OpType` value. +func (op *OpType) Scan(v any) error { + if v == nil { + *op = OpType("") + return nil + } + + switch src := v.(type) { + case string: + *op = OpType(src) + case []byte: + *op = OpType(string(src)) + case OpType: + *op = src + default: + return ErrUnsupportedType + } + + return nil +} + +// MarshalGQL implement the Marshaler interface for gqlgen +func (op OpType) MarshalGQL(w io.Writer) { + // graphql ID is a scalar which must be quoted + io.WriteString(w, strconv.Quote(string(op))) //nolint:errcheck +} + +// UnmarshalGQL implement the Unmarshaler interface for gqlgen +func (op *OpType) UnmarshalGQL(v interface{}) error { + return op.Scan(v) +} diff --git a/entfga/role.go b/entfga/role.go new file mode 100644 index 0000000..3cfe10e --- /dev/null +++ b/entfga/role.go @@ -0,0 +1,62 @@ +package entfga + +import ( + "fmt" + "io" + "strings" +) + +type Role string + +var ( + RoleOwner Role = "OWNER" + RoleAdmin Role = "ADMIN" + RoleMember Role = "MEMBER" + Invalid Role = "INVALID" +) + +// Values returns a slice of strings that represents all the possible values of the Role enum. +// Possible default values are "ADMIN", and "MEMBER". +func (Role) Values() (kinds []string) { + for _, s := range []Role{RoleAdmin, RoleMember} { + kinds = append(kinds, string(s)) + } + + return +} + +// String returns the role as a string +func (r Role) String() string { + return string(r) +} + +// Enum returns the Role based on string input +func Enum(r string) Role { + switch r := strings.ToUpper(r); r { + case RoleOwner.String(): + return RoleOwner + case RoleAdmin.String(): + return RoleAdmin + case RoleMember.String(): + return RoleMember + default: + return Invalid + } +} + +// MarshalGQL implement the Marshaler interface for gqlgen +func (r Role) MarshalGQL(w io.Writer) { + _, _ = w.Write([]byte(`"` + r.String() + `"`)) +} + +// UnmarshalGQL implement the Unmarshaler interface for gqlgen +func (r *Role) UnmarshalGQL(v interface{}) error { + str, ok := v.(string) + if !ok { + return fmt.Errorf("wrong type for Role, got: %T", v) //nolint:err113 + } + + *r = Role(str) + + return nil +} diff --git a/entfga/role_test.go b/entfga/role_test.go new file mode 100644 index 0000000..9798745 --- /dev/null +++ b/entfga/role_test.go @@ -0,0 +1,45 @@ +package entfga_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/theopenlane/iam/entfga" +) + +func TestEnum(t *testing.T) { + testCases := []struct { + name string + role string + expected entfga.Role + }{ + { + name: "admin", + role: "admin", + expected: entfga.RoleAdmin, + }, + { + name: "member", + role: "member", + expected: entfga.RoleMember, + }, + { + name: "owner", + role: "owner", + expected: entfga.RoleOwner, + }, + { + name: "invalid role", + role: "cattypist", + expected: entfga.Invalid, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + res := entfga.Enum(tc.role) + assert.Equal(t, tc.expected, res) + }) + } +} diff --git a/entfga/template.go b/entfga/template.go new file mode 100644 index 0000000..db042dc --- /dev/null +++ b/entfga/template.go @@ -0,0 +1,189 @@ +package entfga + +import ( + "bytes" + "fmt" + "os" + "strings" + "text/template" + + "entgo.io/ent/entc/gen" + "github.com/stoewer/go-strcase" + "golang.org/x/tools/imports" +) + +const ( + templateDir = "templates" +) + +// extractObjectType gets the key that is used for the object type +func extractObjectType(val any) string { + objectType, ok := val.(string) + if !ok { + return "" + } + + return objectType +} + +// extractIDField gets the key that is used for the id field +func extractIDField(val any) string { + idField, ok := val.(string) + if !ok { + return "" + } + + if idField == "" { + return "ID" + } + + return idField +} + +// extractNillableIDField gets the key that is used for the nillable id field +func extractNillableIDField(val any) bool { + nillable, ok := val.(bool) + if !ok { + return false + } + + return nillable +} + +// extractOrgOwnedField gets the key that is used for the org owned field +func extractOrgOwnedField(val any) bool { + orgOwned, ok := val.(bool) + if !ok { + return false + } + + return orgOwned +} + +// hasCreateID checks if the input would have the ID to check permissions +func hasCreateID(val any) bool { + idField, ok := val.(string) + if !ok { + return false + } + + if idField == "" || idField == "ID" { + return false + } + + return true +} + +// hasMutationInputSet checks if the annotation for MutationInputs is set on the schema +// this annotation would look like: +// `entgql.Mutations(entgql.MutationCreate(), entgql.MutationUpdate()),` +// on an ent schema +func hasMutationInputSet(val any) bool { + annotation, ok := val.(map[string]interface{}) + if !ok { + return false + } + + if res, ok := annotation["MutationInputs"]; ok && res != nil { + return true + } + + return false +} + +// extractIncludeHooks gets the key that is used to determine if the hooks should be included +func extractIncludeHooks(val any) bool { + includeHooks, ok := val.(bool) + if !ok { + return true + } + + return includeHooks +} + +// useSoftDeletes checks the config properties for the Soft Delete setting +func useSoftDeletes(config Config) bool { + return config.SoftDeletes +} + +// parseTemplate parses the template and sets values in the template +func parseTemplate(name, path string) *gen.Template { + t := gen.NewTemplate(name) + t.Funcs(template.FuncMap{ + "extractObjectType": extractObjectType, + "extractIDField": extractIDField, + "extractNillableIDField": extractNillableIDField, + "extractOrgOwnedField": extractOrgOwnedField, + "hasCreateID": hasCreateID, + "hasMutationInputSet": hasMutationInputSet, + "extractIncludeHooks": extractIncludeHooks, + "useSoftDeletes": useSoftDeletes, + "ToUpperCamel": strcase.UpperCamelCase, + "ToLower": strings.ToLower, + }) + + return gen.MustParse(t.ParseFS(_templates, path)) +} + +// templateInfo is the information needed to parse the template +// for the authz checks +type templateInfo struct { + // Graph holds the nodes/entities of the loaded graph schema + Graph gen.Graph + // GeneratedPkg is the package name for the generated files by ent + GeneratedPkg string + // GeneratedPath is the path to the generated files by ent + GeneratedPath string +} + +// parseAuthzChecksTemplate parses the template and sets values in the template +func parseAuthzChecksTemplate(info templateInfo) error { + name := "authzChecks" + templateName := fmt.Sprintf("%s.tmpl", name) + + t := template.New(name) + t.Funcs(template.FuncMap{ + "extractObjectType": extractObjectType, + "extractIDField": extractIDField, + "extractOrgOwnedField": extractOrgOwnedField, + "extractNillableIDField": extractNillableIDField, + "hasCreateID": hasCreateID, + "hasMutationInputSet": hasMutationInputSet, + "ToLower": strings.ToLower, + }) + + // parse the template + template.Must(t.ParseFS(_templates, fmt.Sprintf("%s/%s", templateDir, templateName))) + + // execute the template into a buffer + var buf bytes.Buffer + if err := t.ExecuteTemplate(&buf, templateName, info); err != nil { + return err + } + + // create the output file + outputPath := fmt.Sprintf("%s/%s.go", info.GeneratedPath, strcase.SnakeCase(name)) + + return writeAndFormatFile(buf, outputPath) +} + +// writeAndFormatFile formats the bytes using gofmt and goimports and writes them to the output file +func writeAndFormatFile(buf bytes.Buffer, outputPath string) error { + // run gofmt and goimports on the file contents + formatted, err := imports.Process(outputPath, buf.Bytes(), nil) + if err != nil { + return fmt.Errorf("%w: failed to format file: %v", ErrFailedToWriteTemplate, err) + } + + file, err := os.Create(outputPath) + if err != nil { + return fmt.Errorf("%w: failed to create file: %v", ErrFailedToWriteTemplate, err) + } + + // write the formatted source to the file + if _, err := file.Write(formatted); err != nil { + return fmt.Errorf("%w: failed to write to file: %v", ErrFailedToWriteTemplate, err) + } + + return nil +} diff --git a/entfga/template_test.go b/entfga/template_test.go new file mode 100644 index 0000000..5fd6667 --- /dev/null +++ b/entfga/template_test.go @@ -0,0 +1,43 @@ +package entfga + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_hasMutationInputSet(t *testing.T) { + testCases := []struct { + name string + input any + expected bool + }{ + { + name: "mutation inputs set", + input: map[string]interface{}{"MutationInputs": map[string]interface{}{"IsCreate": true}}, + expected: true, + }, + { + name: "mutation inputs not set", + input: map[string]interface{}{}, + expected: false, + }, + { + name: "mutation inputs set to nil", + input: map[string]interface{}{"MutationInputs": nil}, + expected: false, + }, + { + name: "invalid input type", + input: "invalid", + expected: false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + result := hasMutationInputSet(tc.input) + assert.Equal(t, tc.expected, result) + }) + } +} diff --git a/entfga/templates/authzChecks.tmpl b/entfga/templates/authzChecks.tmpl new file mode 100644 index 0000000..c5417ef --- /dev/null +++ b/entfga/templates/authzChecks.tmpl @@ -0,0 +1,237 @@ +// Code generated by entfga, DO NOT EDIT. +package {{ .GeneratedPkg }} + +{{/* Add imports so the correct privacy package is imported */}} +import ( + "github.com/99designs/gqlgen/graphql" + "entgo.io/ent/privacy" + + "github.com/theopenlane/iam/fgax" + "github.com/theopenlane/iam/auth" +) + +{{- $nodes := .Graph.Nodes }} + +{{- range $n := $nodes }} + {{- $name := $n.Name }} + {{- $mutator := $n.MutationName }} + {{- $querier := $n.QueryName }} + + {{/* Only include nodes with the Authz check anntoation. See: Annotations.Name */}} + {{- if $n.Annotations.Authz }} + + {{- $objectType := extractObjectType $n.Annotations.Authz.ObjectType }} + {{- $idField := extractIDField $n.Annotations.Authz.IDField }} + {{- $nillable := extractNillableIDField $n.Annotations.Authz.NillableIDField }} + {{- $orgOwned := extractOrgOwnedField $n.Annotations.Authz.OrgOwnedField }} + + func (q *{{ $querier }}) CheckAccess(ctx context.Context) error { + gCtx := graphql.GetFieldContext(ctx) + + if gCtx != nil { + ac := fgax.AccessCheck{ + Relation: fgax.CanView, + ObjectType: "{{ $objectType | ToLower }}", + SubjectType: auth.GetAuthzSubjectType(ctx), + } + + // check id from graphql arg context + // when all objects are requested, the interceptor will check object access + // check the where input first + whereArg := gCtx.Args["where"] + if whereArg != nil { + where, ok := whereArg.(*{{ $name }}WhereInput) + if ok && where != nil && where.{{ $idField }} != nil { + ac.ObjectID = *where.{{ $idField }} + } + } + + // if that doesn't work, check for the id in the args + if ac.ObjectID == "" { + ac.ObjectID, _ = gCtx.Args["{{ $idField | ToLower }}"].(string) + } + + // if we still don't have an object id, run the query and grab the object ID + // from the result + // this happens on join tables where we have the join ID (for updates and deletes) + // and not the actual object id + if ac.ObjectID == "" && "id" != "{{ $idField | ToLower }}" { + // allow this query to run + reqCtx := privacy.DecisionContext(ctx, privacy.Allow) + ob, err := q.Clone().Only(reqCtx) + if err != nil { + return privacy.Allowf("nil request, bypassing auth check") + } + ac.ObjectID = ob.{{ $idField }} + } + + // request is for a list objects, will get filtered in interceptors + if ac.ObjectID == "" { + return privacy.Allowf("nil request, bypassing auth check") + } + + var err error + ac.SubjectID, err = auth.GetUserIDFromContext(ctx) + if err != nil { + return err + } + + + access, err := q.Authz.CheckAccess(ctx, ac) + if err != nil { + return privacy.Skipf("unable to check access, %s", err.Error()) + } + + if access { + return privacy.Allow + } + } + + // Skip to the next privacy rule (equivalent to return nil) + return privacy.Skip + } + + {{- if $n.Annotations.EntGQL | hasMutationInputSet }} + func (m *{{ $mutator }}) CheckAccessForEdit(ctx context.Context) error { + ac := fgax.AccessCheck{ + Relation: fgax.CanEdit, + ObjectType: "{{ $objectType | ToLower }}", + SubjectType: auth.GetAuthzSubjectType(ctx), + } + + {{- if $orgOwned }} + orgID, oErr := auth.GetOrganizationIDFromContext(ctx) + + // if we still don't have an object id, run the query and grab the object ID + // from the result + // this happens when using a personal access token since it is authorized for multiple orgs + if orgID == "" || oErr != nil { + id, _ := m.ID() + + if id != "" { + // allow this query to run + reqCtx := privacy.DecisionContext(ctx, privacy.Allow) + ob, err := m.Client().{{ $name }}.Get(reqCtx, id) + if err != nil { + m.Logger.Debugw("error getting object", "error", err) + + return err + } + + orgID = ob.{{ $idField }} + } + } + + ac.ObjectID = orgID + {{ else }} + + gCtx := graphql.GetFieldContext(ctx) + + {{ if hasCreateID $n.Annotations.Authz.IDField }} + // get the input from the context + gInput := gCtx.Args["input"] + + // check if the input is a Create{{ $name }}Input + input, ok := gInput.(Create{{ $name }}Input) + if ok { + {{- if $nillable }} + ac.ObjectID = *input.{{ $idField }} + {{ else }} + ac.ObjectID = input.{{ $idField }} + {{ end }} + } + {{- end }} + + // check the id from the args + if ac.ObjectID == "" { + ac.ObjectID, _ = gCtx.Args["{{ $idField | ToLower }}"].(string) + } + + // if this is still empty, we need to query the object to get the object id + // this happens on join tables where we have the join ID (for updates and deletes) + if ac.ObjectID == "" && "id" != "{{ $idField | ToLower }}" { + id, ok := gCtx.Args["id"].(string) + if ok { + // allow this query to run + reqCtx := privacy.DecisionContext(ctx, privacy.Allow) + ob, err := m.Client().{{ $name }}.Query().Where({{ $name | ToLower }}.ID(id)).Only(reqCtx) + if err != nil { + return privacy.Skipf("nil request, skipping auth check") + } + ac.ObjectID = ob.{{ $idField }} + } + } + {{- end }} + + // request is for a list objects, will get filtered in interceptors + if ac.ObjectID == "" { + return privacy.Allowf("nil request, bypassing auth check") + } + + m.Logger.Debugw("checking mutation access") + + var err error + ac.SubjectID, err = auth.GetUserIDFromContext(ctx) + if err != nil { + return err + } + + m.Logger.Infow("checking relationship tuples", "relation", ac.Relation, "object_id", ac.ObjectID) + + access, err := m.Authz.CheckAccess(ctx, ac) + if err != nil { + return privacy.Skipf("unable to check access, %s", err.Error()) + } + + if access { + m.Logger.Debugw("access allowed", "relation", ac.Relation, "object_id", ac.ObjectID) + + return privacy.Allow + } + + // deny if it was a mutation is not allowed + return privacy.Deny + } + + func (m *{{ $mutator }}) CheckAccessForDelete(ctx context.Context) error { + ac := fgax.AccessCheck{ + Relation: fgax.CanDelete, + ObjectType: "{{ $objectType | ToLower }}", + SubjectType: auth.GetAuthzSubjectType(ctx), + } + + gCtx := graphql.GetFieldContext(ctx) + + var ok bool + ac.ObjectID, ok = gCtx.Args["id"].(string) + if !ok { + return privacy.Allowf("nil request, bypassing auth check") + } + + m.Logger.Debugw("checking mutation access") + + var err error + ac.SubjectID, err = auth.GetUserIDFromContext(ctx) + if err != nil { + return err + } + + m.Logger.Infow("checking relationship tuples", "relation", ac.Relation, "object_id", ac.ObjectID) + + access, err := m.Authz.CheckAccess(ctx, ac) + if err != nil { + return privacy.Skipf("unable to check access, %s", err.Error()) + } + + if access { + m.Logger.Debugw("access allowed", "relation", ac.Relation, "object_id", ac.ObjectID) + + return privacy.Allow + } + + // deny if it was a mutation is not allowed + return privacy.Deny + } + {{- end }} + {{- end }} +{{- end }} \ No newline at end of file diff --git a/entfga/templates/authzFromMutation.tmpl b/entfga/templates/authzFromMutation.tmpl new file mode 100644 index 0000000..51744c5 --- /dev/null +++ b/entfga/templates/authzFromMutation.tmpl @@ -0,0 +1,175 @@ +{{/* gotype: entgo.io/ent/entc/gen.Graph */}} + +{{ define "authFromMutation" }} +// Code generated by entfga, DO NOT EDIT. + + {{ $pkg := base $.Config.Package }} + {{ template "header" $ }} + + {{/* Add Check for Soft Delete See: AuthzConfig.SoftDeletes */}} + {{ $softDeletes := $.Annotations.AuthzConfig.SoftDeletes }} + + {{ range $n := $.Nodes }} + {{ $name := $n.Name }} + {{ $mutator := $n.MutationName }} + {{/* Only include nodes with the Authz annotation with hooks. See: Annotation.Name */}} + {{ if and ($n.Annotations.Authz) ($n.Annotations.Authz.IncludeHooks) }} + + {{ $objectType := extractObjectType $n.Annotations.Authz.ObjectType }} + func (m *{{ $mutator }}) CreateTuplesFromCreate(ctx context.Context) error { + {{ $includeHooks := extractIncludeHooks $n.Annotations.Authz.IncludeHooks }} + // Get fields for tuple creation + userID, _ := m.UserID() + objectID, _ := m.{{ $objectType | ToUpperCamel }}ID() + role, _ := m.Role() + + // get tuple key + req := fgax.TupleRequest{ + SubjectID: userID, + SubjectType: "user", + ObjectID: objectID, + ObjectType: "{{ $objectType | ToLower }}", + Relation: role.String(), + } + tuple := fgax.GetTupleKey(req) + + if _, err := m.Authz.WriteTupleKeys(ctx, []fgax.TupleKey{tuple}, nil); err != nil { + m.Logger.Errorw("failed to create relationship tuple", "error", err) + + return err + } + + m.Logger.Debugw("created relationship tuples", "relation", role, "object", tuple.Object) + + return nil + } + + func (m *{{ $mutator }}) CreateTuplesFromUpdate(ctx context.Context) error { + {{ $includeHooks := extractIncludeHooks $n.Annotations.Authz.IncludeHooks }} + + {{- if $softDeletes }} + // check for soft delete operation and delete instead + if entx.CheckIsSoftDelete(ctx) { + return m.CreateTuplesFromDelete(ctx) + } + {{- end }} + + // get ids that will be updated + ids, err := m.IDs(ctx) + if err != nil { + return err + } + + var ( + writes []fgax.TupleKey + deletes []fgax.TupleKey + ) + + oldRole, err := m.OldRole(ctx) + if err != nil { + return err + } + + newRole, exists := m.Role() + if !exists { + return entfga.ErrMissingRole + } + + if oldRole == newRole { + m.Logger.Debugw("nothing to update, roles are the same", "old_role", oldRole, "new_role", newRole) + + return nil + } + + // User the IDs of the memberships and delete all related tuples + for _, id := range ids { + member, err := m.Client().{{ $name }}.Get(ctx, id) + if err != nil { + return err + } + + req := fgax.TupleRequest{ + SubjectID: member.UserID, + SubjectType: "user", + ObjectID: member.{{ $objectType | ToUpperCamel }}ID, + ObjectType: "{{ $objectType | ToLower }}", + Relation: oldRole.String(), + } + d := fgax.GetTupleKey(req) + + deletes = append(deletes, d) + + req.Relation = newRole.String() + w := fgax.GetTupleKey(req) + + writes = append(writes, w) + + if len(writes) == 0 && len(deletes) == 0 { + m.Logger.Debugw("no relationships to create or delete") + + return nil + } + + if _, err := m.Authz.WriteTupleKeys(ctx, writes, deletes); err != nil { + m.Logger.Errorw("failed to update relationship tuple", "error", err) + + return err + } + } + + return nil + } + + func (m *{{ $mutator }}) CreateTuplesFromDelete(ctx context.Context) error { + {{ $includeHooks := extractIncludeHooks $n.Annotations.Authz.IncludeHooks }} + + {{- if $softDeletes }} + // check for soft delete operation and skip so it happens on update + if entx.CheckIsSoftDelete(ctx) { + return nil + } + {{- end }} + + // get ids that will be deleted + ids, err := m.IDs(ctx) + if err != nil { + return err + } + + tuples := []fgax.TupleKey{} + + // User the IDs of the memberships and delete all related tuples + for _, id := range ids { + // this wont work with soft deletes + members, err := m.Client().{{ $name }}.Get(ctx, id) + if err != nil { + return err + } + + req := fgax.TupleRequest{ + SubjectID: members.UserID, + SubjectType: "user", + ObjectID: members.{{ $objectType | ToUpperCamel }}ID, + ObjectType: "{{ $objectType | ToLower }}", + Relation: members.Role.String(), + } + t := fgax.GetTupleKey(req) + + tuples = append(tuples, t) + } + + if len(tuples) > 0 { + if _, err := m.Authz.WriteTupleKeys(ctx, nil, tuples); err != nil { + m.Logger.Errorw("failed to delete relationship tuple", "error", err) + + return err + } + + m.Logger.Debugw("deleted relationship tuples") + } + + return nil + } + {{ end }} + {{ end }} +{{ end }} \ No newline at end of file diff --git a/entfga/templates/client.tmpl b/entfga/templates/client.tmpl new file mode 100644 index 0000000..66ec0e0 --- /dev/null +++ b/entfga/templates/client.tmpl @@ -0,0 +1,61 @@ +{{/* gotype: entgo.io/ent/entc/gen.Graph */}} + +{{ define "client/init" }} +// Client is the client that holds all ent builders. +type Client struct { + config + {{- if $.SupportMigrate }} + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + {{- end }} + {{- range $n := $.Nodes }} + // {{ $n.Name }} is the client for interacting with the {{ $n.Name }} builders. + {{ $n.Name }} *{{ $n.ClientName }} + {{- end }} + {{- template "client/fields/additional" $ }} + {{- with $tmpls := matchTemplate "client/fields/additional/*" }} + {{- range $tmpl := $tmpls }} + {{- xtemplate $tmpl $ }} + {{- end }} + {{- end }} + // authzActivated determines if the authz hooks have already been activated + authzActivated bool +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + client := &Client{config: cfg} + client.init() + return client +} + +func (c *Client) init() { + {{- if $.SupportMigrate }} + c.Schema = migrate.NewSchema(c.driver) + {{- end }} + {{- range $n := $.Nodes }} + c.{{ $n.Name }} = New{{ $n.ClientName }}(c.config) + {{- end }} +} + +// WithAuthz adds the authz hooks to the appropriate schemas - generated by entfga +func (c *Client) WithAuthz() { + if !c.authzActivated { + {{- range $n := $.Nodes }} + {{- $name := $n.Name }} + {{ if $n.Annotations.Authz }} + {{ $includeHooks := extractIncludeHooks $n.Annotations.Authz.IncludeHooks }} + {{ if $includeHooks}} + for _, hook := range entfga.AuthzHooks[*{{ $name }}Mutation]() { + c.{{ $name }}.Use(hook) + } + {{- end }} + {{- end }} + {{- end }} + c.authzActivated = true + } +} + +{{ end }} \ No newline at end of file diff --git a/entfga/types.go b/entfga/types.go new file mode 100644 index 0000000..a7aeb1c --- /dev/null +++ b/entfga/types.go @@ -0,0 +1,73 @@ +package entfga + +import ( + "context" + "fmt" + + "entgo.io/ent" +) + +// Mutation interface that all generated Mutation types must implement +// These functions (with the exception of Op() which is already created) are generated by the ent extension for every schema +// that includes the `entfga.NewFGAExtension“ extension to satisfy the interface +// If hooks are skipped by the mutation, the functions are created to satisfy the interface but always return nil and are not added to the client +type Mutation interface { + // Op is the ent operation being taken on the Mutation (Create, Update, UpdateOne, Delete, DeleteOne) + Op() ent.Op + // CreateTuplesFromCreate creates tuple relationships for the user/object type on Create Mutations + CreateTuplesFromCreate(ctx context.Context) error + // CreateTuplesFromUpdate creates new and deletes old tuple relationships for the user/object type on Update Mutations + CreateTuplesFromUpdate(ctx context.Context) error + // CreateTuplesFromDelete deletes tuple relationships for the user/object type on Delete Mutations + CreateTuplesFromDelete(ctx context.Context) error + // CheckAccessForEdit checks if the user has access to edit the object type + CheckAccessForEdit(ctx context.Context) error + // CheckAccessForDelete checks if the user has access to delete the object type + CheckAccessForDelete(ctx context.Context) error +} + +// Mutator is an interface thats defines a method for mutating a generic ent value based on a given mutation. +// This is used as a generic interface that ent generated Mutations will implement +type Mutator interface { + Mutate(context.Context, Mutation) (ent.Value, error) +} + +// Query interface that all generated Query types must implement +type Query interface { + // Op is the ent operation being taken on the Mutation (Create, Update, UpdateOne, Delete, DeleteOne) + Op() ent.Op + + // CheckAccess checks if the user has read access to the object type + CheckAccess(ctx context.Context) error +} + +// Querier is an interface thats defines a method for querying a generic ent value based on a given query. +// This is used as a generic interface that ent generated Query will implement +type Querier interface { + Query(context.Context, Query) (ent.Value, error) +} + +// getTypedMutation determines the specific mutation type +func getTypedMutation[T Mutation](m ent.Mutation) (T, error) { + f, ok := any(m).(T) + if !ok { + return f, fmt.Errorf("expected appropriately typed mutation, got: %+v", m) //nolint:err113 + } + + return f, nil +} + +// On will execute the appropriate hook based on the ent operation +func On(hk ent.Hook, op ent.Op) ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + hasOp := m.Op().Is(op) + + if hasOp { + return hk(next).Mutate(ctx, m) + } + + return next.Mutate(ctx, m) + }) + } +} diff --git a/fgax/checks.go b/fgax/checks.go new file mode 100644 index 0000000..234c9f4 --- /dev/null +++ b/fgax/checks.go @@ -0,0 +1,224 @@ +package fgax + +import ( + "context" + + ofgaclient "github.com/openfga/go-sdk/client" +) + +const ( + // subject types + defaultSubject = userSubject + userSubject = "user" + serviceSubject = "service" + + // object types + organizationObject = "organization" + groupObject = "group" + roleObject = "role" +) + +// AccessCheck is a struct to hold the information needed to check access +type AccessCheck struct { + // ObjectType is the type of object being checked + ObjectType Kind + // ObjectID is the ID of the object being checked + ObjectID string + // SubjectID is the ID of the user making the request + SubjectID string + // SubjectType is the type of subject being checked + SubjectType string + // Relation is the relationship being checked (e.g. "view", "edit", "delete") + Relation string +} + +// ListAccess is a struct to hold the information needed to list all relations +type ListAccess struct { + // ObjectType is the type of object being checked + ObjectType Kind + // ObjectID is the ID of the object being checked + ObjectID string + // SubjectID is the ID of the user making the request + SubjectID string + // SubjectType is the type of subject being checked + SubjectType string + // Relations is the relationship being checked (e.g. "can_view", "can_edit", "can_delete") + Relations []string +} + +// CheckAccess checks if the user has access to the object type with the given relation +func (c *Client) CheckAccess(ctx context.Context, ac AccessCheck) (bool, error) { + if err := validateAccessCheck(ac); err != nil { + return false, err + } + + if ac.SubjectType == "" { + ac.SubjectType = defaultSubject + } + + sub := Entity{ + Kind: Kind(ac.SubjectType), + Identifier: ac.SubjectID, + } + + obj := Entity{ + Kind: ac.ObjectType, + Identifier: ac.ObjectID, + } + + c.Logger.Infow("checking relationship tuples", "relation", ac.Relation, "object", obj.String()) + + checkReq := ofgaclient.ClientCheckRequest{ + User: sub.String(), + Relation: ac.Relation, + Object: obj.String(), + } + + return c.checkTuple(ctx, checkReq) +} + +// ListRelations returns the list of relations the user has with the object +func (c *Client) ListRelations(ctx context.Context, ac ListAccess) ([]string, error) { + if err := validateListAccess(ac); err != nil { + return nil, err + } + + if ac.SubjectType == "" { + ac.SubjectType = defaultSubject + } + + sub := Entity{ + Kind: Kind(ac.SubjectType), + Identifier: ac.SubjectID, + } + + obj := Entity{ + Kind: ac.ObjectType, + Identifier: ac.ObjectID, + } + + checks := []ofgaclient.ClientCheckRequest{} + + for _, rel := range ac.Relations { + check := ofgaclient.ClientCheckRequest{ + User: sub.String(), + Relation: rel, + Object: obj.String(), + } + + checks = append(checks, check) + } + + return c.batchCheckTuples(ctx, checks) +} + +// CheckOrgReadAccess checks if the user has read access to the organization +func (c *Client) CheckOrgReadAccess(ctx context.Context, ac AccessCheck) (bool, error) { + ac.ObjectType = organizationObject + ac.Relation = CanView // read access + + return c.CheckAccess(ctx, ac) +} + +// CheckOrgWriteAccess checks if the user has write access to the organization +func (c *Client) CheckOrgWriteAccess(ctx context.Context, ac AccessCheck) (bool, error) { + ac.ObjectType = organizationObject + ac.Relation = CanEdit // write access + + return c.CheckAccess(ctx, ac) +} + +// CheckOrgAccess checks if the user has access to the organization with the given relation +func (c *Client) CheckOrgAccess(ctx context.Context, ac AccessCheck) (bool, error) { + ac.ObjectType = organizationObject + + return c.CheckAccess(ctx, ac) +} + +// CheckGroupAccess checks if the user has access to the group with the given relation +func (c *Client) CheckGroupAccess(ctx context.Context, ac AccessCheck) (bool, error) { + ac.ObjectType = groupObject + + return c.CheckAccess(ctx, ac) +} + +// checkTuple checks the openFGA store for provided relationship tuple +func (c *Client) checkTuple(ctx context.Context, check ofgaclient.ClientCheckRequest) (bool, error) { + data, err := c.Ofga.Check(ctx).Body(check).Execute() + if err != nil { + c.Logger.Errorw("error checking tuple", "tuple", check, "error", err.Error()) + + return false, err + } + + return *data.Allowed, nil +} + +// batchCheckTuples checks the openFGA store for provided relationship tuples and returns the allowed relations +func (c *Client) batchCheckTuples(ctx context.Context, checks []ofgaclient.ClientCheckRequest) ([]string, error) { + res, err := c.Ofga.BatchCheck(ctx).Body(checks).Execute() + if err != nil || res == nil { + return nil, err + } + + relations := []string{} + + for _, r := range *res { + if r.Allowed != nil && *r.Allowed { + relations = append(relations, r.Request.Relation) + } + } + + return relations, nil +} + +// CheckSystemAdminRole checks if the user has system admin access +func (c *Client) CheckSystemAdminRole(ctx context.Context, userID string) (bool, error) { + ac := AccessCheck{ + ObjectType: roleObject, + ObjectID: SystemAdminRole, + Relation: RoleRelation, + SubjectID: userID, + SubjectType: userSubject, // admin roles are always user roles, never an API token + } + + return c.CheckAccess(ctx, ac) +} + +// validateAccessCheck checks if the AccessCheck struct is valid +func validateAccessCheck(ac AccessCheck) error { + if ac.SubjectID == "" { + return ErrInvalidAccessCheck + } + + if ac.ObjectType == "" { + return ErrInvalidAccessCheck + } + + if ac.ObjectID == "" { + return ErrInvalidAccessCheck + } + + if ac.Relation == "" { + return ErrInvalidAccessCheck + } + + return nil +} + +// validateListAccess checks if the ListAccess struct is valid +func validateListAccess(ac ListAccess) error { + if ac.SubjectID == "" { + return ErrInvalidAccessCheck + } + + if ac.ObjectType == "" { + return ErrInvalidAccessCheck + } + + if ac.ObjectID == "" { + return ErrInvalidAccessCheck + } + + return nil +} diff --git a/fgax/checks_test.go b/fgax/checks_test.go new file mode 100644 index 0000000..8827b74 --- /dev/null +++ b/fgax/checks_test.go @@ -0,0 +1,236 @@ +package fgax + +import ( + "context" + "testing" + + ofgaclient "github.com/openfga/go-sdk/client" + "github.com/stretchr/testify/assert" + + mock_fga "github.com/theopenlane/iam/fgax/mockery" +) + +func TestCheckTuple(t *testing.T) { + testCases := []struct { + name string + relation string + object string + expectedRes bool + errRes string + }{ + { + name: "happy path, valid tuple", + relation: "member", + object: "organization:openlane", + expectedRes: true, + errRes: "", + }, + { + name: "tuple does not exist", + relation: "member", + object: "organization:cat-friends", + expectedRes: false, + errRes: "", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + // setup mock client + c := mock_fga.NewMockSdkClient(t) + mc := NewMockFGAClient(t, c) + + // mock response for input + body := ofgaclient.ClientCheckRequest{ + User: "user:ulid-of-member", + Relation: tc.relation, + Object: tc.object, + } + + mock_fga.CheckAny(t, c, tc.expectedRes) + + // do request + valid, err := mc.checkTuple(context.Background(), body) + + if tc.errRes != "" { + assert.Error(t, err) + assert.ErrorContains(t, err, tc.errRes) + assert.Equal(t, tc.expectedRes, valid) + + return + } + + assert.NoError(t, err) + assert.Equal(t, tc.expectedRes, valid) + }) + } +} + +func TestCheckAccess(t *testing.T) { + tests := []struct { + name string + ac AccessCheck + expectedRes bool + wantErr bool + }{ + { + name: "happy path, valid access", + ac: AccessCheck{ + ObjectType: "organization", + ObjectID: "ulid-of-org", + Relation: "member", + SubjectID: "ulid-of-member", + }, + expectedRes: true, + wantErr: false, + }, + { + name: "happy path, valid access", + ac: AccessCheck{ + ObjectType: "organization", + ObjectID: "ulid-of-org", + SubjectType: "service", + Relation: "member", + SubjectID: "ulid-of-token", + }, + expectedRes: true, + wantErr: false, + }, + { + name: "missing object type", + ac: AccessCheck{ + ObjectID: "ulid-of-org", + Relation: "member", + SubjectID: "ulid-of-member", + }, + expectedRes: false, + wantErr: true, + }, + { + name: "missing relation", + ac: AccessCheck{ + ObjectType: "organization", + ObjectID: "ulid-of-org", + SubjectID: "ulid-of-member", + }, + expectedRes: false, + wantErr: true, + }, + { + name: "missing object type", + ac: AccessCheck{ + Relation: "member", + ObjectID: "ulid-of-org", + SubjectID: "ulid-of-member", + }, + expectedRes: false, + wantErr: true, + }, + { + name: "missing subject", + ac: AccessCheck{ + Relation: "member", + ObjectType: "organization", + ObjectID: "ulid-of-org", + }, + expectedRes: false, + wantErr: true, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // setup mock client + c := mock_fga.NewMockSdkClient(t) + mc := NewMockFGAClient(t, c) + + if tc.expectedRes { + mock_fga.CheckAny(t, c, tc.expectedRes) + } + + // do request + valid, err := mc.CheckAccess(context.Background(), tc.ac) + + if tc.wantErr { + assert.Error(t, err) + assert.Equal(t, tc.expectedRes, valid) + + return + } + + assert.NoError(t, err) + assert.Equal(t, tc.expectedRes, valid) + }) + } +} + +func TestListRelations(t *testing.T) { + tests := []struct { + name string + check ListAccess + expectedRes []string + wantErr bool + }{ + { + name: "happy path", + check: ListAccess{ + ObjectType: "organization", + ObjectID: "ulid-of-org", + Relations: []string{"can_delete", "can_view", "can_read"}, + SubjectID: "ulid-of-member", + }, + expectedRes: []string{"can_view", "can_read"}, + wantErr: false, + }, + { + name: "missing object type", + check: ListAccess{ + ObjectID: "ulid-of-org", + Relations: []string{"can_delete", "can_view", "can_read"}, + SubjectID: "ulid-of-member", + }, + wantErr: true, + }, + { + name: "missing object id", + check: ListAccess{ + ObjectType: "organization", + Relations: []string{"can_delete", "can_view", "can_read"}, + SubjectID: "ulid-of-member", + }, + wantErr: true, + }, + { + name: "missing subject id", + check: ListAccess{ + ObjectType: "organization", + ObjectID: "ulid-of-org", + Relations: []string{"can_delete", "can_view", "can_read"}, + }, + wantErr: true, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // setup mock client + c := mock_fga.NewMockSdkClient(t) + mc := NewMockFGAClient(t, c) + + if !tc.wantErr { + mock_fga.BatchCheck(t, c, tc.check.Relations, tc.expectedRes) + } + + // do request + valid, err := mc.ListRelations(context.Background(), tc.check) + + if tc.wantErr { + assert.Error(t, err) + assert.Equal(t, tc.expectedRes, valid) + + return + } + + assert.NoError(t, err) + assert.Equal(t, tc.expectedRes, valid) + }) + } +} diff --git a/fgax/doc.go b/fgax/doc.go new file mode 100644 index 0000000..a06b187 --- /dev/null +++ b/fgax/doc.go @@ -0,0 +1,3 @@ +// Package fgax includes client libraries to interact with openfga authorization +// credit to https://github.com/canonical/ofga/blob/main/tuples.go +package fgax diff --git a/fgax/errors.go b/fgax/errors.go new file mode 100644 index 0000000..b7914d9 --- /dev/null +++ b/fgax/errors.go @@ -0,0 +1,69 @@ +package fgax + +import ( + "errors" + "fmt" +) + +var ( + // ErrFGAMissingHost is returned when a host is not provided + ErrFGAMissingHost = errors.New("invalid OpenFGA config: missing host") + + // ErrMissingRelation is returned when a relation is empty in a tuple creation + ErrMissingRelation = errors.New("unable to create tuple, missing relation") + + // ErrInvalidAccessCheck is returned when a field required to check a tuple is empty + ErrInvalidAccessCheck = errors.New("unable to check tuple, missing required field") + + // ErrMissingObject is returned when a object is empty in a tuple creation + ErrMissingObject = errors.New("unable to create tuple, missing object") + + // ErrMissingObjectOnDeletion is returned when a object is empty in a tuple deletion + ErrMissingObjectOnDeletion = errors.New("unable to delete tuple, missing object") + + // ErrFailedToTransformModel is returned when the FGA model cannot be transformed to JSON + ErrFailedToTransformModel = errors.New("failed to transform fga model") + + // ErrMissingRequiredField is returned when a required field is missing + ErrMissingRequiredField = errors.New("missing required field") +) + +// InvalidEntityError is returned when an invalid openFGA entity is configured +type InvalidEntityError struct { + EntityRepresentation string +} + +// Error returns the InvalidEntityError in string format +func (e *InvalidEntityError) Error() string { + return fmt.Sprintf("invalid entity representation: %s", e.EntityRepresentation) +} + +func newInvalidEntityError(s string) *InvalidEntityError { + return &InvalidEntityError{ + EntityRepresentation: s, + } +} + +// WritingTuplesError is returned when an error is returned writing a relationship tuple +type WritingTuplesError struct { + User string + Relation string + Object string + Operation string + ErrorResponse error +} + +// Error returns the InvalidEntityError in string format +func (e *WritingTuplesError) Error() string { + return fmt.Sprintf("failed to %s tuple to OpenFGA store: (user: %s; relation: %s; object: %s), error: %v", e.Operation, e.User, e.Relation, e.Object, e.ErrorResponse.Error()) +} + +func newWritingTuplesError(user, relation, object, operation string, err error) *WritingTuplesError { + return &WritingTuplesError{ + User: user, + Relation: relation, + Object: object, + Operation: operation, + ErrorResponse: err, + } +} diff --git a/fgax/fga.go b/fgax/fga.go new file mode 100644 index 0000000..7454c88 --- /dev/null +++ b/fgax/fga.go @@ -0,0 +1,277 @@ +package fgax + +import ( + "context" + + openfga "github.com/openfga/go-sdk" + ofgaclient "github.com/openfga/go-sdk/client" + "github.com/openfga/go-sdk/credentials" + "go.uber.org/zap" +) + +// Client is an ofga client with some configuration +type Client struct { + // Ofga is the openFGA client + Ofga ofgaclient.SdkClient + // Config is the client configuration + Config ofgaclient.ClientConfiguration + // Logger is the provided Logger + Logger *zap.SugaredLogger +} + +// Config configures the openFGA setup +type Config struct { + // Enabled - checks this first before reading the config + Enabled bool `json:"enabled" koanf:"enabled" jsonschema:"description=enables authorization checks with openFGA" default:"true"` + // StoreName of the FGA Store + StoreName string `json:"storeName" koanf:"storeName" jsonschema:"description=name of openFGA store" default:"openlane"` + // HostURL of the fga API, replaces Host and Scheme settings + HostURL string `json:"hostUrl" koanf:"hostUrl" jsonschema:"description=host url with scheme of the openFGA API,required" default:"https://authz.theopenlane.io"` + // StoreID of the authorization store in FGA + StoreID string `json:"storeId" koanf:"storeId" jsonschema:"description=id of openFGA store"` + // ModelID that already exists in authorization store to be used + ModelID string `json:"modelId" koanf:"modelId" jsonschema:"description=id of openFGA model"` + // CreateNewModel force creates a new model, even if one already exists + CreateNewModel bool `json:"createNewModel" koanf:"createNewModel" jsonschema:"description=force create a new model, even if one already exists" default:"false"` + // ModelFile is the path to the model file + ModelFile string `json:"modelFile" koanf:"modelFile" jsonschema:"description=path to the fga model file" default:"fga/model/openlane.fga"` + // Credentials for the client + Credentials Credentials `json:"credentials" koanf:"credentials" jsonschema:"description=credentials for the openFGA client"` +} + +// Credentials for the openFGA client +type Credentials struct { + // APIToken is the token to use for the client, required if using API token authentication + APIToken string `json:"apiToken" koanf:"apiToken" jsonschema:"description=api token for the openFGA client, required if using pre-shared key authentication"` + // ClientID is the client ID to use for the client, required if using client credentials + ClientID string `json:"clientId" koanf:"clientId" jsonschema:"description=client id for the openFGA client, required if using client credentials authentication"` + // ClientSecret is the client secret to use for the client, required if using client credentials + ClientSecret string `json:"clientSecret" koanf:"clientSecret" jsonschema:"description=client secret for the openFGA client, required if using client credentials authentication"` + // Audience is the audience to use for the client, required if using client credentials + Audience string `json:"audience" koanf:"audience" jsonschema:"description=audience for the openFGA client"` + // Issuer is the issuer to use for the client, required if using client credentials + Issuer string `json:"issuer" koanf:"issuer" jsonschema:"description=issuer for the openFGA client"` + // Scopes is the scopes to use for the client, required if using client credentials + Scopes string `json:"scopes" koanf:"scopes" jsonschema:"description=scopes for the openFGA client"` +} + +// Option is a functional configuration option for openFGA client +type Option func(c *Client) + +// NewClient returns a wrapped OpenFGA API client ensuring all calls are made +// to the provided authorization model (id) and returns what is necessary. +func NewClient(host string, opts ...Option) (*Client, error) { + if host == "" { + return nil, ErrFGAMissingHost + } + + // The api host is the only required field when setting up a new FGA client connection + client := Client{ + Config: ofgaclient.ClientConfiguration{ + ApiUrl: host, + }, + } + + for _, opt := range opts { + opt(&client) + } + + fgaClient, err := ofgaclient.NewSdkClient(&client.Config) + if err != nil { + return nil, err + } + + client.Ofga = fgaClient + + return &client, err +} + +func (c *Client) GetModelID() string { + return c.Config.AuthorizationModelId +} + +// WithLogger sets logger +func WithLogger(l *zap.SugaredLogger) Option { + return func(c *Client) { + c.Logger = l + } +} + +// WithStoreID sets the store IDs, not needed when calling `CreateStore` or `ListStores` +func WithStoreID(storeID string) Option { + return func(c *Client) { + c.Config.StoreId = storeID + } +} + +// WithAuthorizationModelID sets the authorization model ID +func WithAuthorizationModelID(authModelID string) Option { + return func(c *Client) { + c.Config.AuthorizationModelId = authModelID + } +} + +// WithAPITokenCredentials sets the credentials for the client with an API token +func WithAPITokenCredentials(token string) Option { + return func(c *Client) { + c.Config.Credentials = &credentials.Credentials{ + Method: credentials.CredentialsMethodApiToken, + Config: &credentials.Config{ + ApiToken: token, + }, + } + } +} + +// WithClientCredentials sets the client credentials for the client with a client ID and secret +func WithClientCredentials(clientID, clientSecret, aud, issuer, scopes string) Option { + return func(c *Client) { + c.Config.Credentials = &credentials.Credentials{ + Method: credentials.CredentialsMethodClientCredentials, + Config: &credentials.Config{ + ClientCredentialsClientId: clientID, + ClientCredentialsClientSecret: clientSecret, + ClientCredentialsApiAudience: aud, + ClientCredentialsApiTokenIssuer: issuer, + ClientCredentialsScopes: scopes, + }, + } + } +} + +// WithToken sets the client credentials +func WithToken(token string) Option { + return func(c *Client) { + c.Config.Credentials = &credentials.Credentials{ + Method: credentials.CredentialsMethodApiToken, + Config: &credentials.Config{ + ApiToken: token, + }, + } + } +} + +// CreateFGAClientWithStore returns a Client with a store and model configured +func CreateFGAClientWithStore(ctx context.Context, c Config, l *zap.SugaredLogger) (*Client, error) { + // initialize options with logger + opts := []Option{ + WithLogger(l), + } + + // set credentials if provided + if c.Credentials.APIToken != "" { + opts = append(opts, WithAPITokenCredentials(c.Credentials.APIToken)) + } else if c.Credentials.ClientID != "" && c.Credentials.ClientSecret != "" { + opts = append(opts, WithClientCredentials( + c.Credentials.ClientID, + c.Credentials.ClientSecret, + c.Credentials.Audience, + c.Credentials.Issuer, + c.Credentials.Scopes, + )) + } + + // create store if an ID was not configured + if c.StoreID == "" { + // Create new store + fgaClient, err := NewClient( + c.HostURL, + opts..., + ) + if err != nil { + return nil, err + } + + c.StoreID, err = fgaClient.CreateStore(ctx, c.StoreName) + if err != nil { + return nil, err + } + } + + // add store ID to the options + opts = append(opts, WithStoreID(c.StoreID)) + + // create model if ID was not configured + if c.ModelID == "" { + // create fga client with store ID + fgaClient, err := NewClient( + c.HostURL, + opts..., + ) + if err != nil { + return nil, err + } + + // Create model if one does not already exist + modelID, err := fgaClient.CreateModelFromFile(ctx, c.ModelFile, c.CreateNewModel) + if err != nil { + return nil, err + } + + // Set ModelID in the config + c.ModelID = modelID + } + + // add model ID to the options + opts = append(opts, + WithAuthorizationModelID(c.ModelID), + ) + + // create fga client with store ID + return NewClient( + c.HostURL, + opts..., + ) +} + +// CreateStore creates a new fine grained authorization store and returns the store ID +func (c *Client) CreateStore(ctx context.Context, storeName string) (string, error) { + options := ofgaclient.ClientListStoresOptions{ + ContinuationToken: openfga.PtrString(""), + } + + stores, err := c.Ofga.ListStores(context.Background()).Options(options).Execute() + if err != nil { + return "", err + } + + // Only create a new test store if one does not exist + if len(stores.GetStores()) > 0 { + storeID := stores.GetStores()[0].Id + c.Logger.Infow("fga store exists", "store_id", storeID) + + return storeID, nil + } + + // Create new store + storeReq := c.Ofga.CreateStore(context.Background()) + + resp, err := storeReq.Body(ofgaclient.ClientCreateStoreRequest{ + Name: storeName, + }).Execute() + if err != nil { + return "", err + } + + storeID := resp.GetId() + + c.Logger.Infow("fga store created", "store_id", storeID) + + return storeID, nil +} + +// Healthcheck reads the model to check if the connection is working +func Healthcheck(client Client) func(ctx context.Context) error { + return func(ctx context.Context) error { + opts := ofgaclient.ClientReadAuthorizationModelOptions{ + AuthorizationModelId: &client.Config.AuthorizationModelId, + } + + _, err := client.Ofga.ReadAuthorizationModel(ctx).Options(opts).Execute() + if err != nil { + return err + } + + return nil + } +} diff --git a/fgax/list.go b/fgax/list.go new file mode 100644 index 0000000..8314732 --- /dev/null +++ b/fgax/list.go @@ -0,0 +1,169 @@ +package fgax + +import ( + "context" + "fmt" + + fgasdk "github.com/openfga/go-sdk" + ofgaclient "github.com/openfga/go-sdk/client" +) + +// ListRequest is the fields needed to list objects or users +type ListRequest struct { + // ObjectID is the identifier of the object that the subject is related to, required on ListUsers + ObjectID string + // ObjectType is the type of object that the subject is related to, required on ListUsers + ObjectType string + // SubjectID is the identifier of the subject that is related to the object, required on ListObjects + SubjectID string + // SubjectType is the type of subject that is related to the object, required on ListObjects + SubjectType string + // Relation is the relationship between the subject and object + Relation string +} + +// ListObjectsRequest creates the ClientListObjectsRequest and queries the FGA store for all objects with the user+relation +func (c *Client) ListObjectsRequest(ctx context.Context, req ListRequest) (*ofgaclient.ClientListObjectsResponse, error) { + // valid and set defaults + if err := req.validateListObjectsInput(); err != nil { + return nil, err + } + + sub := Entity{ + Kind: Kind(req.SubjectType), + Identifier: req.SubjectID, + } + + listReq := ofgaclient.ClientListObjectsRequest{ + User: sub.String(), + Relation: req.Relation, + Type: req.ObjectType, + } + + c.Logger.Debugw("listing objects", "relation", req.SubjectType, sub.String(), req.Relation, "type", req.ObjectType) + + return c.listObjects(ctx, listReq) +} + +// ListUserRequest creates the ClientListUserRequest and queries the FGA store for all users with the object+relation +func (c *Client) ListUserRequest(ctx context.Context, req ListRequest) (*ofgaclient.ClientListUsersResponse, error) { + if err := req.validateListUsersInput(); err != nil { + return nil, err + } + + // create the fga object + obj := fgasdk.FgaObject{ + Type: req.ObjectType, + Id: req.ObjectID, + } + + // compose the list request + listReq := ofgaclient.ClientListUsersRequest{ + Object: obj, + Relation: req.Relation, + UserFilters: []fgasdk.UserTypeFilter{{Type: req.SubjectType}}, + } + + c.Logger.Debugw("listing users", "relation", req.Relation, "object", obj.Id, "type", obj.Type) + + return c.listUsers(ctx, listReq) +} + +// listObjects checks the openFGA store for all objects associated with a user+relation +func (c *Client) listObjects(ctx context.Context, req ofgaclient.ClientListObjectsRequest) (*ofgaclient.ClientListObjectsResponse, error) { + list, err := c.Ofga.ListObjects(ctx).Body(req).Execute() + if err != nil { + c.Logger.Errorw("error listing objects", + "user", req.User, + "relation", req.Relation, + "type", req.Type, + "error", err.Error()) + + return nil, err + } + + return list, nil +} + +// listUsers checks the openFGA store for all users associated with a object+relation +func (c *Client) listUsers(ctx context.Context, req ofgaclient.ClientListUsersRequest) (*ofgaclient.ClientListUsersResponse, error) { + list, err := c.Ofga.ListUsers(ctx).Body(req).Execute() + if err != nil { + c.Logger.Errorw("error listing users", + "object", req.Object.Id, + "type", req.Object.Type, + "relation", req.Relation, + "error", err.Error()) + + return nil, err + } + + return list, nil +} + +func (r *ListRequest) setListRequestDefaults() { + // default to user type + if r.SubjectType == "" { + r.SubjectType = defaultSubject + } + + // default to view permissions + if r.Relation == "" { + r.Relation = CanView + } +} + +func (r *ListRequest) validateListObjectsInput() error { + if r.SubjectID == "" { + return fmt.Errorf("%w, subject_id", ErrMissingRequiredField) + } + + r.setListRequestDefaults() + + return nil +} + +func (r *ListRequest) validateListUsersInput() error { + if r.ObjectID == "" { + return fmt.Errorf("%w, object_id", ErrMissingRequiredField) + } + + r.setListRequestDefaults() + + return nil +} + +// ListContains checks the results of an fga ListObjects and parses the entities +// to get the identifier to compare to another identifier based on entity type +func ListContains(entityType string, l []string, i string) bool { + for _, o := range l { + e, _ := ParseEntity(o) + + // make sure its the correct entity type + if e.Kind.String() != entityType { + continue + } + + if i == e.Identifier { + return true + } + } + + return false +} + +// GetEntityIDs returns a list of identifiers from a list of objects +func GetEntityIDs(l *ofgaclient.ClientListObjectsResponse) ([]string, error) { + ids := make([]string, 0, len(l.Objects)) + + for _, o := range l.Objects { + e, err := ParseEntity(o) + if err != nil { + return nil, err + } + + ids = append(ids, e.Identifier) + } + + return ids, nil +} diff --git a/fgax/list_test.go b/fgax/list_test.go new file mode 100644 index 0000000..e974dcf --- /dev/null +++ b/fgax/list_test.go @@ -0,0 +1,428 @@ +package fgax + +import ( + "context" + "errors" + "fmt" + "testing" + + openfga "github.com/openfga/go-sdk" + ofgaclient "github.com/openfga/go-sdk/client" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + mock_fga "github.com/theopenlane/iam/fgax/mockery" +) + +func TestListContains(t *testing.T) { + testCases := []struct { + name string + objectID string + fgaObjects []string + expectedRes bool + }{ + { + name: "happy path, object found", + objectID: "TbaK4knu9NDoG85DAKob0", + fgaObjects: []string{ + "organization:TbaK4knu9NDoG85DAKob0", + "organization:-AV6JyT7-qmedy0WPOjKM", + "something-else:TbaK4knu9NDoG85DAKob0", + }, + expectedRes: true, + }, + { + name: "incorrect type but correct id, not found", + objectID: "TbaK4knu9NDoG85DAKob0", + fgaObjects: []string{ + "organization:GxSAidJu4LZzjcnHQ-KTV", + "organization:-AV6JyT7-qmedy0WPOjKM", + "something-else:TbaK4knu9NDoG85DAKob0", + }, + expectedRes: false, + }, + { + name: "id not found", + objectID: "TbaK4knu9NDoG85DAKob0", + fgaObjects: []string{ + "organization:GxSAidJu4LZzjcnHQ-KTV", + "organization:-AV6JyT7-qmedy0WPOjKM", + }, + expectedRes: false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + entityType := "organization" + found := ListContains(entityType, tc.fgaObjects, tc.objectID) + + assert.Equal(t, tc.expectedRes, found) + }) + } +} + +func TestListObjectsRequest(t *testing.T) { + objects := []string{"organization:openlane"} + testCases := []struct { + name string + relation string + userID string + subjectType string + objectType string + expectedRes *ofgaclient.ClientListObjectsResponse + errRes error + }{ + { + name: "happy path", + relation: "can_view", + userID: "ulid-of-user", + subjectType: "user", + objectType: "organization", + expectedRes: &openfga.ListObjectsResponse{ + Objects: objects, + }, + errRes: nil, + }, + { + name: "happy path, service account", + relation: "can_view", + userID: "ulid-of-token", + subjectType: "service", + objectType: "organization", + expectedRes: &openfga.ListObjectsResponse{ + Objects: objects, + }, + errRes: nil, + }, + { + name: "error response", + relation: "can_view", + userID: "ulid-of-user", + objectType: "organization", + expectedRes: nil, + errRes: errors.New("boom"), //nolint:err113 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + // setup mock client + mc := mock_fga.NewMockSdkClient(t) + + c := NewMockFGAClient(t, mc) + + // mock response for input + body := []string{ + "organization:openlane", + } + + mock_fga.ListOnce(t, mc, body, tc.errRes) + + // do request + req := ListRequest{ + SubjectID: tc.userID, + SubjectType: tc.subjectType, + ObjectType: tc.objectType, + Relation: tc.relation, + } + + resp, err := c.ListObjectsRequest( + context.Background(), + req, + ) + + if tc.errRes != nil { + assert.Error(t, err) + assert.Equal(t, err, tc.errRes) + assert.Equal(t, tc.expectedRes, resp) + + return + } + + assert.NoError(t, err) + assert.Equal(t, tc.expectedRes.GetObjects(), resp.GetObjects()) + }) + } +} + +func TestListUsersRequest(t *testing.T) { + users := []openfga.User{ + { + Object: &openfga.FgaObject{ + Type: "user", + Id: "mitb", + }, + }, + { + Object: &openfga.FgaObject{ + Type: "user", + Id: "funk", + }, + }, + } + + testCases := []struct { + name string + relation string + objectType string + objectID string + expectedRes *ofgaclient.ClientListUsersResponse + errRes error + }{ + { + name: "happy path", + relation: "can_view", + objectType: "organization", + objectID: "ulid-of-object", + expectedRes: &openfga.ListUsersResponse{ + Users: users, + }, + errRes: nil, + }, + { + name: "error response", + relation: "can_view", + objectType: "organization", + objectID: "ulid-of-object1", + expectedRes: nil, + errRes: errors.New("boom"), //nolint:err113 + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + // setup mock client + mc := mock_fga.NewMockSdkClient(t) + + c := NewMockFGAClient(t, mc) + + // mock response for input + mock_fga.ListUsers(t, mc, users, tc.errRes) + + req := ListRequest{ + ObjectID: tc.objectID, + ObjectType: tc.objectType, + Relation: tc.relation, + } + + // do request + resp, err := c.ListUserRequest( + context.Background(), + req, + ) + + if tc.errRes != nil { + assert.Error(t, err) + assert.Equal(t, err, tc.errRes) + assert.Equal(t, tc.expectedRes, resp) + + return + } + + assert.NoError(t, err) + assert.Equal(t, tc.expectedRes.GetUsers(), resp.GetUsers()) + }) + } +} + +func TestGetEntityIDs(t *testing.T) { + testCases := []struct { + name string + objects []string + expectedIDs []string + expectedErr string + }{ + { + name: "happy path", + objects: []string{"organization:openlane"}, + expectedIDs: []string{"openlane"}, + }, + { + name: "multiple objects", + objects: []string{"organization:openlane", "organization:another"}, + expectedIDs: []string{"openlane", "another"}, + }, + { + name: "empty objects", + objects: []string{}, + expectedIDs: []string{}, + }, + + { + name: "invalid object", + objects: []string{"organization"}, + expectedIDs: []string{}, + expectedErr: "invalid entity representation: organization", + }, + } + + for _, tc := range testCases { + response := &ofgaclient.ClientListObjectsResponse{ + Objects: tc.objects, + } + + ids, err := GetEntityIDs(response) + if tc.expectedErr != "" { + assert.Error(t, err) + assert.Nil(t, ids) + + return + } + + require.NoError(t, err) + assert.Equal(t, tc.expectedIDs, ids) + } +} + +func TestSetListRequestDefaults(t *testing.T) { + testCases := []struct { + name string + req ListRequest + expectedReq ListRequest + }{ + { + name: "set all", + req: ListRequest{}, + expectedReq: ListRequest{ + SubjectType: defaultSubject, + Relation: CanView, + }, + }, + { + name: "set default subject type", + req: ListRequest{ + Relation: CanEdit, + }, + expectedReq: ListRequest{ + SubjectType: defaultSubject, + Relation: CanEdit, + }, + }, + { + name: "set default relation", + req: ListRequest{ + SubjectType: "service", + }, + expectedReq: ListRequest{ + SubjectType: "service", + Relation: CanView, + }, + }, + { + name: "set none", + req: ListRequest{ + SubjectType: "service", + Relation: CanEdit, + }, + expectedReq: ListRequest{ + SubjectType: "service", + Relation: CanEdit, + }, + }, + } + + for _, tc := range testCases { + // Call the function to set the default values + tc.req.setListRequestDefaults() + + // Check if the default values are set correctly + assert.Equal(t, tc.expectedReq, tc.req) + } +} +func TestValidateListObjectsInput(t *testing.T) { + testCases := []struct { + name string + req ListRequest + expected error + }{ + { + name: "valid input", + req: ListRequest{ + SubjectID: "user123", + SubjectType: "user", + Relation: "can_view", + }, + expected: nil, + }, + { + name: "missing subject ID", + req: ListRequest{ + SubjectType: "user", + Relation: "can_view", + }, + expected: fmt.Errorf("%w, subject_id", ErrMissingRequiredField), + }, + { + name: "default subject type", + req: ListRequest{ + SubjectID: "user123", + Relation: "can_view", + }, + expected: nil, + }, + { + name: "default relation", + req: ListRequest{ + SubjectID: "user123", + SubjectType: "user", + }, + expected: nil, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + err := tc.req.validateListObjectsInput() + assert.Equal(t, tc.expected, err) + }) + } +} +func TestValidateListUsersInput(t *testing.T) { + testCases := []struct { + name string + req ListRequest + expected error + }{ + { + name: "valid input", + req: ListRequest{ + ObjectID: "object123", + ObjectType: "organization", + Relation: "can_view", + }, + expected: nil, + }, + { + name: "missing object ID", + req: ListRequest{ + ObjectType: "organization", + Relation: "can_view", + }, + expected: fmt.Errorf("%w, object_id", ErrMissingRequiredField), + }, + { + name: "default object type", + req: ListRequest{ + ObjectID: "object123", + Relation: "can_view", + }, + expected: nil, + }, + { + name: "default relation", + req: ListRequest{ + ObjectID: "object123", + ObjectType: "organization", + }, + expected: nil, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + err := tc.req.validateListUsersInput() + assert.Equal(t, tc.expected, err) + }) + } +} diff --git a/fgax/mockery/.mockery.yaml b/fgax/mockery/.mockery.yaml new file mode 100644 index 0000000..e3df641 --- /dev/null +++ b/fgax/mockery/.mockery.yaml @@ -0,0 +1,6 @@ +with-expecter: true +dir: . +all: true +disable-version-string: true +packages: + github.com/openfga/go-sdk/client: diff --git a/fgax/mockery/doc.go b/fgax/mockery/doc.go new file mode 100644 index 0000000..3979322 --- /dev/null +++ b/fgax/mockery/doc.go @@ -0,0 +1,4 @@ +// Package client includes the mock FGA client generated by testify mockery +// +//go:generate mockery --config .mockery.yaml +package client diff --git a/fgax/mockery/helpers.go b/fgax/mockery/helpers.go new file mode 100644 index 0000000..8463ccd --- /dev/null +++ b/fgax/mockery/helpers.go @@ -0,0 +1,236 @@ +package client + +import ( + "errors" + "slices" + "testing" + + openfga "github.com/openfga/go-sdk" + ofgaclient "github.com/openfga/go-sdk/client" + mock "github.com/stretchr/testify/mock" +) + +// ClearMocks is used to clear mocks in a test loop +// easiest to use `def mock_fga.ClearMocks(c)` so no matter how the test exits +// mocks are always cleared before the next test case +func ClearMocks(c *MockSdkClient) { + c.ExpectedCalls = c.ExpectedCalls[:0] +} + +// WriteAny creates mock write responses based on the mock FGA client for +// any times in a test +func WriteAny(t *testing.T, c *MockSdkClient) { + wi := NewMockSdkClientWriteRequestInterface(t) + + expectedResponse := ofgaclient.ClientWriteResponse{ + Writes: []ofgaclient.ClientWriteRequestWriteResponse{ + { + Status: ofgaclient.SUCCESS, + }, + }, + Deletes: []ofgaclient.ClientWriteRequestDeleteResponse{ + { + Status: ofgaclient.SUCCESS, + }, + }, + } + + wi.EXPECT().Execute().Return(&expectedResponse, nil) + + wi.EXPECT().Options(mock.Anything).Return(wi) + + wi.EXPECT().Body(mock.Anything).Return(wi) + + c.EXPECT().Write(mock.Anything).Return(wi) +} + +// WriteOnce creates mock write responses based on the mock FGA client +// one time per test +func WriteOnce(t *testing.T, c *MockSdkClient) { + wi := NewMockSdkClientWriteRequestInterface(t) + + expectedResponse := ofgaclient.ClientWriteResponse{ + Writes: []ofgaclient.ClientWriteRequestWriteResponse{ + { + Status: ofgaclient.SUCCESS, + }, + }, + Deletes: []ofgaclient.ClientWriteRequestDeleteResponse{ + { + Status: ofgaclient.SUCCESS, + }, + }, + } + + wi.EXPECT().Execute().Return(&expectedResponse, nil) + + wi.EXPECT().Options(mock.Anything).Return(wi) + + wi.EXPECT().Body(mock.Anything).Return(wi) + + c.EXPECT().Write(mock.Anything).Return(wi).Once() +} + +// WriteError creates mock write error response based on the mock FGA client for +// any times in a test +func WriteError(t *testing.T, c *MockSdkClient, err error) { + wi := NewMockSdkClientWriteRequestInterface(t) + + expectedResponse := ofgaclient.ClientWriteResponse{ + Writes: []ofgaclient.ClientWriteRequestWriteResponse{ + { + Status: ofgaclient.FAILURE, + Error: err, + }, + }, + Deletes: []ofgaclient.ClientWriteRequestDeleteResponse{ + { + Status: ofgaclient.SUCCESS, + Error: err, + }, + }, + } + + wi.EXPECT().Execute().Return(&expectedResponse, err) + + wi.EXPECT().Options(mock.Anything).Return(wi) + + wi.EXPECT().Body(mock.Anything).Return(wi) + + c.EXPECT().Write(mock.Anything).Return(wi) +} + +// ListAny mocks a list request for any times in a test +func ListAny(t *testing.T, c *MockSdkClient, allowedObjects []string) { + lr := NewMockSdkClientListObjectsRequestInterface(t) + + resp := ofgaclient.ClientListObjectsResponse{} + resp.SetObjects(allowedObjects) + + lr.EXPECT().Execute().Return(&resp, nil) + + lr.EXPECT().Body(mock.Anything).Return(lr) + + c.EXPECT().ListObjects(mock.Anything).Return(lr) +} + +// ListOnce mocks a list request once with a allowed objects and error if provided +func ListOnce(t *testing.T, c *MockSdkClient, allowedObjects []string, err error) { + lr := NewMockSdkClientListObjectsRequestInterface(t) + + resp := ofgaclient.ClientListObjectsResponse{} + resp.SetObjects(allowedObjects) + + lr.EXPECT().Execute().Return(&resp, err) + + lr.EXPECT().Body(mock.Anything).Return(lr) + + c.EXPECT().ListObjects(mock.Anything).Return(lr).Once() +} + +// ListOnce mocks a list request once with a allowed objects and error if provided +func ListUsers(t *testing.T, c *MockSdkClient, allowedUsers []openfga.User, err error) { + lr := NewMockSdkClientListUsersRequestInterface(t) + + resp := ofgaclient.ClientListUsersResponse{} + resp.SetUsers(allowedUsers) + + lr.EXPECT().Execute().Return(&resp, err) + + lr.EXPECT().Body(mock.Anything).Return(lr) + + c.EXPECT().ListUsers(mock.Anything).Return(lr).Once() +} + +// ListTimes mocks a list request for the specified number of times in a test +func ListTimes(t *testing.T, c *MockSdkClient, allowedObjects []string, times int) { + lr := NewMockSdkClientListObjectsRequestInterface(t) + + resp := ofgaclient.ClientListObjectsResponse{} + resp.SetObjects(allowedObjects) + + lr.EXPECT().Execute().Return(&resp, nil) + + lr.EXPECT().Body(mock.Anything).Return(lr) + + c.EXPECT().ListObjects(mock.Anything).Return(lr).Times(times) +} + +// ReadAny mocks a read request for any times in a test +func ReadAny(t *testing.T, c *MockSdkClient) { + rr := NewMockSdkClientReadRequestInterface(t) + + rr.EXPECT().Execute().Return(&ofgaclient.ClientReadResponse{}, nil) + + rr.EXPECT().Options(mock.Anything).Return(rr) + + c.EXPECT().Read(mock.Anything).Return(rr) +} + +// CheckAny mocks a check request for any times in a test +func CheckAny(t *testing.T, c *MockSdkClient, allowed bool) { + cr := NewMockSdkClientCheckRequestInterface(t) + + resp := ofgaclient.ClientCheckResponse{ + CheckResponse: openfga.CheckResponse{ + Allowed: openfga.PtrBool(allowed), + }, + } + + cr.EXPECT().Execute().Return(&resp, nil) + + cr.EXPECT().Body(mock.Anything).Return(cr) + + c.EXPECT().Check(mock.Anything).Return(cr) +} + +// CheckAny mocks a check request for any times in a test +func BatchCheck(t *testing.T, c *MockSdkClient, list []string, allowed []string) { + batch := NewMockSdkClientBatchCheckRequestInterface(t) + + resp := []ofgaclient.ClientBatchCheckSingleResponse{} + + for _, relation := range list { + result := false + if slices.Contains(allowed, relation) { + result = true + } + + ccr := ofgaclient.ClientCheckResponse{} + ccr.SetAllowed(result) + + checkResp := ofgaclient.ClientBatchCheckSingleResponse{ + Request: ofgaclient.ClientCheckRequest{ + Relation: relation, + }, + ClientCheckResponse: ccr, + } + + resp = append(resp, checkResp) + } + + batch.EXPECT().Execute().Return(&resp, nil) + + batch.EXPECT().Body(mock.Anything).Return(batch) + + c.EXPECT().BatchCheck(mock.Anything).Return(batch) +} + +// DeleteAny creates mock delete responses based on the mock FGA client for +// any times in a test +func DeleteAny(t *testing.T, c *MockSdkClient, errMsg string) { + di := NewMockSdkClientDeleteTuplesRequestInterface(t) + + var err error + if errMsg != "" { + err = errors.New(errMsg) // nolint:err113 + } + + di.EXPECT().Execute().Return(&ofgaclient.ClientWriteResponse{}, err) + + di.EXPECT().Options(mock.Anything).Return(di) + + di.EXPECT().Body(mock.Anything).Return(di) + + c.EXPECT().DeleteTuples(mock.Anything).Return(di) +} diff --git a/fgax/mockery/mock_SdkClient.go b/fgax/mockery/mock_SdkClient.go new file mode 100644 index 0000000..7a69a05 --- /dev/null +++ b/fgax/mockery/mock_SdkClient.go @@ -0,0 +1,2266 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClient is an autogenerated mock type for the SdkClient type +type MockSdkClient struct { + mock.Mock +} + +type MockSdkClient_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClient) EXPECT() *MockSdkClient_Expecter { + return &MockSdkClient_Expecter{mock: &_m.Mock} +} + +// BatchCheck provides a mock function with given fields: ctx +func (_m *MockSdkClient) BatchCheck(ctx context.Context) client.SdkClientBatchCheckRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for BatchCheck") + } + + var r0 client.SdkClientBatchCheckRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientBatchCheckRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientBatchCheckRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_BatchCheck_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchCheck' +type MockSdkClient_BatchCheck_Call struct { + *mock.Call +} + +// BatchCheck is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) BatchCheck(ctx interface{}) *MockSdkClient_BatchCheck_Call { + return &MockSdkClient_BatchCheck_Call{Call: _e.mock.On("BatchCheck", ctx)} +} + +func (_c *MockSdkClient_BatchCheck_Call) Run(run func(ctx context.Context)) *MockSdkClient_BatchCheck_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_BatchCheck_Call) Return(_a0 client.SdkClientBatchCheckRequestInterface) *MockSdkClient_BatchCheck_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_BatchCheck_Call) RunAndReturn(run func(context.Context) client.SdkClientBatchCheckRequestInterface) *MockSdkClient_BatchCheck_Call { + _c.Call.Return(run) + return _c +} + +// BatchCheckExecute provides a mock function with given fields: request +func (_m *MockSdkClient) BatchCheckExecute(request client.SdkClientBatchCheckRequestInterface) (*[]client.ClientBatchCheckSingleResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for BatchCheckExecute") + } + + var r0 *[]client.ClientBatchCheckSingleResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientBatchCheckRequestInterface) (*[]client.ClientBatchCheckSingleResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientBatchCheckRequestInterface) *[]client.ClientBatchCheckSingleResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*[]client.ClientBatchCheckSingleResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientBatchCheckRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_BatchCheckExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BatchCheckExecute' +type MockSdkClient_BatchCheckExecute_Call struct { + *mock.Call +} + +// BatchCheckExecute is a helper method to define mock.On call +// - request client.SdkClientBatchCheckRequestInterface +func (_e *MockSdkClient_Expecter) BatchCheckExecute(request interface{}) *MockSdkClient_BatchCheckExecute_Call { + return &MockSdkClient_BatchCheckExecute_Call{Call: _e.mock.On("BatchCheckExecute", request)} +} + +func (_c *MockSdkClient_BatchCheckExecute_Call) Run(run func(request client.SdkClientBatchCheckRequestInterface)) *MockSdkClient_BatchCheckExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientBatchCheckRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_BatchCheckExecute_Call) Return(_a0 *[]client.ClientBatchCheckSingleResponse, _a1 error) *MockSdkClient_BatchCheckExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_BatchCheckExecute_Call) RunAndReturn(run func(client.SdkClientBatchCheckRequestInterface) (*[]client.ClientBatchCheckSingleResponse, error)) *MockSdkClient_BatchCheckExecute_Call { + _c.Call.Return(run) + return _c +} + +// Check provides a mock function with given fields: ctx +func (_m *MockSdkClient) Check(ctx context.Context) client.SdkClientCheckRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for Check") + } + + var r0 client.SdkClientCheckRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientCheckRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientCheckRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_Check_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Check' +type MockSdkClient_Check_Call struct { + *mock.Call +} + +// Check is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) Check(ctx interface{}) *MockSdkClient_Check_Call { + return &MockSdkClient_Check_Call{Call: _e.mock.On("Check", ctx)} +} + +func (_c *MockSdkClient_Check_Call) Run(run func(ctx context.Context)) *MockSdkClient_Check_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_Check_Call) Return(_a0 client.SdkClientCheckRequestInterface) *MockSdkClient_Check_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_Check_Call) RunAndReturn(run func(context.Context) client.SdkClientCheckRequestInterface) *MockSdkClient_Check_Call { + _c.Call.Return(run) + return _c +} + +// CheckExecute provides a mock function with given fields: request +func (_m *MockSdkClient) CheckExecute(request client.SdkClientCheckRequestInterface) (*client.ClientCheckResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for CheckExecute") + } + + var r0 *client.ClientCheckResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientCheckRequestInterface) (*client.ClientCheckResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientCheckRequestInterface) *client.ClientCheckResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientCheckResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientCheckRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_CheckExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CheckExecute' +type MockSdkClient_CheckExecute_Call struct { + *mock.Call +} + +// CheckExecute is a helper method to define mock.On call +// - request client.SdkClientCheckRequestInterface +func (_e *MockSdkClient_Expecter) CheckExecute(request interface{}) *MockSdkClient_CheckExecute_Call { + return &MockSdkClient_CheckExecute_Call{Call: _e.mock.On("CheckExecute", request)} +} + +func (_c *MockSdkClient_CheckExecute_Call) Run(run func(request client.SdkClientCheckRequestInterface)) *MockSdkClient_CheckExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientCheckRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_CheckExecute_Call) Return(_a0 *client.ClientCheckResponse, _a1 error) *MockSdkClient_CheckExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_CheckExecute_Call) RunAndReturn(run func(client.SdkClientCheckRequestInterface) (*client.ClientCheckResponse, error)) *MockSdkClient_CheckExecute_Call { + _c.Call.Return(run) + return _c +} + +// CreateStore provides a mock function with given fields: ctx +func (_m *MockSdkClient) CreateStore(ctx context.Context) client.SdkClientCreateStoreRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for CreateStore") + } + + var r0 client.SdkClientCreateStoreRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientCreateStoreRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientCreateStoreRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_CreateStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateStore' +type MockSdkClient_CreateStore_Call struct { + *mock.Call +} + +// CreateStore is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) CreateStore(ctx interface{}) *MockSdkClient_CreateStore_Call { + return &MockSdkClient_CreateStore_Call{Call: _e.mock.On("CreateStore", ctx)} +} + +func (_c *MockSdkClient_CreateStore_Call) Run(run func(ctx context.Context)) *MockSdkClient_CreateStore_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_CreateStore_Call) Return(_a0 client.SdkClientCreateStoreRequestInterface) *MockSdkClient_CreateStore_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_CreateStore_Call) RunAndReturn(run func(context.Context) client.SdkClientCreateStoreRequestInterface) *MockSdkClient_CreateStore_Call { + _c.Call.Return(run) + return _c +} + +// CreateStoreExecute provides a mock function with given fields: request +func (_m *MockSdkClient) CreateStoreExecute(request client.SdkClientCreateStoreRequestInterface) (*openfga.CreateStoreResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for CreateStoreExecute") + } + + var r0 *openfga.CreateStoreResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientCreateStoreRequestInterface) (*openfga.CreateStoreResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientCreateStoreRequestInterface) *openfga.CreateStoreResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.CreateStoreResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientCreateStoreRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_CreateStoreExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateStoreExecute' +type MockSdkClient_CreateStoreExecute_Call struct { + *mock.Call +} + +// CreateStoreExecute is a helper method to define mock.On call +// - request client.SdkClientCreateStoreRequestInterface +func (_e *MockSdkClient_Expecter) CreateStoreExecute(request interface{}) *MockSdkClient_CreateStoreExecute_Call { + return &MockSdkClient_CreateStoreExecute_Call{Call: _e.mock.On("CreateStoreExecute", request)} +} + +func (_c *MockSdkClient_CreateStoreExecute_Call) Run(run func(request client.SdkClientCreateStoreRequestInterface)) *MockSdkClient_CreateStoreExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientCreateStoreRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_CreateStoreExecute_Call) Return(_a0 *openfga.CreateStoreResponse, _a1 error) *MockSdkClient_CreateStoreExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_CreateStoreExecute_Call) RunAndReturn(run func(client.SdkClientCreateStoreRequestInterface) (*openfga.CreateStoreResponse, error)) *MockSdkClient_CreateStoreExecute_Call { + _c.Call.Return(run) + return _c +} + +// DeleteStore provides a mock function with given fields: ctx +func (_m *MockSdkClient) DeleteStore(ctx context.Context) client.SdkClientDeleteStoreRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for DeleteStore") + } + + var r0 client.SdkClientDeleteStoreRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientDeleteStoreRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientDeleteStoreRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_DeleteStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteStore' +type MockSdkClient_DeleteStore_Call struct { + *mock.Call +} + +// DeleteStore is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) DeleteStore(ctx interface{}) *MockSdkClient_DeleteStore_Call { + return &MockSdkClient_DeleteStore_Call{Call: _e.mock.On("DeleteStore", ctx)} +} + +func (_c *MockSdkClient_DeleteStore_Call) Run(run func(ctx context.Context)) *MockSdkClient_DeleteStore_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_DeleteStore_Call) Return(_a0 client.SdkClientDeleteStoreRequestInterface) *MockSdkClient_DeleteStore_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_DeleteStore_Call) RunAndReturn(run func(context.Context) client.SdkClientDeleteStoreRequestInterface) *MockSdkClient_DeleteStore_Call { + _c.Call.Return(run) + return _c +} + +// DeleteStoreExecute provides a mock function with given fields: request +func (_m *MockSdkClient) DeleteStoreExecute(request client.SdkClientDeleteStoreRequestInterface) (*client.ClientDeleteStoreResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for DeleteStoreExecute") + } + + var r0 *client.ClientDeleteStoreResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientDeleteStoreRequestInterface) (*client.ClientDeleteStoreResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientDeleteStoreRequestInterface) *client.ClientDeleteStoreResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientDeleteStoreResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientDeleteStoreRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_DeleteStoreExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteStoreExecute' +type MockSdkClient_DeleteStoreExecute_Call struct { + *mock.Call +} + +// DeleteStoreExecute is a helper method to define mock.On call +// - request client.SdkClientDeleteStoreRequestInterface +func (_e *MockSdkClient_Expecter) DeleteStoreExecute(request interface{}) *MockSdkClient_DeleteStoreExecute_Call { + return &MockSdkClient_DeleteStoreExecute_Call{Call: _e.mock.On("DeleteStoreExecute", request)} +} + +func (_c *MockSdkClient_DeleteStoreExecute_Call) Run(run func(request client.SdkClientDeleteStoreRequestInterface)) *MockSdkClient_DeleteStoreExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientDeleteStoreRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_DeleteStoreExecute_Call) Return(_a0 *client.ClientDeleteStoreResponse, _a1 error) *MockSdkClient_DeleteStoreExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_DeleteStoreExecute_Call) RunAndReturn(run func(client.SdkClientDeleteStoreRequestInterface) (*client.ClientDeleteStoreResponse, error)) *MockSdkClient_DeleteStoreExecute_Call { + _c.Call.Return(run) + return _c +} + +// DeleteTuples provides a mock function with given fields: ctx +func (_m *MockSdkClient) DeleteTuples(ctx context.Context) client.SdkClientDeleteTuplesRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for DeleteTuples") + } + + var r0 client.SdkClientDeleteTuplesRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientDeleteTuplesRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientDeleteTuplesRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_DeleteTuples_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteTuples' +type MockSdkClient_DeleteTuples_Call struct { + *mock.Call +} + +// DeleteTuples is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) DeleteTuples(ctx interface{}) *MockSdkClient_DeleteTuples_Call { + return &MockSdkClient_DeleteTuples_Call{Call: _e.mock.On("DeleteTuples", ctx)} +} + +func (_c *MockSdkClient_DeleteTuples_Call) Run(run func(ctx context.Context)) *MockSdkClient_DeleteTuples_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_DeleteTuples_Call) Return(_a0 client.SdkClientDeleteTuplesRequestInterface) *MockSdkClient_DeleteTuples_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_DeleteTuples_Call) RunAndReturn(run func(context.Context) client.SdkClientDeleteTuplesRequestInterface) *MockSdkClient_DeleteTuples_Call { + _c.Call.Return(run) + return _c +} + +// DeleteTuplesExecute provides a mock function with given fields: request +func (_m *MockSdkClient) DeleteTuplesExecute(request client.SdkClientDeleteTuplesRequestInterface) (*client.ClientWriteResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for DeleteTuplesExecute") + } + + var r0 *client.ClientWriteResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientDeleteTuplesRequestInterface) (*client.ClientWriteResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientDeleteTuplesRequestInterface) *client.ClientWriteResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientDeleteTuplesRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_DeleteTuplesExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteTuplesExecute' +type MockSdkClient_DeleteTuplesExecute_Call struct { + *mock.Call +} + +// DeleteTuplesExecute is a helper method to define mock.On call +// - request client.SdkClientDeleteTuplesRequestInterface +func (_e *MockSdkClient_Expecter) DeleteTuplesExecute(request interface{}) *MockSdkClient_DeleteTuplesExecute_Call { + return &MockSdkClient_DeleteTuplesExecute_Call{Call: _e.mock.On("DeleteTuplesExecute", request)} +} + +func (_c *MockSdkClient_DeleteTuplesExecute_Call) Run(run func(request client.SdkClientDeleteTuplesRequestInterface)) *MockSdkClient_DeleteTuplesExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientDeleteTuplesRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_DeleteTuplesExecute_Call) Return(_a0 *client.ClientWriteResponse, _a1 error) *MockSdkClient_DeleteTuplesExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_DeleteTuplesExecute_Call) RunAndReturn(run func(client.SdkClientDeleteTuplesRequestInterface) (*client.ClientWriteResponse, error)) *MockSdkClient_DeleteTuplesExecute_Call { + _c.Call.Return(run) + return _c +} + +// Expand provides a mock function with given fields: ctx +func (_m *MockSdkClient) Expand(ctx context.Context) client.SdkClientExpandRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for Expand") + } + + var r0 client.SdkClientExpandRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientExpandRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientExpandRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_Expand_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Expand' +type MockSdkClient_Expand_Call struct { + *mock.Call +} + +// Expand is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) Expand(ctx interface{}) *MockSdkClient_Expand_Call { + return &MockSdkClient_Expand_Call{Call: _e.mock.On("Expand", ctx)} +} + +func (_c *MockSdkClient_Expand_Call) Run(run func(ctx context.Context)) *MockSdkClient_Expand_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_Expand_Call) Return(_a0 client.SdkClientExpandRequestInterface) *MockSdkClient_Expand_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_Expand_Call) RunAndReturn(run func(context.Context) client.SdkClientExpandRequestInterface) *MockSdkClient_Expand_Call { + _c.Call.Return(run) + return _c +} + +// ExpandExecute provides a mock function with given fields: request +func (_m *MockSdkClient) ExpandExecute(request client.SdkClientExpandRequestInterface) (*openfga.ExpandResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for ExpandExecute") + } + + var r0 *openfga.ExpandResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientExpandRequestInterface) (*openfga.ExpandResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientExpandRequestInterface) *openfga.ExpandResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ExpandResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientExpandRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ExpandExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ExpandExecute' +type MockSdkClient_ExpandExecute_Call struct { + *mock.Call +} + +// ExpandExecute is a helper method to define mock.On call +// - request client.SdkClientExpandRequestInterface +func (_e *MockSdkClient_Expecter) ExpandExecute(request interface{}) *MockSdkClient_ExpandExecute_Call { + return &MockSdkClient_ExpandExecute_Call{Call: _e.mock.On("ExpandExecute", request)} +} + +func (_c *MockSdkClient_ExpandExecute_Call) Run(run func(request client.SdkClientExpandRequestInterface)) *MockSdkClient_ExpandExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientExpandRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ExpandExecute_Call) Return(_a0 *openfga.ExpandResponse, _a1 error) *MockSdkClient_ExpandExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ExpandExecute_Call) RunAndReturn(run func(client.SdkClientExpandRequestInterface) (*openfga.ExpandResponse, error)) *MockSdkClient_ExpandExecute_Call { + _c.Call.Return(run) + return _c +} + +// GetStore provides a mock function with given fields: ctx +func (_m *MockSdkClient) GetStore(ctx context.Context) client.SdkClientGetStoreRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for GetStore") + } + + var r0 client.SdkClientGetStoreRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientGetStoreRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientGetStoreRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_GetStore_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStore' +type MockSdkClient_GetStore_Call struct { + *mock.Call +} + +// GetStore is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) GetStore(ctx interface{}) *MockSdkClient_GetStore_Call { + return &MockSdkClient_GetStore_Call{Call: _e.mock.On("GetStore", ctx)} +} + +func (_c *MockSdkClient_GetStore_Call) Run(run func(ctx context.Context)) *MockSdkClient_GetStore_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_GetStore_Call) Return(_a0 client.SdkClientGetStoreRequestInterface) *MockSdkClient_GetStore_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_GetStore_Call) RunAndReturn(run func(context.Context) client.SdkClientGetStoreRequestInterface) *MockSdkClient_GetStore_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreExecute provides a mock function with given fields: request +func (_m *MockSdkClient) GetStoreExecute(request client.SdkClientGetStoreRequestInterface) (*openfga.GetStoreResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for GetStoreExecute") + } + + var r0 *openfga.GetStoreResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientGetStoreRequestInterface) (*openfga.GetStoreResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientGetStoreRequestInterface) *openfga.GetStoreResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.GetStoreResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientGetStoreRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_GetStoreExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreExecute' +type MockSdkClient_GetStoreExecute_Call struct { + *mock.Call +} + +// GetStoreExecute is a helper method to define mock.On call +// - request client.SdkClientGetStoreRequestInterface +func (_e *MockSdkClient_Expecter) GetStoreExecute(request interface{}) *MockSdkClient_GetStoreExecute_Call { + return &MockSdkClient_GetStoreExecute_Call{Call: _e.mock.On("GetStoreExecute", request)} +} + +func (_c *MockSdkClient_GetStoreExecute_Call) Run(run func(request client.SdkClientGetStoreRequestInterface)) *MockSdkClient_GetStoreExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientGetStoreRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_GetStoreExecute_Call) Return(_a0 *openfga.GetStoreResponse, _a1 error) *MockSdkClient_GetStoreExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_GetStoreExecute_Call) RunAndReturn(run func(client.SdkClientGetStoreRequestInterface) (*openfga.GetStoreResponse, error)) *MockSdkClient_GetStoreExecute_Call { + _c.Call.Return(run) + return _c +} + +// ListObjects provides a mock function with given fields: ctx +func (_m *MockSdkClient) ListObjects(ctx context.Context) client.SdkClientListObjectsRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for ListObjects") + } + + var r0 client.SdkClientListObjectsRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientListObjectsRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListObjectsRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_ListObjects_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListObjects' +type MockSdkClient_ListObjects_Call struct { + *mock.Call +} + +// ListObjects is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) ListObjects(ctx interface{}) *MockSdkClient_ListObjects_Call { + return &MockSdkClient_ListObjects_Call{Call: _e.mock.On("ListObjects", ctx)} +} + +func (_c *MockSdkClient_ListObjects_Call) Run(run func(ctx context.Context)) *MockSdkClient_ListObjects_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_ListObjects_Call) Return(_a0 client.SdkClientListObjectsRequestInterface) *MockSdkClient_ListObjects_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_ListObjects_Call) RunAndReturn(run func(context.Context) client.SdkClientListObjectsRequestInterface) *MockSdkClient_ListObjects_Call { + _c.Call.Return(run) + return _c +} + +// ListObjectsExecute provides a mock function with given fields: request +func (_m *MockSdkClient) ListObjectsExecute(request client.SdkClientListObjectsRequestInterface) (*openfga.ListObjectsResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for ListObjectsExecute") + } + + var r0 *openfga.ListObjectsResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientListObjectsRequestInterface) (*openfga.ListObjectsResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientListObjectsRequestInterface) *openfga.ListObjectsResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ListObjectsResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientListObjectsRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ListObjectsExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListObjectsExecute' +type MockSdkClient_ListObjectsExecute_Call struct { + *mock.Call +} + +// ListObjectsExecute is a helper method to define mock.On call +// - request client.SdkClientListObjectsRequestInterface +func (_e *MockSdkClient_Expecter) ListObjectsExecute(request interface{}) *MockSdkClient_ListObjectsExecute_Call { + return &MockSdkClient_ListObjectsExecute_Call{Call: _e.mock.On("ListObjectsExecute", request)} +} + +func (_c *MockSdkClient_ListObjectsExecute_Call) Run(run func(request client.SdkClientListObjectsRequestInterface)) *MockSdkClient_ListObjectsExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientListObjectsRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ListObjectsExecute_Call) Return(_a0 *openfga.ListObjectsResponse, _a1 error) *MockSdkClient_ListObjectsExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ListObjectsExecute_Call) RunAndReturn(run func(client.SdkClientListObjectsRequestInterface) (*openfga.ListObjectsResponse, error)) *MockSdkClient_ListObjectsExecute_Call { + _c.Call.Return(run) + return _c +} + +// ListRelations provides a mock function with given fields: ctx +func (_m *MockSdkClient) ListRelations(ctx context.Context) client.SdkClientListRelationsRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for ListRelations") + } + + var r0 client.SdkClientListRelationsRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientListRelationsRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListRelationsRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_ListRelations_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListRelations' +type MockSdkClient_ListRelations_Call struct { + *mock.Call +} + +// ListRelations is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) ListRelations(ctx interface{}) *MockSdkClient_ListRelations_Call { + return &MockSdkClient_ListRelations_Call{Call: _e.mock.On("ListRelations", ctx)} +} + +func (_c *MockSdkClient_ListRelations_Call) Run(run func(ctx context.Context)) *MockSdkClient_ListRelations_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_ListRelations_Call) Return(_a0 client.SdkClientListRelationsRequestInterface) *MockSdkClient_ListRelations_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_ListRelations_Call) RunAndReturn(run func(context.Context) client.SdkClientListRelationsRequestInterface) *MockSdkClient_ListRelations_Call { + _c.Call.Return(run) + return _c +} + +// ListRelationsExecute provides a mock function with given fields: request +func (_m *MockSdkClient) ListRelationsExecute(request client.SdkClientListRelationsRequestInterface) (*client.ClientListRelationsResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for ListRelationsExecute") + } + + var r0 *client.ClientListRelationsResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientListRelationsRequestInterface) (*client.ClientListRelationsResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientListRelationsRequestInterface) *client.ClientListRelationsResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientListRelationsResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientListRelationsRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ListRelationsExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListRelationsExecute' +type MockSdkClient_ListRelationsExecute_Call struct { + *mock.Call +} + +// ListRelationsExecute is a helper method to define mock.On call +// - request client.SdkClientListRelationsRequestInterface +func (_e *MockSdkClient_Expecter) ListRelationsExecute(request interface{}) *MockSdkClient_ListRelationsExecute_Call { + return &MockSdkClient_ListRelationsExecute_Call{Call: _e.mock.On("ListRelationsExecute", request)} +} + +func (_c *MockSdkClient_ListRelationsExecute_Call) Run(run func(request client.SdkClientListRelationsRequestInterface)) *MockSdkClient_ListRelationsExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientListRelationsRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ListRelationsExecute_Call) Return(_a0 *client.ClientListRelationsResponse, _a1 error) *MockSdkClient_ListRelationsExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ListRelationsExecute_Call) RunAndReturn(run func(client.SdkClientListRelationsRequestInterface) (*client.ClientListRelationsResponse, error)) *MockSdkClient_ListRelationsExecute_Call { + _c.Call.Return(run) + return _c +} + +// ListStores provides a mock function with given fields: ctx +func (_m *MockSdkClient) ListStores(ctx context.Context) client.SdkClientListStoresRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for ListStores") + } + + var r0 client.SdkClientListStoresRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientListStoresRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListStoresRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_ListStores_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStores' +type MockSdkClient_ListStores_Call struct { + *mock.Call +} + +// ListStores is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) ListStores(ctx interface{}) *MockSdkClient_ListStores_Call { + return &MockSdkClient_ListStores_Call{Call: _e.mock.On("ListStores", ctx)} +} + +func (_c *MockSdkClient_ListStores_Call) Run(run func(ctx context.Context)) *MockSdkClient_ListStores_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_ListStores_Call) Return(_a0 client.SdkClientListStoresRequestInterface) *MockSdkClient_ListStores_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_ListStores_Call) RunAndReturn(run func(context.Context) client.SdkClientListStoresRequestInterface) *MockSdkClient_ListStores_Call { + _c.Call.Return(run) + return _c +} + +// ListStoresExecute provides a mock function with given fields: request +func (_m *MockSdkClient) ListStoresExecute(request client.SdkClientListStoresRequestInterface) (*openfga.ListStoresResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for ListStoresExecute") + } + + var r0 *openfga.ListStoresResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientListStoresRequestInterface) (*openfga.ListStoresResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientListStoresRequestInterface) *openfga.ListStoresResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ListStoresResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientListStoresRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ListStoresExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStoresExecute' +type MockSdkClient_ListStoresExecute_Call struct { + *mock.Call +} + +// ListStoresExecute is a helper method to define mock.On call +// - request client.SdkClientListStoresRequestInterface +func (_e *MockSdkClient_Expecter) ListStoresExecute(request interface{}) *MockSdkClient_ListStoresExecute_Call { + return &MockSdkClient_ListStoresExecute_Call{Call: _e.mock.On("ListStoresExecute", request)} +} + +func (_c *MockSdkClient_ListStoresExecute_Call) Run(run func(request client.SdkClientListStoresRequestInterface)) *MockSdkClient_ListStoresExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientListStoresRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ListStoresExecute_Call) Return(_a0 *openfga.ListStoresResponse, _a1 error) *MockSdkClient_ListStoresExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ListStoresExecute_Call) RunAndReturn(run func(client.SdkClientListStoresRequestInterface) (*openfga.ListStoresResponse, error)) *MockSdkClient_ListStoresExecute_Call { + _c.Call.Return(run) + return _c +} + +// ListUsers provides a mock function with given fields: ctx +func (_m *MockSdkClient) ListUsers(ctx context.Context) client.SdkClientListUsersRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for ListUsers") + } + + var r0 client.SdkClientListUsersRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientListUsersRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListUsersRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_ListUsers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListUsers' +type MockSdkClient_ListUsers_Call struct { + *mock.Call +} + +// ListUsers is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) ListUsers(ctx interface{}) *MockSdkClient_ListUsers_Call { + return &MockSdkClient_ListUsers_Call{Call: _e.mock.On("ListUsers", ctx)} +} + +func (_c *MockSdkClient_ListUsers_Call) Run(run func(ctx context.Context)) *MockSdkClient_ListUsers_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_ListUsers_Call) Return(_a0 client.SdkClientListUsersRequestInterface) *MockSdkClient_ListUsers_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_ListUsers_Call) RunAndReturn(run func(context.Context) client.SdkClientListUsersRequestInterface) *MockSdkClient_ListUsers_Call { + _c.Call.Return(run) + return _c +} + +// ListUsersExecute provides a mock function with given fields: r +func (_m *MockSdkClient) ListUsersExecute(r client.SdkClientListUsersRequestInterface) (*openfga.ListUsersResponse, error) { + ret := _m.Called(r) + + if len(ret) == 0 { + panic("no return value specified for ListUsersExecute") + } + + var r0 *openfga.ListUsersResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientListUsersRequestInterface) (*openfga.ListUsersResponse, error)); ok { + return rf(r) + } + if rf, ok := ret.Get(0).(func(client.SdkClientListUsersRequestInterface) *openfga.ListUsersResponse); ok { + r0 = rf(r) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ListUsersResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientListUsersRequestInterface) error); ok { + r1 = rf(r) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ListUsersExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListUsersExecute' +type MockSdkClient_ListUsersExecute_Call struct { + *mock.Call +} + +// ListUsersExecute is a helper method to define mock.On call +// - r client.SdkClientListUsersRequestInterface +func (_e *MockSdkClient_Expecter) ListUsersExecute(r interface{}) *MockSdkClient_ListUsersExecute_Call { + return &MockSdkClient_ListUsersExecute_Call{Call: _e.mock.On("ListUsersExecute", r)} +} + +func (_c *MockSdkClient_ListUsersExecute_Call) Run(run func(r client.SdkClientListUsersRequestInterface)) *MockSdkClient_ListUsersExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientListUsersRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ListUsersExecute_Call) Return(_a0 *openfga.ListUsersResponse, _a1 error) *MockSdkClient_ListUsersExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ListUsersExecute_Call) RunAndReturn(run func(client.SdkClientListUsersRequestInterface) (*openfga.ListUsersResponse, error)) *MockSdkClient_ListUsersExecute_Call { + _c.Call.Return(run) + return _c +} + +// Read provides a mock function with given fields: ctx +func (_m *MockSdkClient) Read(ctx context.Context) client.SdkClientReadRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for Read") + } + + var r0 client.SdkClientReadRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientReadRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_Read_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Read' +type MockSdkClient_Read_Call struct { + *mock.Call +} + +// Read is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) Read(ctx interface{}) *MockSdkClient_Read_Call { + return &MockSdkClient_Read_Call{Call: _e.mock.On("Read", ctx)} +} + +func (_c *MockSdkClient_Read_Call) Run(run func(ctx context.Context)) *MockSdkClient_Read_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_Read_Call) Return(_a0 client.SdkClientReadRequestInterface) *MockSdkClient_Read_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_Read_Call) RunAndReturn(run func(context.Context) client.SdkClientReadRequestInterface) *MockSdkClient_Read_Call { + _c.Call.Return(run) + return _c +} + +// ReadAssertions provides a mock function with given fields: ctx +func (_m *MockSdkClient) ReadAssertions(ctx context.Context) client.SdkClientReadAssertionsRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for ReadAssertions") + } + + var r0 client.SdkClientReadAssertionsRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientReadAssertionsRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadAssertionsRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_ReadAssertions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadAssertions' +type MockSdkClient_ReadAssertions_Call struct { + *mock.Call +} + +// ReadAssertions is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) ReadAssertions(ctx interface{}) *MockSdkClient_ReadAssertions_Call { + return &MockSdkClient_ReadAssertions_Call{Call: _e.mock.On("ReadAssertions", ctx)} +} + +func (_c *MockSdkClient_ReadAssertions_Call) Run(run func(ctx context.Context)) *MockSdkClient_ReadAssertions_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_ReadAssertions_Call) Return(_a0 client.SdkClientReadAssertionsRequestInterface) *MockSdkClient_ReadAssertions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_ReadAssertions_Call) RunAndReturn(run func(context.Context) client.SdkClientReadAssertionsRequestInterface) *MockSdkClient_ReadAssertions_Call { + _c.Call.Return(run) + return _c +} + +// ReadAssertionsExecute provides a mock function with given fields: request +func (_m *MockSdkClient) ReadAssertionsExecute(request client.SdkClientReadAssertionsRequestInterface) (*openfga.ReadAssertionsResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for ReadAssertionsExecute") + } + + var r0 *openfga.ReadAssertionsResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientReadAssertionsRequestInterface) (*openfga.ReadAssertionsResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientReadAssertionsRequestInterface) *openfga.ReadAssertionsResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadAssertionsResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientReadAssertionsRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ReadAssertionsExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadAssertionsExecute' +type MockSdkClient_ReadAssertionsExecute_Call struct { + *mock.Call +} + +// ReadAssertionsExecute is a helper method to define mock.On call +// - request client.SdkClientReadAssertionsRequestInterface +func (_e *MockSdkClient_Expecter) ReadAssertionsExecute(request interface{}) *MockSdkClient_ReadAssertionsExecute_Call { + return &MockSdkClient_ReadAssertionsExecute_Call{Call: _e.mock.On("ReadAssertionsExecute", request)} +} + +func (_c *MockSdkClient_ReadAssertionsExecute_Call) Run(run func(request client.SdkClientReadAssertionsRequestInterface)) *MockSdkClient_ReadAssertionsExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientReadAssertionsRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ReadAssertionsExecute_Call) Return(_a0 *openfga.ReadAssertionsResponse, _a1 error) *MockSdkClient_ReadAssertionsExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ReadAssertionsExecute_Call) RunAndReturn(run func(client.SdkClientReadAssertionsRequestInterface) (*openfga.ReadAssertionsResponse, error)) *MockSdkClient_ReadAssertionsExecute_Call { + _c.Call.Return(run) + return _c +} + +// ReadAuthorizationModel provides a mock function with given fields: ctx +func (_m *MockSdkClient) ReadAuthorizationModel(ctx context.Context) client.SdkClientReadAuthorizationModelRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for ReadAuthorizationModel") + } + + var r0 client.SdkClientReadAuthorizationModelRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientReadAuthorizationModelRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadAuthorizationModelRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_ReadAuthorizationModel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadAuthorizationModel' +type MockSdkClient_ReadAuthorizationModel_Call struct { + *mock.Call +} + +// ReadAuthorizationModel is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) ReadAuthorizationModel(ctx interface{}) *MockSdkClient_ReadAuthorizationModel_Call { + return &MockSdkClient_ReadAuthorizationModel_Call{Call: _e.mock.On("ReadAuthorizationModel", ctx)} +} + +func (_c *MockSdkClient_ReadAuthorizationModel_Call) Run(run func(ctx context.Context)) *MockSdkClient_ReadAuthorizationModel_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_ReadAuthorizationModel_Call) Return(_a0 client.SdkClientReadAuthorizationModelRequestInterface) *MockSdkClient_ReadAuthorizationModel_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_ReadAuthorizationModel_Call) RunAndReturn(run func(context.Context) client.SdkClientReadAuthorizationModelRequestInterface) *MockSdkClient_ReadAuthorizationModel_Call { + _c.Call.Return(run) + return _c +} + +// ReadAuthorizationModelExecute provides a mock function with given fields: request +func (_m *MockSdkClient) ReadAuthorizationModelExecute(request client.SdkClientReadAuthorizationModelRequestInterface) (*openfga.ReadAuthorizationModelResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for ReadAuthorizationModelExecute") + } + + var r0 *openfga.ReadAuthorizationModelResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientReadAuthorizationModelRequestInterface) (*openfga.ReadAuthorizationModelResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientReadAuthorizationModelRequestInterface) *openfga.ReadAuthorizationModelResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadAuthorizationModelResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientReadAuthorizationModelRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ReadAuthorizationModelExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadAuthorizationModelExecute' +type MockSdkClient_ReadAuthorizationModelExecute_Call struct { + *mock.Call +} + +// ReadAuthorizationModelExecute is a helper method to define mock.On call +// - request client.SdkClientReadAuthorizationModelRequestInterface +func (_e *MockSdkClient_Expecter) ReadAuthorizationModelExecute(request interface{}) *MockSdkClient_ReadAuthorizationModelExecute_Call { + return &MockSdkClient_ReadAuthorizationModelExecute_Call{Call: _e.mock.On("ReadAuthorizationModelExecute", request)} +} + +func (_c *MockSdkClient_ReadAuthorizationModelExecute_Call) Run(run func(request client.SdkClientReadAuthorizationModelRequestInterface)) *MockSdkClient_ReadAuthorizationModelExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientReadAuthorizationModelRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ReadAuthorizationModelExecute_Call) Return(_a0 *openfga.ReadAuthorizationModelResponse, _a1 error) *MockSdkClient_ReadAuthorizationModelExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ReadAuthorizationModelExecute_Call) RunAndReturn(run func(client.SdkClientReadAuthorizationModelRequestInterface) (*openfga.ReadAuthorizationModelResponse, error)) *MockSdkClient_ReadAuthorizationModelExecute_Call { + _c.Call.Return(run) + return _c +} + +// ReadAuthorizationModels provides a mock function with given fields: ctx +func (_m *MockSdkClient) ReadAuthorizationModels(ctx context.Context) client.SdkClientReadAuthorizationModelsRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for ReadAuthorizationModels") + } + + var r0 client.SdkClientReadAuthorizationModelsRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientReadAuthorizationModelsRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadAuthorizationModelsRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_ReadAuthorizationModels_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadAuthorizationModels' +type MockSdkClient_ReadAuthorizationModels_Call struct { + *mock.Call +} + +// ReadAuthorizationModels is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) ReadAuthorizationModels(ctx interface{}) *MockSdkClient_ReadAuthorizationModels_Call { + return &MockSdkClient_ReadAuthorizationModels_Call{Call: _e.mock.On("ReadAuthorizationModels", ctx)} +} + +func (_c *MockSdkClient_ReadAuthorizationModels_Call) Run(run func(ctx context.Context)) *MockSdkClient_ReadAuthorizationModels_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_ReadAuthorizationModels_Call) Return(_a0 client.SdkClientReadAuthorizationModelsRequestInterface) *MockSdkClient_ReadAuthorizationModels_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_ReadAuthorizationModels_Call) RunAndReturn(run func(context.Context) client.SdkClientReadAuthorizationModelsRequestInterface) *MockSdkClient_ReadAuthorizationModels_Call { + _c.Call.Return(run) + return _c +} + +// ReadAuthorizationModelsExecute provides a mock function with given fields: request +func (_m *MockSdkClient) ReadAuthorizationModelsExecute(request client.SdkClientReadAuthorizationModelsRequestInterface) (*openfga.ReadAuthorizationModelsResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for ReadAuthorizationModelsExecute") + } + + var r0 *openfga.ReadAuthorizationModelsResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientReadAuthorizationModelsRequestInterface) (*openfga.ReadAuthorizationModelsResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientReadAuthorizationModelsRequestInterface) *openfga.ReadAuthorizationModelsResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadAuthorizationModelsResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientReadAuthorizationModelsRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ReadAuthorizationModelsExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadAuthorizationModelsExecute' +type MockSdkClient_ReadAuthorizationModelsExecute_Call struct { + *mock.Call +} + +// ReadAuthorizationModelsExecute is a helper method to define mock.On call +// - request client.SdkClientReadAuthorizationModelsRequestInterface +func (_e *MockSdkClient_Expecter) ReadAuthorizationModelsExecute(request interface{}) *MockSdkClient_ReadAuthorizationModelsExecute_Call { + return &MockSdkClient_ReadAuthorizationModelsExecute_Call{Call: _e.mock.On("ReadAuthorizationModelsExecute", request)} +} + +func (_c *MockSdkClient_ReadAuthorizationModelsExecute_Call) Run(run func(request client.SdkClientReadAuthorizationModelsRequestInterface)) *MockSdkClient_ReadAuthorizationModelsExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientReadAuthorizationModelsRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ReadAuthorizationModelsExecute_Call) Return(_a0 *openfga.ReadAuthorizationModelsResponse, _a1 error) *MockSdkClient_ReadAuthorizationModelsExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ReadAuthorizationModelsExecute_Call) RunAndReturn(run func(client.SdkClientReadAuthorizationModelsRequestInterface) (*openfga.ReadAuthorizationModelsResponse, error)) *MockSdkClient_ReadAuthorizationModelsExecute_Call { + _c.Call.Return(run) + return _c +} + +// ReadChanges provides a mock function with given fields: ctx +func (_m *MockSdkClient) ReadChanges(ctx context.Context) client.SdkClientReadChangesRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for ReadChanges") + } + + var r0 client.SdkClientReadChangesRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientReadChangesRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadChangesRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_ReadChanges_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadChanges' +type MockSdkClient_ReadChanges_Call struct { + *mock.Call +} + +// ReadChanges is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) ReadChanges(ctx interface{}) *MockSdkClient_ReadChanges_Call { + return &MockSdkClient_ReadChanges_Call{Call: _e.mock.On("ReadChanges", ctx)} +} + +func (_c *MockSdkClient_ReadChanges_Call) Run(run func(ctx context.Context)) *MockSdkClient_ReadChanges_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_ReadChanges_Call) Return(_a0 client.SdkClientReadChangesRequestInterface) *MockSdkClient_ReadChanges_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_ReadChanges_Call) RunAndReturn(run func(context.Context) client.SdkClientReadChangesRequestInterface) *MockSdkClient_ReadChanges_Call { + _c.Call.Return(run) + return _c +} + +// ReadChangesExecute provides a mock function with given fields: request +func (_m *MockSdkClient) ReadChangesExecute(request client.SdkClientReadChangesRequestInterface) (*openfga.ReadChangesResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for ReadChangesExecute") + } + + var r0 *openfga.ReadChangesResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientReadChangesRequestInterface) (*openfga.ReadChangesResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientReadChangesRequestInterface) *openfga.ReadChangesResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadChangesResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientReadChangesRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ReadChangesExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadChangesExecute' +type MockSdkClient_ReadChangesExecute_Call struct { + *mock.Call +} + +// ReadChangesExecute is a helper method to define mock.On call +// - request client.SdkClientReadChangesRequestInterface +func (_e *MockSdkClient_Expecter) ReadChangesExecute(request interface{}) *MockSdkClient_ReadChangesExecute_Call { + return &MockSdkClient_ReadChangesExecute_Call{Call: _e.mock.On("ReadChangesExecute", request)} +} + +func (_c *MockSdkClient_ReadChangesExecute_Call) Run(run func(request client.SdkClientReadChangesRequestInterface)) *MockSdkClient_ReadChangesExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientReadChangesRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ReadChangesExecute_Call) Return(_a0 *openfga.ReadChangesResponse, _a1 error) *MockSdkClient_ReadChangesExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ReadChangesExecute_Call) RunAndReturn(run func(client.SdkClientReadChangesRequestInterface) (*openfga.ReadChangesResponse, error)) *MockSdkClient_ReadChangesExecute_Call { + _c.Call.Return(run) + return _c +} + +// ReadExecute provides a mock function with given fields: request +func (_m *MockSdkClient) ReadExecute(request client.SdkClientReadRequestInterface) (*openfga.ReadResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for ReadExecute") + } + + var r0 *openfga.ReadResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientReadRequestInterface) (*openfga.ReadResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientReadRequestInterface) *openfga.ReadResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientReadRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ReadExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadExecute' +type MockSdkClient_ReadExecute_Call struct { + *mock.Call +} + +// ReadExecute is a helper method to define mock.On call +// - request client.SdkClientReadRequestInterface +func (_e *MockSdkClient_Expecter) ReadExecute(request interface{}) *MockSdkClient_ReadExecute_Call { + return &MockSdkClient_ReadExecute_Call{Call: _e.mock.On("ReadExecute", request)} +} + +func (_c *MockSdkClient_ReadExecute_Call) Run(run func(request client.SdkClientReadRequestInterface)) *MockSdkClient_ReadExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientReadRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ReadExecute_Call) Return(_a0 *openfga.ReadResponse, _a1 error) *MockSdkClient_ReadExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ReadExecute_Call) RunAndReturn(run func(client.SdkClientReadRequestInterface) (*openfga.ReadResponse, error)) *MockSdkClient_ReadExecute_Call { + _c.Call.Return(run) + return _c +} + +// ReadLatestAuthorizationModel provides a mock function with given fields: ctx +func (_m *MockSdkClient) ReadLatestAuthorizationModel(ctx context.Context) client.SdkClientReadLatestAuthorizationModelRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for ReadLatestAuthorizationModel") + } + + var r0 client.SdkClientReadLatestAuthorizationModelRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientReadLatestAuthorizationModelRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadLatestAuthorizationModelRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_ReadLatestAuthorizationModel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadLatestAuthorizationModel' +type MockSdkClient_ReadLatestAuthorizationModel_Call struct { + *mock.Call +} + +// ReadLatestAuthorizationModel is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) ReadLatestAuthorizationModel(ctx interface{}) *MockSdkClient_ReadLatestAuthorizationModel_Call { + return &MockSdkClient_ReadLatestAuthorizationModel_Call{Call: _e.mock.On("ReadLatestAuthorizationModel", ctx)} +} + +func (_c *MockSdkClient_ReadLatestAuthorizationModel_Call) Run(run func(ctx context.Context)) *MockSdkClient_ReadLatestAuthorizationModel_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_ReadLatestAuthorizationModel_Call) Return(_a0 client.SdkClientReadLatestAuthorizationModelRequestInterface) *MockSdkClient_ReadLatestAuthorizationModel_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_ReadLatestAuthorizationModel_Call) RunAndReturn(run func(context.Context) client.SdkClientReadLatestAuthorizationModelRequestInterface) *MockSdkClient_ReadLatestAuthorizationModel_Call { + _c.Call.Return(run) + return _c +} + +// ReadLatestAuthorizationModelExecute provides a mock function with given fields: request +func (_m *MockSdkClient) ReadLatestAuthorizationModelExecute(request client.SdkClientReadLatestAuthorizationModelRequestInterface) (*openfga.ReadAuthorizationModelResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for ReadLatestAuthorizationModelExecute") + } + + var r0 *openfga.ReadAuthorizationModelResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientReadLatestAuthorizationModelRequestInterface) (*openfga.ReadAuthorizationModelResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientReadLatestAuthorizationModelRequestInterface) *openfga.ReadAuthorizationModelResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadAuthorizationModelResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientReadLatestAuthorizationModelRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_ReadLatestAuthorizationModelExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReadLatestAuthorizationModelExecute' +type MockSdkClient_ReadLatestAuthorizationModelExecute_Call struct { + *mock.Call +} + +// ReadLatestAuthorizationModelExecute is a helper method to define mock.On call +// - request client.SdkClientReadLatestAuthorizationModelRequestInterface +func (_e *MockSdkClient_Expecter) ReadLatestAuthorizationModelExecute(request interface{}) *MockSdkClient_ReadLatestAuthorizationModelExecute_Call { + return &MockSdkClient_ReadLatestAuthorizationModelExecute_Call{Call: _e.mock.On("ReadLatestAuthorizationModelExecute", request)} +} + +func (_c *MockSdkClient_ReadLatestAuthorizationModelExecute_Call) Run(run func(request client.SdkClientReadLatestAuthorizationModelRequestInterface)) *MockSdkClient_ReadLatestAuthorizationModelExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientReadLatestAuthorizationModelRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_ReadLatestAuthorizationModelExecute_Call) Return(_a0 *openfga.ReadAuthorizationModelResponse, _a1 error) *MockSdkClient_ReadLatestAuthorizationModelExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_ReadLatestAuthorizationModelExecute_Call) RunAndReturn(run func(client.SdkClientReadLatestAuthorizationModelRequestInterface) (*openfga.ReadAuthorizationModelResponse, error)) *MockSdkClient_ReadLatestAuthorizationModelExecute_Call { + _c.Call.Return(run) + return _c +} + +// Write provides a mock function with given fields: ctx +func (_m *MockSdkClient) Write(ctx context.Context) client.SdkClientWriteRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for Write") + } + + var r0 client.SdkClientWriteRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientWriteRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_Write_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Write' +type MockSdkClient_Write_Call struct { + *mock.Call +} + +// Write is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) Write(ctx interface{}) *MockSdkClient_Write_Call { + return &MockSdkClient_Write_Call{Call: _e.mock.On("Write", ctx)} +} + +func (_c *MockSdkClient_Write_Call) Run(run func(ctx context.Context)) *MockSdkClient_Write_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_Write_Call) Return(_a0 client.SdkClientWriteRequestInterface) *MockSdkClient_Write_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_Write_Call) RunAndReturn(run func(context.Context) client.SdkClientWriteRequestInterface) *MockSdkClient_Write_Call { + _c.Call.Return(run) + return _c +} + +// WriteAssertions provides a mock function with given fields: ctx +func (_m *MockSdkClient) WriteAssertions(ctx context.Context) client.SdkClientWriteAssertionsRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for WriteAssertions") + } + + var r0 client.SdkClientWriteAssertionsRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientWriteAssertionsRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteAssertionsRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_WriteAssertions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WriteAssertions' +type MockSdkClient_WriteAssertions_Call struct { + *mock.Call +} + +// WriteAssertions is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) WriteAssertions(ctx interface{}) *MockSdkClient_WriteAssertions_Call { + return &MockSdkClient_WriteAssertions_Call{Call: _e.mock.On("WriteAssertions", ctx)} +} + +func (_c *MockSdkClient_WriteAssertions_Call) Run(run func(ctx context.Context)) *MockSdkClient_WriteAssertions_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_WriteAssertions_Call) Return(_a0 client.SdkClientWriteAssertionsRequestInterface) *MockSdkClient_WriteAssertions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_WriteAssertions_Call) RunAndReturn(run func(context.Context) client.SdkClientWriteAssertionsRequestInterface) *MockSdkClient_WriteAssertions_Call { + _c.Call.Return(run) + return _c +} + +// WriteAssertionsExecute provides a mock function with given fields: request +func (_m *MockSdkClient) WriteAssertionsExecute(request client.SdkClientWriteAssertionsRequestInterface) (*client.ClientWriteAssertionsResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for WriteAssertionsExecute") + } + + var r0 *client.ClientWriteAssertionsResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientWriteAssertionsRequestInterface) (*client.ClientWriteAssertionsResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientWriteAssertionsRequestInterface) *client.ClientWriteAssertionsResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteAssertionsResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientWriteAssertionsRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_WriteAssertionsExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WriteAssertionsExecute' +type MockSdkClient_WriteAssertionsExecute_Call struct { + *mock.Call +} + +// WriteAssertionsExecute is a helper method to define mock.On call +// - request client.SdkClientWriteAssertionsRequestInterface +func (_e *MockSdkClient_Expecter) WriteAssertionsExecute(request interface{}) *MockSdkClient_WriteAssertionsExecute_Call { + return &MockSdkClient_WriteAssertionsExecute_Call{Call: _e.mock.On("WriteAssertionsExecute", request)} +} + +func (_c *MockSdkClient_WriteAssertionsExecute_Call) Run(run func(request client.SdkClientWriteAssertionsRequestInterface)) *MockSdkClient_WriteAssertionsExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientWriteAssertionsRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_WriteAssertionsExecute_Call) Return(_a0 *client.ClientWriteAssertionsResponse, _a1 error) *MockSdkClient_WriteAssertionsExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_WriteAssertionsExecute_Call) RunAndReturn(run func(client.SdkClientWriteAssertionsRequestInterface) (*client.ClientWriteAssertionsResponse, error)) *MockSdkClient_WriteAssertionsExecute_Call { + _c.Call.Return(run) + return _c +} + +// WriteAuthorizationModel provides a mock function with given fields: ctx +func (_m *MockSdkClient) WriteAuthorizationModel(ctx context.Context) client.SdkClientWriteAuthorizationModelRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for WriteAuthorizationModel") + } + + var r0 client.SdkClientWriteAuthorizationModelRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientWriteAuthorizationModelRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteAuthorizationModelRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_WriteAuthorizationModel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WriteAuthorizationModel' +type MockSdkClient_WriteAuthorizationModel_Call struct { + *mock.Call +} + +// WriteAuthorizationModel is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) WriteAuthorizationModel(ctx interface{}) *MockSdkClient_WriteAuthorizationModel_Call { + return &MockSdkClient_WriteAuthorizationModel_Call{Call: _e.mock.On("WriteAuthorizationModel", ctx)} +} + +func (_c *MockSdkClient_WriteAuthorizationModel_Call) Run(run func(ctx context.Context)) *MockSdkClient_WriteAuthorizationModel_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_WriteAuthorizationModel_Call) Return(_a0 client.SdkClientWriteAuthorizationModelRequestInterface) *MockSdkClient_WriteAuthorizationModel_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_WriteAuthorizationModel_Call) RunAndReturn(run func(context.Context) client.SdkClientWriteAuthorizationModelRequestInterface) *MockSdkClient_WriteAuthorizationModel_Call { + _c.Call.Return(run) + return _c +} + +// WriteAuthorizationModelExecute provides a mock function with given fields: request +func (_m *MockSdkClient) WriteAuthorizationModelExecute(request client.SdkClientWriteAuthorizationModelRequestInterface) (*openfga.WriteAuthorizationModelResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for WriteAuthorizationModelExecute") + } + + var r0 *openfga.WriteAuthorizationModelResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientWriteAuthorizationModelRequestInterface) (*openfga.WriteAuthorizationModelResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientWriteAuthorizationModelRequestInterface) *openfga.WriteAuthorizationModelResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.WriteAuthorizationModelResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientWriteAuthorizationModelRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_WriteAuthorizationModelExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WriteAuthorizationModelExecute' +type MockSdkClient_WriteAuthorizationModelExecute_Call struct { + *mock.Call +} + +// WriteAuthorizationModelExecute is a helper method to define mock.On call +// - request client.SdkClientWriteAuthorizationModelRequestInterface +func (_e *MockSdkClient_Expecter) WriteAuthorizationModelExecute(request interface{}) *MockSdkClient_WriteAuthorizationModelExecute_Call { + return &MockSdkClient_WriteAuthorizationModelExecute_Call{Call: _e.mock.On("WriteAuthorizationModelExecute", request)} +} + +func (_c *MockSdkClient_WriteAuthorizationModelExecute_Call) Run(run func(request client.SdkClientWriteAuthorizationModelRequestInterface)) *MockSdkClient_WriteAuthorizationModelExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientWriteAuthorizationModelRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_WriteAuthorizationModelExecute_Call) Return(_a0 *openfga.WriteAuthorizationModelResponse, _a1 error) *MockSdkClient_WriteAuthorizationModelExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_WriteAuthorizationModelExecute_Call) RunAndReturn(run func(client.SdkClientWriteAuthorizationModelRequestInterface) (*openfga.WriteAuthorizationModelResponse, error)) *MockSdkClient_WriteAuthorizationModelExecute_Call { + _c.Call.Return(run) + return _c +} + +// WriteExecute provides a mock function with given fields: request +func (_m *MockSdkClient) WriteExecute(request client.SdkClientWriteRequestInterface) (*client.ClientWriteResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for WriteExecute") + } + + var r0 *client.ClientWriteResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientWriteRequestInterface) (*client.ClientWriteResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientWriteRequestInterface) *client.ClientWriteResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientWriteRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_WriteExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WriteExecute' +type MockSdkClient_WriteExecute_Call struct { + *mock.Call +} + +// WriteExecute is a helper method to define mock.On call +// - request client.SdkClientWriteRequestInterface +func (_e *MockSdkClient_Expecter) WriteExecute(request interface{}) *MockSdkClient_WriteExecute_Call { + return &MockSdkClient_WriteExecute_Call{Call: _e.mock.On("WriteExecute", request)} +} + +func (_c *MockSdkClient_WriteExecute_Call) Run(run func(request client.SdkClientWriteRequestInterface)) *MockSdkClient_WriteExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientWriteRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_WriteExecute_Call) Return(_a0 *client.ClientWriteResponse, _a1 error) *MockSdkClient_WriteExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_WriteExecute_Call) RunAndReturn(run func(client.SdkClientWriteRequestInterface) (*client.ClientWriteResponse, error)) *MockSdkClient_WriteExecute_Call { + _c.Call.Return(run) + return _c +} + +// WriteTuples provides a mock function with given fields: ctx +func (_m *MockSdkClient) WriteTuples(ctx context.Context) client.SdkClientWriteTuplesRequestInterface { + ret := _m.Called(ctx) + + if len(ret) == 0 { + panic("no return value specified for WriteTuples") + } + + var r0 client.SdkClientWriteTuplesRequestInterface + if rf, ok := ret.Get(0).(func(context.Context) client.SdkClientWriteTuplesRequestInterface); ok { + r0 = rf(ctx) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteTuplesRequestInterface) + } + } + + return r0 +} + +// MockSdkClient_WriteTuples_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WriteTuples' +type MockSdkClient_WriteTuples_Call struct { + *mock.Call +} + +// WriteTuples is a helper method to define mock.On call +// - ctx context.Context +func (_e *MockSdkClient_Expecter) WriteTuples(ctx interface{}) *MockSdkClient_WriteTuples_Call { + return &MockSdkClient_WriteTuples_Call{Call: _e.mock.On("WriteTuples", ctx)} +} + +func (_c *MockSdkClient_WriteTuples_Call) Run(run func(ctx context.Context)) *MockSdkClient_WriteTuples_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context)) + }) + return _c +} + +func (_c *MockSdkClient_WriteTuples_Call) Return(_a0 client.SdkClientWriteTuplesRequestInterface) *MockSdkClient_WriteTuples_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClient_WriteTuples_Call) RunAndReturn(run func(context.Context) client.SdkClientWriteTuplesRequestInterface) *MockSdkClient_WriteTuples_Call { + _c.Call.Return(run) + return _c +} + +// WriteTuplesExecute provides a mock function with given fields: request +func (_m *MockSdkClient) WriteTuplesExecute(request client.SdkClientWriteTuplesRequestInterface) (*client.ClientWriteResponse, error) { + ret := _m.Called(request) + + if len(ret) == 0 { + panic("no return value specified for WriteTuplesExecute") + } + + var r0 *client.ClientWriteResponse + var r1 error + if rf, ok := ret.Get(0).(func(client.SdkClientWriteTuplesRequestInterface) (*client.ClientWriteResponse, error)); ok { + return rf(request) + } + if rf, ok := ret.Get(0).(func(client.SdkClientWriteTuplesRequestInterface) *client.ClientWriteResponse); ok { + r0 = rf(request) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteResponse) + } + } + + if rf, ok := ret.Get(1).(func(client.SdkClientWriteTuplesRequestInterface) error); ok { + r1 = rf(request) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClient_WriteTuplesExecute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WriteTuplesExecute' +type MockSdkClient_WriteTuplesExecute_Call struct { + *mock.Call +} + +// WriteTuplesExecute is a helper method to define mock.On call +// - request client.SdkClientWriteTuplesRequestInterface +func (_e *MockSdkClient_Expecter) WriteTuplesExecute(request interface{}) *MockSdkClient_WriteTuplesExecute_Call { + return &MockSdkClient_WriteTuplesExecute_Call{Call: _e.mock.On("WriteTuplesExecute", request)} +} + +func (_c *MockSdkClient_WriteTuplesExecute_Call) Run(run func(request client.SdkClientWriteTuplesRequestInterface)) *MockSdkClient_WriteTuplesExecute_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.SdkClientWriteTuplesRequestInterface)) + }) + return _c +} + +func (_c *MockSdkClient_WriteTuplesExecute_Call) Return(_a0 *client.ClientWriteResponse, _a1 error) *MockSdkClient_WriteTuplesExecute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClient_WriteTuplesExecute_Call) RunAndReturn(run func(client.SdkClientWriteTuplesRequestInterface) (*client.ClientWriteResponse, error)) *MockSdkClient_WriteTuplesExecute_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClient creates a new instance of MockSdkClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClient(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClient { + mock := &MockSdkClient{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientBatchCheckRequestInterface.go b/fgax/mockery/mock_SdkClientBatchCheckRequestInterface.go new file mode 100644 index 0000000..8ddbbc9 --- /dev/null +++ b/fgax/mockery/mock_SdkClientBatchCheckRequestInterface.go @@ -0,0 +1,426 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" +) + +// MockSdkClientBatchCheckRequestInterface is an autogenerated mock type for the SdkClientBatchCheckRequestInterface type +type MockSdkClientBatchCheckRequestInterface struct { + mock.Mock +} + +type MockSdkClientBatchCheckRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientBatchCheckRequestInterface) EXPECT() *MockSdkClientBatchCheckRequestInterface_Expecter { + return &MockSdkClientBatchCheckRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientBatchCheckRequestInterface) Body(body []client.ClientCheckRequest) client.SdkClientBatchCheckRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientBatchCheckRequestInterface + if rf, ok := ret.Get(0).(func([]client.ClientCheckRequest) client.SdkClientBatchCheckRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientBatchCheckRequestInterface) + } + } + + return r0 +} + +// MockSdkClientBatchCheckRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientBatchCheckRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body []client.ClientCheckRequest +func (_e *MockSdkClientBatchCheckRequestInterface_Expecter) Body(body interface{}) *MockSdkClientBatchCheckRequestInterface_Body_Call { + return &MockSdkClientBatchCheckRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientBatchCheckRequestInterface_Body_Call) Run(run func(body []client.ClientCheckRequest)) *MockSdkClientBatchCheckRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].([]client.ClientCheckRequest)) + }) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_Body_Call) Return(_a0 client.SdkClientBatchCheckRequestInterface) *MockSdkClientBatchCheckRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_Body_Call) RunAndReturn(run func([]client.ClientCheckRequest) client.SdkClientBatchCheckRequestInterface) *MockSdkClientBatchCheckRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientBatchCheckRequestInterface) Execute() (*[]client.ClientBatchCheckSingleResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *[]client.ClientBatchCheckSingleResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*[]client.ClientBatchCheckSingleResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *[]client.ClientBatchCheckSingleResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*[]client.ClientBatchCheckSingleResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientBatchCheckRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientBatchCheckRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientBatchCheckRequestInterface_Expecter) Execute() *MockSdkClientBatchCheckRequestInterface_Execute_Call { + return &MockSdkClientBatchCheckRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientBatchCheckRequestInterface_Execute_Call) Run(run func()) *MockSdkClientBatchCheckRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_Execute_Call) Return(_a0 *[]client.ClientBatchCheckSingleResponse, _a1 error) *MockSdkClientBatchCheckRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_Execute_Call) RunAndReturn(run func() (*[]client.ClientBatchCheckSingleResponse, error)) *MockSdkClientBatchCheckRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetAuthorizationModelIdOverride provides a mock function with given fields: +func (_m *MockSdkClientBatchCheckRequestInterface) GetAuthorizationModelIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetAuthorizationModelIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientBatchCheckRequestInterface_GetAuthorizationModelIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizationModelIdOverride' +type MockSdkClientBatchCheckRequestInterface_GetAuthorizationModelIdOverride_Call struct { + *mock.Call +} + +// GetAuthorizationModelIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientBatchCheckRequestInterface_Expecter) GetAuthorizationModelIdOverride() *MockSdkClientBatchCheckRequestInterface_GetAuthorizationModelIdOverride_Call { + return &MockSdkClientBatchCheckRequestInterface_GetAuthorizationModelIdOverride_Call{Call: _e.mock.On("GetAuthorizationModelIdOverride")} +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetAuthorizationModelIdOverride_Call) Run(run func()) *MockSdkClientBatchCheckRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetAuthorizationModelIdOverride_Call) Return(_a0 *string) *MockSdkClientBatchCheckRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetAuthorizationModelIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientBatchCheckRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientBatchCheckRequestInterface) GetBody() *[]client.ClientCheckRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *[]client.ClientCheckRequest + if rf, ok := ret.Get(0).(func() *[]client.ClientCheckRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*[]client.ClientCheckRequest) + } + } + + return r0 +} + +// MockSdkClientBatchCheckRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientBatchCheckRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientBatchCheckRequestInterface_Expecter) GetBody() *MockSdkClientBatchCheckRequestInterface_GetBody_Call { + return &MockSdkClientBatchCheckRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientBatchCheckRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetBody_Call) Return(_a0 *[]client.ClientCheckRequest) *MockSdkClientBatchCheckRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetBody_Call) RunAndReturn(run func() *[]client.ClientCheckRequest) *MockSdkClientBatchCheckRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientBatchCheckRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientBatchCheckRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientBatchCheckRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientBatchCheckRequestInterface_Expecter) GetContext() *MockSdkClientBatchCheckRequestInterface_GetContext_Call { + return &MockSdkClientBatchCheckRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientBatchCheckRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientBatchCheckRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientBatchCheckRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientBatchCheckRequestInterface) GetOptions() *client.ClientBatchCheckOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientBatchCheckOptions + if rf, ok := ret.Get(0).(func() *client.ClientBatchCheckOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientBatchCheckOptions) + } + } + + return r0 +} + +// MockSdkClientBatchCheckRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientBatchCheckRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientBatchCheckRequestInterface_Expecter) GetOptions() *MockSdkClientBatchCheckRequestInterface_GetOptions_Call { + return &MockSdkClientBatchCheckRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientBatchCheckRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetOptions_Call) Return(_a0 *client.ClientBatchCheckOptions) *MockSdkClientBatchCheckRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientBatchCheckOptions) *MockSdkClientBatchCheckRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientBatchCheckRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientBatchCheckRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientBatchCheckRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientBatchCheckRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientBatchCheckRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientBatchCheckRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientBatchCheckRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientBatchCheckRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientBatchCheckRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientBatchCheckRequestInterface) Options(options client.ClientBatchCheckOptions) client.SdkClientBatchCheckRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientBatchCheckRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientBatchCheckOptions) client.SdkClientBatchCheckRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientBatchCheckRequestInterface) + } + } + + return r0 +} + +// MockSdkClientBatchCheckRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientBatchCheckRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientBatchCheckOptions +func (_e *MockSdkClientBatchCheckRequestInterface_Expecter) Options(options interface{}) *MockSdkClientBatchCheckRequestInterface_Options_Call { + return &MockSdkClientBatchCheckRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientBatchCheckRequestInterface_Options_Call) Run(run func(options client.ClientBatchCheckOptions)) *MockSdkClientBatchCheckRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientBatchCheckOptions)) + }) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_Options_Call) Return(_a0 client.SdkClientBatchCheckRequestInterface) *MockSdkClientBatchCheckRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientBatchCheckRequestInterface_Options_Call) RunAndReturn(run func(client.ClientBatchCheckOptions) client.SdkClientBatchCheckRequestInterface) *MockSdkClientBatchCheckRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientBatchCheckRequestInterface creates a new instance of MockSdkClientBatchCheckRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientBatchCheckRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientBatchCheckRequestInterface { + mock := &MockSdkClientBatchCheckRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientCheckRequestInterface.go b/fgax/mockery/mock_SdkClientCheckRequestInterface.go new file mode 100644 index 0000000..cd96780 --- /dev/null +++ b/fgax/mockery/mock_SdkClientCheckRequestInterface.go @@ -0,0 +1,426 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" +) + +// MockSdkClientCheckRequestInterface is an autogenerated mock type for the SdkClientCheckRequestInterface type +type MockSdkClientCheckRequestInterface struct { + mock.Mock +} + +type MockSdkClientCheckRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientCheckRequestInterface) EXPECT() *MockSdkClientCheckRequestInterface_Expecter { + return &MockSdkClientCheckRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientCheckRequestInterface) Body(body client.ClientCheckRequest) client.SdkClientCheckRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientCheckRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientCheckRequest) client.SdkClientCheckRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientCheckRequestInterface) + } + } + + return r0 +} + +// MockSdkClientCheckRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientCheckRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body client.ClientCheckRequest +func (_e *MockSdkClientCheckRequestInterface_Expecter) Body(body interface{}) *MockSdkClientCheckRequestInterface_Body_Call { + return &MockSdkClientCheckRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientCheckRequestInterface_Body_Call) Run(run func(body client.ClientCheckRequest)) *MockSdkClientCheckRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientCheckRequest)) + }) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_Body_Call) Return(_a0 client.SdkClientCheckRequestInterface) *MockSdkClientCheckRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_Body_Call) RunAndReturn(run func(client.ClientCheckRequest) client.SdkClientCheckRequestInterface) *MockSdkClientCheckRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientCheckRequestInterface) Execute() (*client.ClientCheckResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *client.ClientCheckResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*client.ClientCheckResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *client.ClientCheckResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientCheckResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientCheckRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientCheckRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientCheckRequestInterface_Expecter) Execute() *MockSdkClientCheckRequestInterface_Execute_Call { + return &MockSdkClientCheckRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientCheckRequestInterface_Execute_Call) Run(run func()) *MockSdkClientCheckRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_Execute_Call) Return(_a0 *client.ClientCheckResponse, _a1 error) *MockSdkClientCheckRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_Execute_Call) RunAndReturn(run func() (*client.ClientCheckResponse, error)) *MockSdkClientCheckRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetAuthorizationModelIdOverride provides a mock function with given fields: +func (_m *MockSdkClientCheckRequestInterface) GetAuthorizationModelIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetAuthorizationModelIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientCheckRequestInterface_GetAuthorizationModelIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizationModelIdOverride' +type MockSdkClientCheckRequestInterface_GetAuthorizationModelIdOverride_Call struct { + *mock.Call +} + +// GetAuthorizationModelIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientCheckRequestInterface_Expecter) GetAuthorizationModelIdOverride() *MockSdkClientCheckRequestInterface_GetAuthorizationModelIdOverride_Call { + return &MockSdkClientCheckRequestInterface_GetAuthorizationModelIdOverride_Call{Call: _e.mock.On("GetAuthorizationModelIdOverride")} +} + +func (_c *MockSdkClientCheckRequestInterface_GetAuthorizationModelIdOverride_Call) Run(run func()) *MockSdkClientCheckRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_GetAuthorizationModelIdOverride_Call) Return(_a0 *string) *MockSdkClientCheckRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_GetAuthorizationModelIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientCheckRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientCheckRequestInterface) GetBody() *client.ClientCheckRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *client.ClientCheckRequest + if rf, ok := ret.Get(0).(func() *client.ClientCheckRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientCheckRequest) + } + } + + return r0 +} + +// MockSdkClientCheckRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientCheckRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientCheckRequestInterface_Expecter) GetBody() *MockSdkClientCheckRequestInterface_GetBody_Call { + return &MockSdkClientCheckRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientCheckRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientCheckRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_GetBody_Call) Return(_a0 *client.ClientCheckRequest) *MockSdkClientCheckRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_GetBody_Call) RunAndReturn(run func() *client.ClientCheckRequest) *MockSdkClientCheckRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientCheckRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientCheckRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientCheckRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientCheckRequestInterface_Expecter) GetContext() *MockSdkClientCheckRequestInterface_GetContext_Call { + return &MockSdkClientCheckRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientCheckRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientCheckRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientCheckRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientCheckRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientCheckRequestInterface) GetOptions() *client.ClientCheckOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientCheckOptions + if rf, ok := ret.Get(0).(func() *client.ClientCheckOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientCheckOptions) + } + } + + return r0 +} + +// MockSdkClientCheckRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientCheckRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientCheckRequestInterface_Expecter) GetOptions() *MockSdkClientCheckRequestInterface_GetOptions_Call { + return &MockSdkClientCheckRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientCheckRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientCheckRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_GetOptions_Call) Return(_a0 *client.ClientCheckOptions) *MockSdkClientCheckRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientCheckOptions) *MockSdkClientCheckRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientCheckRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientCheckRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientCheckRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientCheckRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientCheckRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientCheckRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientCheckRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientCheckRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientCheckRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientCheckRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientCheckRequestInterface) Options(options client.ClientCheckOptions) client.SdkClientCheckRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientCheckRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientCheckOptions) client.SdkClientCheckRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientCheckRequestInterface) + } + } + + return r0 +} + +// MockSdkClientCheckRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientCheckRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientCheckOptions +func (_e *MockSdkClientCheckRequestInterface_Expecter) Options(options interface{}) *MockSdkClientCheckRequestInterface_Options_Call { + return &MockSdkClientCheckRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientCheckRequestInterface_Options_Call) Run(run func(options client.ClientCheckOptions)) *MockSdkClientCheckRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientCheckOptions)) + }) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_Options_Call) Return(_a0 client.SdkClientCheckRequestInterface) *MockSdkClientCheckRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCheckRequestInterface_Options_Call) RunAndReturn(run func(client.ClientCheckOptions) client.SdkClientCheckRequestInterface) *MockSdkClientCheckRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientCheckRequestInterface creates a new instance of MockSdkClientCheckRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientCheckRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientCheckRequestInterface { + mock := &MockSdkClientCheckRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientCreateStoreRequestInterface.go b/fgax/mockery/mock_SdkClientCreateStoreRequestInterface.go new file mode 100644 index 0000000..e58a8de --- /dev/null +++ b/fgax/mockery/mock_SdkClientCreateStoreRequestInterface.go @@ -0,0 +1,334 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientCreateStoreRequestInterface is an autogenerated mock type for the SdkClientCreateStoreRequestInterface type +type MockSdkClientCreateStoreRequestInterface struct { + mock.Mock +} + +type MockSdkClientCreateStoreRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientCreateStoreRequestInterface) EXPECT() *MockSdkClientCreateStoreRequestInterface_Expecter { + return &MockSdkClientCreateStoreRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientCreateStoreRequestInterface) Body(body client.ClientCreateStoreRequest) client.SdkClientCreateStoreRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientCreateStoreRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientCreateStoreRequest) client.SdkClientCreateStoreRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientCreateStoreRequestInterface) + } + } + + return r0 +} + +// MockSdkClientCreateStoreRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientCreateStoreRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body client.ClientCreateStoreRequest +func (_e *MockSdkClientCreateStoreRequestInterface_Expecter) Body(body interface{}) *MockSdkClientCreateStoreRequestInterface_Body_Call { + return &MockSdkClientCreateStoreRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientCreateStoreRequestInterface_Body_Call) Run(run func(body client.ClientCreateStoreRequest)) *MockSdkClientCreateStoreRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientCreateStoreRequest)) + }) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_Body_Call) Return(_a0 client.SdkClientCreateStoreRequestInterface) *MockSdkClientCreateStoreRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_Body_Call) RunAndReturn(run func(client.ClientCreateStoreRequest) client.SdkClientCreateStoreRequestInterface) *MockSdkClientCreateStoreRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientCreateStoreRequestInterface) Execute() (*openfga.CreateStoreResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.CreateStoreResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.CreateStoreResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.CreateStoreResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.CreateStoreResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientCreateStoreRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientCreateStoreRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientCreateStoreRequestInterface_Expecter) Execute() *MockSdkClientCreateStoreRequestInterface_Execute_Call { + return &MockSdkClientCreateStoreRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientCreateStoreRequestInterface_Execute_Call) Run(run func()) *MockSdkClientCreateStoreRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_Execute_Call) Return(_a0 *openfga.CreateStoreResponse, _a1 error) *MockSdkClientCreateStoreRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.CreateStoreResponse, error)) *MockSdkClientCreateStoreRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientCreateStoreRequestInterface) GetBody() *client.ClientCreateStoreRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *client.ClientCreateStoreRequest + if rf, ok := ret.Get(0).(func() *client.ClientCreateStoreRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientCreateStoreRequest) + } + } + + return r0 +} + +// MockSdkClientCreateStoreRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientCreateStoreRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientCreateStoreRequestInterface_Expecter) GetBody() *MockSdkClientCreateStoreRequestInterface_GetBody_Call { + return &MockSdkClientCreateStoreRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientCreateStoreRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientCreateStoreRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_GetBody_Call) Return(_a0 *client.ClientCreateStoreRequest) *MockSdkClientCreateStoreRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_GetBody_Call) RunAndReturn(run func() *client.ClientCreateStoreRequest) *MockSdkClientCreateStoreRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientCreateStoreRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientCreateStoreRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientCreateStoreRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientCreateStoreRequestInterface_Expecter) GetContext() *MockSdkClientCreateStoreRequestInterface_GetContext_Call { + return &MockSdkClientCreateStoreRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientCreateStoreRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientCreateStoreRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientCreateStoreRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientCreateStoreRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientCreateStoreRequestInterface) GetOptions() *client.ClientCreateStoreOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientCreateStoreOptions + if rf, ok := ret.Get(0).(func() *client.ClientCreateStoreOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientCreateStoreOptions) + } + } + + return r0 +} + +// MockSdkClientCreateStoreRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientCreateStoreRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientCreateStoreRequestInterface_Expecter) GetOptions() *MockSdkClientCreateStoreRequestInterface_GetOptions_Call { + return &MockSdkClientCreateStoreRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientCreateStoreRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientCreateStoreRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_GetOptions_Call) Return(_a0 *client.ClientCreateStoreOptions) *MockSdkClientCreateStoreRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientCreateStoreOptions) *MockSdkClientCreateStoreRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientCreateStoreRequestInterface) Options(options client.ClientCreateStoreOptions) client.SdkClientCreateStoreRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientCreateStoreRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientCreateStoreOptions) client.SdkClientCreateStoreRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientCreateStoreRequestInterface) + } + } + + return r0 +} + +// MockSdkClientCreateStoreRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientCreateStoreRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientCreateStoreOptions +func (_e *MockSdkClientCreateStoreRequestInterface_Expecter) Options(options interface{}) *MockSdkClientCreateStoreRequestInterface_Options_Call { + return &MockSdkClientCreateStoreRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientCreateStoreRequestInterface_Options_Call) Run(run func(options client.ClientCreateStoreOptions)) *MockSdkClientCreateStoreRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientCreateStoreOptions)) + }) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_Options_Call) Return(_a0 client.SdkClientCreateStoreRequestInterface) *MockSdkClientCreateStoreRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientCreateStoreRequestInterface_Options_Call) RunAndReturn(run func(client.ClientCreateStoreOptions) client.SdkClientCreateStoreRequestInterface) *MockSdkClientCreateStoreRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientCreateStoreRequestInterface creates a new instance of MockSdkClientCreateStoreRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientCreateStoreRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientCreateStoreRequestInterface { + mock := &MockSdkClientCreateStoreRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientDeleteStoreRequestInterface.go b/fgax/mockery/mock_SdkClientDeleteStoreRequestInterface.go new file mode 100644 index 0000000..1cfdd1f --- /dev/null +++ b/fgax/mockery/mock_SdkClientDeleteStoreRequestInterface.go @@ -0,0 +1,284 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" +) + +// MockSdkClientDeleteStoreRequestInterface is an autogenerated mock type for the SdkClientDeleteStoreRequestInterface type +type MockSdkClientDeleteStoreRequestInterface struct { + mock.Mock +} + +type MockSdkClientDeleteStoreRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientDeleteStoreRequestInterface) EXPECT() *MockSdkClientDeleteStoreRequestInterface_Expecter { + return &MockSdkClientDeleteStoreRequestInterface_Expecter{mock: &_m.Mock} +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientDeleteStoreRequestInterface) Execute() (*client.ClientDeleteStoreResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *client.ClientDeleteStoreResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*client.ClientDeleteStoreResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *client.ClientDeleteStoreResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientDeleteStoreResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientDeleteStoreRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientDeleteStoreRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientDeleteStoreRequestInterface_Expecter) Execute() *MockSdkClientDeleteStoreRequestInterface_Execute_Call { + return &MockSdkClientDeleteStoreRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_Execute_Call) Run(run func()) *MockSdkClientDeleteStoreRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_Execute_Call) Return(_a0 *client.ClientDeleteStoreResponse, _a1 error) *MockSdkClientDeleteStoreRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_Execute_Call) RunAndReturn(run func() (*client.ClientDeleteStoreResponse, error)) *MockSdkClientDeleteStoreRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientDeleteStoreRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientDeleteStoreRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientDeleteStoreRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientDeleteStoreRequestInterface_Expecter) GetContext() *MockSdkClientDeleteStoreRequestInterface_GetContext_Call { + return &MockSdkClientDeleteStoreRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientDeleteStoreRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientDeleteStoreRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientDeleteStoreRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientDeleteStoreRequestInterface) GetOptions() *client.ClientDeleteStoreOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientDeleteStoreOptions + if rf, ok := ret.Get(0).(func() *client.ClientDeleteStoreOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientDeleteStoreOptions) + } + } + + return r0 +} + +// MockSdkClientDeleteStoreRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientDeleteStoreRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientDeleteStoreRequestInterface_Expecter) GetOptions() *MockSdkClientDeleteStoreRequestInterface_GetOptions_Call { + return &MockSdkClientDeleteStoreRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientDeleteStoreRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_GetOptions_Call) Return(_a0 *client.ClientDeleteStoreOptions) *MockSdkClientDeleteStoreRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientDeleteStoreOptions) *MockSdkClientDeleteStoreRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientDeleteStoreRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientDeleteStoreRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientDeleteStoreRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientDeleteStoreRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientDeleteStoreRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientDeleteStoreRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientDeleteStoreRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientDeleteStoreRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientDeleteStoreRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientDeleteStoreRequestInterface) Options(options client.ClientDeleteStoreOptions) client.SdkClientDeleteStoreRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientDeleteStoreRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientDeleteStoreOptions) client.SdkClientDeleteStoreRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientDeleteStoreRequestInterface) + } + } + + return r0 +} + +// MockSdkClientDeleteStoreRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientDeleteStoreRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientDeleteStoreOptions +func (_e *MockSdkClientDeleteStoreRequestInterface_Expecter) Options(options interface{}) *MockSdkClientDeleteStoreRequestInterface_Options_Call { + return &MockSdkClientDeleteStoreRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_Options_Call) Run(run func(options client.ClientDeleteStoreOptions)) *MockSdkClientDeleteStoreRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientDeleteStoreOptions)) + }) + return _c +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_Options_Call) Return(_a0 client.SdkClientDeleteStoreRequestInterface) *MockSdkClientDeleteStoreRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientDeleteStoreRequestInterface_Options_Call) RunAndReturn(run func(client.ClientDeleteStoreOptions) client.SdkClientDeleteStoreRequestInterface) *MockSdkClientDeleteStoreRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientDeleteStoreRequestInterface creates a new instance of MockSdkClientDeleteStoreRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientDeleteStoreRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientDeleteStoreRequestInterface { + mock := &MockSdkClientDeleteStoreRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientDeleteTuplesRequestInterface.go b/fgax/mockery/mock_SdkClientDeleteTuplesRequestInterface.go new file mode 100644 index 0000000..d36b911 --- /dev/null +++ b/fgax/mockery/mock_SdkClientDeleteTuplesRequestInterface.go @@ -0,0 +1,334 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientDeleteTuplesRequestInterface is an autogenerated mock type for the SdkClientDeleteTuplesRequestInterface type +type MockSdkClientDeleteTuplesRequestInterface struct { + mock.Mock +} + +type MockSdkClientDeleteTuplesRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientDeleteTuplesRequestInterface) EXPECT() *MockSdkClientDeleteTuplesRequestInterface_Expecter { + return &MockSdkClientDeleteTuplesRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientDeleteTuplesRequestInterface) Body(body []openfga.TupleKeyWithoutCondition) client.SdkClientDeleteTuplesRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientDeleteTuplesRequestInterface + if rf, ok := ret.Get(0).(func([]openfga.TupleKeyWithoutCondition) client.SdkClientDeleteTuplesRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientDeleteTuplesRequestInterface) + } + } + + return r0 +} + +// MockSdkClientDeleteTuplesRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientDeleteTuplesRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body []openfga.TupleKeyWithoutCondition +func (_e *MockSdkClientDeleteTuplesRequestInterface_Expecter) Body(body interface{}) *MockSdkClientDeleteTuplesRequestInterface_Body_Call { + return &MockSdkClientDeleteTuplesRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_Body_Call) Run(run func(body []openfga.TupleKeyWithoutCondition)) *MockSdkClientDeleteTuplesRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].([]openfga.TupleKeyWithoutCondition)) + }) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_Body_Call) Return(_a0 client.SdkClientDeleteTuplesRequestInterface) *MockSdkClientDeleteTuplesRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_Body_Call) RunAndReturn(run func([]openfga.TupleKeyWithoutCondition) client.SdkClientDeleteTuplesRequestInterface) *MockSdkClientDeleteTuplesRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientDeleteTuplesRequestInterface) Execute() (*client.ClientWriteResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *client.ClientWriteResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*client.ClientWriteResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *client.ClientWriteResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientDeleteTuplesRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientDeleteTuplesRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientDeleteTuplesRequestInterface_Expecter) Execute() *MockSdkClientDeleteTuplesRequestInterface_Execute_Call { + return &MockSdkClientDeleteTuplesRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_Execute_Call) Run(run func()) *MockSdkClientDeleteTuplesRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_Execute_Call) Return(_a0 *client.ClientWriteResponse, _a1 error) *MockSdkClientDeleteTuplesRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_Execute_Call) RunAndReturn(run func() (*client.ClientWriteResponse, error)) *MockSdkClientDeleteTuplesRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientDeleteTuplesRequestInterface) GetBody() *[]openfga.TupleKeyWithoutCondition { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *[]openfga.TupleKeyWithoutCondition + if rf, ok := ret.Get(0).(func() *[]openfga.TupleKeyWithoutCondition); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*[]openfga.TupleKeyWithoutCondition) + } + } + + return r0 +} + +// MockSdkClientDeleteTuplesRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientDeleteTuplesRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientDeleteTuplesRequestInterface_Expecter) GetBody() *MockSdkClientDeleteTuplesRequestInterface_GetBody_Call { + return &MockSdkClientDeleteTuplesRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientDeleteTuplesRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_GetBody_Call) Return(_a0 *[]openfga.TupleKeyWithoutCondition) *MockSdkClientDeleteTuplesRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_GetBody_Call) RunAndReturn(run func() *[]openfga.TupleKeyWithoutCondition) *MockSdkClientDeleteTuplesRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientDeleteTuplesRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientDeleteTuplesRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientDeleteTuplesRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientDeleteTuplesRequestInterface_Expecter) GetContext() *MockSdkClientDeleteTuplesRequestInterface_GetContext_Call { + return &MockSdkClientDeleteTuplesRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientDeleteTuplesRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientDeleteTuplesRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientDeleteTuplesRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientDeleteTuplesRequestInterface) GetOptions() *client.ClientWriteOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientWriteOptions + if rf, ok := ret.Get(0).(func() *client.ClientWriteOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteOptions) + } + } + + return r0 +} + +// MockSdkClientDeleteTuplesRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientDeleteTuplesRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientDeleteTuplesRequestInterface_Expecter) GetOptions() *MockSdkClientDeleteTuplesRequestInterface_GetOptions_Call { + return &MockSdkClientDeleteTuplesRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientDeleteTuplesRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_GetOptions_Call) Return(_a0 *client.ClientWriteOptions) *MockSdkClientDeleteTuplesRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientWriteOptions) *MockSdkClientDeleteTuplesRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientDeleteTuplesRequestInterface) Options(options client.ClientWriteOptions) client.SdkClientDeleteTuplesRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientDeleteTuplesRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientWriteOptions) client.SdkClientDeleteTuplesRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientDeleteTuplesRequestInterface) + } + } + + return r0 +} + +// MockSdkClientDeleteTuplesRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientDeleteTuplesRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientWriteOptions +func (_e *MockSdkClientDeleteTuplesRequestInterface_Expecter) Options(options interface{}) *MockSdkClientDeleteTuplesRequestInterface_Options_Call { + return &MockSdkClientDeleteTuplesRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_Options_Call) Run(run func(options client.ClientWriteOptions)) *MockSdkClientDeleteTuplesRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientWriteOptions)) + }) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_Options_Call) Return(_a0 client.SdkClientDeleteTuplesRequestInterface) *MockSdkClientDeleteTuplesRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientDeleteTuplesRequestInterface_Options_Call) RunAndReturn(run func(client.ClientWriteOptions) client.SdkClientDeleteTuplesRequestInterface) *MockSdkClientDeleteTuplesRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientDeleteTuplesRequestInterface creates a new instance of MockSdkClientDeleteTuplesRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientDeleteTuplesRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientDeleteTuplesRequestInterface { + mock := &MockSdkClientDeleteTuplesRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientExpandRequestInterface.go b/fgax/mockery/mock_SdkClientExpandRequestInterface.go new file mode 100644 index 0000000..396e8e4 --- /dev/null +++ b/fgax/mockery/mock_SdkClientExpandRequestInterface.go @@ -0,0 +1,428 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientExpandRequestInterface is an autogenerated mock type for the SdkClientExpandRequestInterface type +type MockSdkClientExpandRequestInterface struct { + mock.Mock +} + +type MockSdkClientExpandRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientExpandRequestInterface) EXPECT() *MockSdkClientExpandRequestInterface_Expecter { + return &MockSdkClientExpandRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientExpandRequestInterface) Body(body client.ClientExpandRequest) client.SdkClientExpandRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientExpandRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientExpandRequest) client.SdkClientExpandRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientExpandRequestInterface) + } + } + + return r0 +} + +// MockSdkClientExpandRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientExpandRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body client.ClientExpandRequest +func (_e *MockSdkClientExpandRequestInterface_Expecter) Body(body interface{}) *MockSdkClientExpandRequestInterface_Body_Call { + return &MockSdkClientExpandRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientExpandRequestInterface_Body_Call) Run(run func(body client.ClientExpandRequest)) *MockSdkClientExpandRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientExpandRequest)) + }) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_Body_Call) Return(_a0 client.SdkClientExpandRequestInterface) *MockSdkClientExpandRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_Body_Call) RunAndReturn(run func(client.ClientExpandRequest) client.SdkClientExpandRequestInterface) *MockSdkClientExpandRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientExpandRequestInterface) Execute() (*openfga.ExpandResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.ExpandResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.ExpandResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.ExpandResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ExpandResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientExpandRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientExpandRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientExpandRequestInterface_Expecter) Execute() *MockSdkClientExpandRequestInterface_Execute_Call { + return &MockSdkClientExpandRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientExpandRequestInterface_Execute_Call) Run(run func()) *MockSdkClientExpandRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_Execute_Call) Return(_a0 *openfga.ExpandResponse, _a1 error) *MockSdkClientExpandRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.ExpandResponse, error)) *MockSdkClientExpandRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetAuthorizationModelIdOverride provides a mock function with given fields: +func (_m *MockSdkClientExpandRequestInterface) GetAuthorizationModelIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetAuthorizationModelIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientExpandRequestInterface_GetAuthorizationModelIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizationModelIdOverride' +type MockSdkClientExpandRequestInterface_GetAuthorizationModelIdOverride_Call struct { + *mock.Call +} + +// GetAuthorizationModelIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientExpandRequestInterface_Expecter) GetAuthorizationModelIdOverride() *MockSdkClientExpandRequestInterface_GetAuthorizationModelIdOverride_Call { + return &MockSdkClientExpandRequestInterface_GetAuthorizationModelIdOverride_Call{Call: _e.mock.On("GetAuthorizationModelIdOverride")} +} + +func (_c *MockSdkClientExpandRequestInterface_GetAuthorizationModelIdOverride_Call) Run(run func()) *MockSdkClientExpandRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_GetAuthorizationModelIdOverride_Call) Return(_a0 *string) *MockSdkClientExpandRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_GetAuthorizationModelIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientExpandRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientExpandRequestInterface) GetBody() *client.ClientExpandRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *client.ClientExpandRequest + if rf, ok := ret.Get(0).(func() *client.ClientExpandRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientExpandRequest) + } + } + + return r0 +} + +// MockSdkClientExpandRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientExpandRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientExpandRequestInterface_Expecter) GetBody() *MockSdkClientExpandRequestInterface_GetBody_Call { + return &MockSdkClientExpandRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientExpandRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientExpandRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_GetBody_Call) Return(_a0 *client.ClientExpandRequest) *MockSdkClientExpandRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_GetBody_Call) RunAndReturn(run func() *client.ClientExpandRequest) *MockSdkClientExpandRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientExpandRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientExpandRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientExpandRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientExpandRequestInterface_Expecter) GetContext() *MockSdkClientExpandRequestInterface_GetContext_Call { + return &MockSdkClientExpandRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientExpandRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientExpandRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientExpandRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientExpandRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientExpandRequestInterface) GetOptions() *client.ClientExpandOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientExpandOptions + if rf, ok := ret.Get(0).(func() *client.ClientExpandOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientExpandOptions) + } + } + + return r0 +} + +// MockSdkClientExpandRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientExpandRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientExpandRequestInterface_Expecter) GetOptions() *MockSdkClientExpandRequestInterface_GetOptions_Call { + return &MockSdkClientExpandRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientExpandRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientExpandRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_GetOptions_Call) Return(_a0 *client.ClientExpandOptions) *MockSdkClientExpandRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientExpandOptions) *MockSdkClientExpandRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientExpandRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientExpandRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientExpandRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientExpandRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientExpandRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientExpandRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientExpandRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientExpandRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientExpandRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientExpandRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientExpandRequestInterface) Options(options client.ClientExpandOptions) client.SdkClientExpandRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientExpandRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientExpandOptions) client.SdkClientExpandRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientExpandRequestInterface) + } + } + + return r0 +} + +// MockSdkClientExpandRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientExpandRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientExpandOptions +func (_e *MockSdkClientExpandRequestInterface_Expecter) Options(options interface{}) *MockSdkClientExpandRequestInterface_Options_Call { + return &MockSdkClientExpandRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientExpandRequestInterface_Options_Call) Run(run func(options client.ClientExpandOptions)) *MockSdkClientExpandRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientExpandOptions)) + }) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_Options_Call) Return(_a0 client.SdkClientExpandRequestInterface) *MockSdkClientExpandRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientExpandRequestInterface_Options_Call) RunAndReturn(run func(client.ClientExpandOptions) client.SdkClientExpandRequestInterface) *MockSdkClientExpandRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientExpandRequestInterface creates a new instance of MockSdkClientExpandRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientExpandRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientExpandRequestInterface { + mock := &MockSdkClientExpandRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientGetStoreRequestInterface.go b/fgax/mockery/mock_SdkClientGetStoreRequestInterface.go new file mode 100644 index 0000000..d213a58 --- /dev/null +++ b/fgax/mockery/mock_SdkClientGetStoreRequestInterface.go @@ -0,0 +1,286 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientGetStoreRequestInterface is an autogenerated mock type for the SdkClientGetStoreRequestInterface type +type MockSdkClientGetStoreRequestInterface struct { + mock.Mock +} + +type MockSdkClientGetStoreRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientGetStoreRequestInterface) EXPECT() *MockSdkClientGetStoreRequestInterface_Expecter { + return &MockSdkClientGetStoreRequestInterface_Expecter{mock: &_m.Mock} +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientGetStoreRequestInterface) Execute() (*openfga.GetStoreResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.GetStoreResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.GetStoreResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.GetStoreResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.GetStoreResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientGetStoreRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientGetStoreRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientGetStoreRequestInterface_Expecter) Execute() *MockSdkClientGetStoreRequestInterface_Execute_Call { + return &MockSdkClientGetStoreRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientGetStoreRequestInterface_Execute_Call) Run(run func()) *MockSdkClientGetStoreRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientGetStoreRequestInterface_Execute_Call) Return(_a0 *openfga.GetStoreResponse, _a1 error) *MockSdkClientGetStoreRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientGetStoreRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.GetStoreResponse, error)) *MockSdkClientGetStoreRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientGetStoreRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientGetStoreRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientGetStoreRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientGetStoreRequestInterface_Expecter) GetContext() *MockSdkClientGetStoreRequestInterface_GetContext_Call { + return &MockSdkClientGetStoreRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientGetStoreRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientGetStoreRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientGetStoreRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientGetStoreRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientGetStoreRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientGetStoreRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientGetStoreRequestInterface) GetOptions() *client.ClientGetStoreOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientGetStoreOptions + if rf, ok := ret.Get(0).(func() *client.ClientGetStoreOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientGetStoreOptions) + } + } + + return r0 +} + +// MockSdkClientGetStoreRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientGetStoreRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientGetStoreRequestInterface_Expecter) GetOptions() *MockSdkClientGetStoreRequestInterface_GetOptions_Call { + return &MockSdkClientGetStoreRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientGetStoreRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientGetStoreRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientGetStoreRequestInterface_GetOptions_Call) Return(_a0 *client.ClientGetStoreOptions) *MockSdkClientGetStoreRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientGetStoreRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientGetStoreOptions) *MockSdkClientGetStoreRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientGetStoreRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientGetStoreRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientGetStoreRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientGetStoreRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientGetStoreRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientGetStoreRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientGetStoreRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientGetStoreRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientGetStoreRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientGetStoreRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientGetStoreRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientGetStoreRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientGetStoreRequestInterface) Options(options client.ClientGetStoreOptions) client.SdkClientGetStoreRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientGetStoreRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientGetStoreOptions) client.SdkClientGetStoreRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientGetStoreRequestInterface) + } + } + + return r0 +} + +// MockSdkClientGetStoreRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientGetStoreRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientGetStoreOptions +func (_e *MockSdkClientGetStoreRequestInterface_Expecter) Options(options interface{}) *MockSdkClientGetStoreRequestInterface_Options_Call { + return &MockSdkClientGetStoreRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientGetStoreRequestInterface_Options_Call) Run(run func(options client.ClientGetStoreOptions)) *MockSdkClientGetStoreRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientGetStoreOptions)) + }) + return _c +} + +func (_c *MockSdkClientGetStoreRequestInterface_Options_Call) Return(_a0 client.SdkClientGetStoreRequestInterface) *MockSdkClientGetStoreRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientGetStoreRequestInterface_Options_Call) RunAndReturn(run func(client.ClientGetStoreOptions) client.SdkClientGetStoreRequestInterface) *MockSdkClientGetStoreRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientGetStoreRequestInterface creates a new instance of MockSdkClientGetStoreRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientGetStoreRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientGetStoreRequestInterface { + mock := &MockSdkClientGetStoreRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientListObjectsRequestInterface.go b/fgax/mockery/mock_SdkClientListObjectsRequestInterface.go new file mode 100644 index 0000000..ecb006a --- /dev/null +++ b/fgax/mockery/mock_SdkClientListObjectsRequestInterface.go @@ -0,0 +1,428 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientListObjectsRequestInterface is an autogenerated mock type for the SdkClientListObjectsRequestInterface type +type MockSdkClientListObjectsRequestInterface struct { + mock.Mock +} + +type MockSdkClientListObjectsRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientListObjectsRequestInterface) EXPECT() *MockSdkClientListObjectsRequestInterface_Expecter { + return &MockSdkClientListObjectsRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientListObjectsRequestInterface) Body(body client.ClientListObjectsRequest) client.SdkClientListObjectsRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientListObjectsRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientListObjectsRequest) client.SdkClientListObjectsRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListObjectsRequestInterface) + } + } + + return r0 +} + +// MockSdkClientListObjectsRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientListObjectsRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body client.ClientListObjectsRequest +func (_e *MockSdkClientListObjectsRequestInterface_Expecter) Body(body interface{}) *MockSdkClientListObjectsRequestInterface_Body_Call { + return &MockSdkClientListObjectsRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientListObjectsRequestInterface_Body_Call) Run(run func(body client.ClientListObjectsRequest)) *MockSdkClientListObjectsRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientListObjectsRequest)) + }) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_Body_Call) Return(_a0 client.SdkClientListObjectsRequestInterface) *MockSdkClientListObjectsRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_Body_Call) RunAndReturn(run func(client.ClientListObjectsRequest) client.SdkClientListObjectsRequestInterface) *MockSdkClientListObjectsRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientListObjectsRequestInterface) Execute() (*openfga.ListObjectsResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.ListObjectsResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.ListObjectsResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.ListObjectsResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ListObjectsResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientListObjectsRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientListObjectsRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientListObjectsRequestInterface_Expecter) Execute() *MockSdkClientListObjectsRequestInterface_Execute_Call { + return &MockSdkClientListObjectsRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientListObjectsRequestInterface_Execute_Call) Run(run func()) *MockSdkClientListObjectsRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_Execute_Call) Return(_a0 *openfga.ListObjectsResponse, _a1 error) *MockSdkClientListObjectsRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.ListObjectsResponse, error)) *MockSdkClientListObjectsRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetAuthorizationModelIdOverride provides a mock function with given fields: +func (_m *MockSdkClientListObjectsRequestInterface) GetAuthorizationModelIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetAuthorizationModelIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientListObjectsRequestInterface_GetAuthorizationModelIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizationModelIdOverride' +type MockSdkClientListObjectsRequestInterface_GetAuthorizationModelIdOverride_Call struct { + *mock.Call +} + +// GetAuthorizationModelIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientListObjectsRequestInterface_Expecter) GetAuthorizationModelIdOverride() *MockSdkClientListObjectsRequestInterface_GetAuthorizationModelIdOverride_Call { + return &MockSdkClientListObjectsRequestInterface_GetAuthorizationModelIdOverride_Call{Call: _e.mock.On("GetAuthorizationModelIdOverride")} +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetAuthorizationModelIdOverride_Call) Run(run func()) *MockSdkClientListObjectsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetAuthorizationModelIdOverride_Call) Return(_a0 *string) *MockSdkClientListObjectsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetAuthorizationModelIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientListObjectsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientListObjectsRequestInterface) GetBody() *client.ClientListObjectsRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *client.ClientListObjectsRequest + if rf, ok := ret.Get(0).(func() *client.ClientListObjectsRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientListObjectsRequest) + } + } + + return r0 +} + +// MockSdkClientListObjectsRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientListObjectsRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientListObjectsRequestInterface_Expecter) GetBody() *MockSdkClientListObjectsRequestInterface_GetBody_Call { + return &MockSdkClientListObjectsRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientListObjectsRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetBody_Call) Return(_a0 *client.ClientListObjectsRequest) *MockSdkClientListObjectsRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetBody_Call) RunAndReturn(run func() *client.ClientListObjectsRequest) *MockSdkClientListObjectsRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientListObjectsRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientListObjectsRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientListObjectsRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientListObjectsRequestInterface_Expecter) GetContext() *MockSdkClientListObjectsRequestInterface_GetContext_Call { + return &MockSdkClientListObjectsRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientListObjectsRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientListObjectsRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientListObjectsRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientListObjectsRequestInterface) GetOptions() *client.ClientListObjectsOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientListObjectsOptions + if rf, ok := ret.Get(0).(func() *client.ClientListObjectsOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientListObjectsOptions) + } + } + + return r0 +} + +// MockSdkClientListObjectsRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientListObjectsRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientListObjectsRequestInterface_Expecter) GetOptions() *MockSdkClientListObjectsRequestInterface_GetOptions_Call { + return &MockSdkClientListObjectsRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientListObjectsRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetOptions_Call) Return(_a0 *client.ClientListObjectsOptions) *MockSdkClientListObjectsRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientListObjectsOptions) *MockSdkClientListObjectsRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientListObjectsRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientListObjectsRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientListObjectsRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientListObjectsRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientListObjectsRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientListObjectsRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientListObjectsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientListObjectsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientListObjectsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientListObjectsRequestInterface) Options(options client.ClientListObjectsOptions) client.SdkClientListObjectsRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientListObjectsRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientListObjectsOptions) client.SdkClientListObjectsRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListObjectsRequestInterface) + } + } + + return r0 +} + +// MockSdkClientListObjectsRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientListObjectsRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientListObjectsOptions +func (_e *MockSdkClientListObjectsRequestInterface_Expecter) Options(options interface{}) *MockSdkClientListObjectsRequestInterface_Options_Call { + return &MockSdkClientListObjectsRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientListObjectsRequestInterface_Options_Call) Run(run func(options client.ClientListObjectsOptions)) *MockSdkClientListObjectsRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientListObjectsOptions)) + }) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_Options_Call) Return(_a0 client.SdkClientListObjectsRequestInterface) *MockSdkClientListObjectsRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListObjectsRequestInterface_Options_Call) RunAndReturn(run func(client.ClientListObjectsOptions) client.SdkClientListObjectsRequestInterface) *MockSdkClientListObjectsRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientListObjectsRequestInterface creates a new instance of MockSdkClientListObjectsRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientListObjectsRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientListObjectsRequestInterface { + mock := &MockSdkClientListObjectsRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientListRelationsRequestInterface.go b/fgax/mockery/mock_SdkClientListRelationsRequestInterface.go new file mode 100644 index 0000000..f8b6abc --- /dev/null +++ b/fgax/mockery/mock_SdkClientListRelationsRequestInterface.go @@ -0,0 +1,426 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" +) + +// MockSdkClientListRelationsRequestInterface is an autogenerated mock type for the SdkClientListRelationsRequestInterface type +type MockSdkClientListRelationsRequestInterface struct { + mock.Mock +} + +type MockSdkClientListRelationsRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientListRelationsRequestInterface) EXPECT() *MockSdkClientListRelationsRequestInterface_Expecter { + return &MockSdkClientListRelationsRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientListRelationsRequestInterface) Body(body client.ClientListRelationsRequest) client.SdkClientListRelationsRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientListRelationsRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientListRelationsRequest) client.SdkClientListRelationsRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListRelationsRequestInterface) + } + } + + return r0 +} + +// MockSdkClientListRelationsRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientListRelationsRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body client.ClientListRelationsRequest +func (_e *MockSdkClientListRelationsRequestInterface_Expecter) Body(body interface{}) *MockSdkClientListRelationsRequestInterface_Body_Call { + return &MockSdkClientListRelationsRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientListRelationsRequestInterface_Body_Call) Run(run func(body client.ClientListRelationsRequest)) *MockSdkClientListRelationsRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientListRelationsRequest)) + }) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_Body_Call) Return(_a0 client.SdkClientListRelationsRequestInterface) *MockSdkClientListRelationsRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_Body_Call) RunAndReturn(run func(client.ClientListRelationsRequest) client.SdkClientListRelationsRequestInterface) *MockSdkClientListRelationsRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientListRelationsRequestInterface) Execute() (*client.ClientListRelationsResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *client.ClientListRelationsResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*client.ClientListRelationsResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *client.ClientListRelationsResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientListRelationsResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientListRelationsRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientListRelationsRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientListRelationsRequestInterface_Expecter) Execute() *MockSdkClientListRelationsRequestInterface_Execute_Call { + return &MockSdkClientListRelationsRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientListRelationsRequestInterface_Execute_Call) Run(run func()) *MockSdkClientListRelationsRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_Execute_Call) Return(_a0 *client.ClientListRelationsResponse, _a1 error) *MockSdkClientListRelationsRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_Execute_Call) RunAndReturn(run func() (*client.ClientListRelationsResponse, error)) *MockSdkClientListRelationsRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetAuthorizationModelIdOverride provides a mock function with given fields: +func (_m *MockSdkClientListRelationsRequestInterface) GetAuthorizationModelIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetAuthorizationModelIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientListRelationsRequestInterface_GetAuthorizationModelIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizationModelIdOverride' +type MockSdkClientListRelationsRequestInterface_GetAuthorizationModelIdOverride_Call struct { + *mock.Call +} + +// GetAuthorizationModelIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientListRelationsRequestInterface_Expecter) GetAuthorizationModelIdOverride() *MockSdkClientListRelationsRequestInterface_GetAuthorizationModelIdOverride_Call { + return &MockSdkClientListRelationsRequestInterface_GetAuthorizationModelIdOverride_Call{Call: _e.mock.On("GetAuthorizationModelIdOverride")} +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetAuthorizationModelIdOverride_Call) Run(run func()) *MockSdkClientListRelationsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetAuthorizationModelIdOverride_Call) Return(_a0 *string) *MockSdkClientListRelationsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetAuthorizationModelIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientListRelationsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientListRelationsRequestInterface) GetBody() *client.ClientListRelationsRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *client.ClientListRelationsRequest + if rf, ok := ret.Get(0).(func() *client.ClientListRelationsRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientListRelationsRequest) + } + } + + return r0 +} + +// MockSdkClientListRelationsRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientListRelationsRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientListRelationsRequestInterface_Expecter) GetBody() *MockSdkClientListRelationsRequestInterface_GetBody_Call { + return &MockSdkClientListRelationsRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientListRelationsRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetBody_Call) Return(_a0 *client.ClientListRelationsRequest) *MockSdkClientListRelationsRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetBody_Call) RunAndReturn(run func() *client.ClientListRelationsRequest) *MockSdkClientListRelationsRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientListRelationsRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientListRelationsRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientListRelationsRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientListRelationsRequestInterface_Expecter) GetContext() *MockSdkClientListRelationsRequestInterface_GetContext_Call { + return &MockSdkClientListRelationsRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientListRelationsRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientListRelationsRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientListRelationsRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientListRelationsRequestInterface) GetOptions() *client.ClientListRelationsOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientListRelationsOptions + if rf, ok := ret.Get(0).(func() *client.ClientListRelationsOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientListRelationsOptions) + } + } + + return r0 +} + +// MockSdkClientListRelationsRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientListRelationsRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientListRelationsRequestInterface_Expecter) GetOptions() *MockSdkClientListRelationsRequestInterface_GetOptions_Call { + return &MockSdkClientListRelationsRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientListRelationsRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetOptions_Call) Return(_a0 *client.ClientListRelationsOptions) *MockSdkClientListRelationsRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientListRelationsOptions) *MockSdkClientListRelationsRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientListRelationsRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientListRelationsRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientListRelationsRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientListRelationsRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientListRelationsRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientListRelationsRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientListRelationsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientListRelationsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientListRelationsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientListRelationsRequestInterface) Options(options client.ClientListRelationsOptions) client.SdkClientListRelationsRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientListRelationsRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientListRelationsOptions) client.SdkClientListRelationsRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListRelationsRequestInterface) + } + } + + return r0 +} + +// MockSdkClientListRelationsRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientListRelationsRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientListRelationsOptions +func (_e *MockSdkClientListRelationsRequestInterface_Expecter) Options(options interface{}) *MockSdkClientListRelationsRequestInterface_Options_Call { + return &MockSdkClientListRelationsRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientListRelationsRequestInterface_Options_Call) Run(run func(options client.ClientListRelationsOptions)) *MockSdkClientListRelationsRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientListRelationsOptions)) + }) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_Options_Call) Return(_a0 client.SdkClientListRelationsRequestInterface) *MockSdkClientListRelationsRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListRelationsRequestInterface_Options_Call) RunAndReturn(run func(client.ClientListRelationsOptions) client.SdkClientListRelationsRequestInterface) *MockSdkClientListRelationsRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientListRelationsRequestInterface creates a new instance of MockSdkClientListRelationsRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientListRelationsRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientListRelationsRequestInterface { + mock := &MockSdkClientListRelationsRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientListStoresRequestInterface.go b/fgax/mockery/mock_SdkClientListStoresRequestInterface.go new file mode 100644 index 0000000..9988e9e --- /dev/null +++ b/fgax/mockery/mock_SdkClientListStoresRequestInterface.go @@ -0,0 +1,239 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientListStoresRequestInterface is an autogenerated mock type for the SdkClientListStoresRequestInterface type +type MockSdkClientListStoresRequestInterface struct { + mock.Mock +} + +type MockSdkClientListStoresRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientListStoresRequestInterface) EXPECT() *MockSdkClientListStoresRequestInterface_Expecter { + return &MockSdkClientListStoresRequestInterface_Expecter{mock: &_m.Mock} +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientListStoresRequestInterface) Execute() (*openfga.ListStoresResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.ListStoresResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.ListStoresResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.ListStoresResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ListStoresResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientListStoresRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientListStoresRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientListStoresRequestInterface_Expecter) Execute() *MockSdkClientListStoresRequestInterface_Execute_Call { + return &MockSdkClientListStoresRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientListStoresRequestInterface_Execute_Call) Run(run func()) *MockSdkClientListStoresRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListStoresRequestInterface_Execute_Call) Return(_a0 *openfga.ListStoresResponse, _a1 error) *MockSdkClientListStoresRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientListStoresRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.ListStoresResponse, error)) *MockSdkClientListStoresRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientListStoresRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientListStoresRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientListStoresRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientListStoresRequestInterface_Expecter) GetContext() *MockSdkClientListStoresRequestInterface_GetContext_Call { + return &MockSdkClientListStoresRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientListStoresRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientListStoresRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListStoresRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientListStoresRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListStoresRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientListStoresRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientListStoresRequestInterface) GetOptions() *client.ClientListStoresOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientListStoresOptions + if rf, ok := ret.Get(0).(func() *client.ClientListStoresOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientListStoresOptions) + } + } + + return r0 +} + +// MockSdkClientListStoresRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientListStoresRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientListStoresRequestInterface_Expecter) GetOptions() *MockSdkClientListStoresRequestInterface_GetOptions_Call { + return &MockSdkClientListStoresRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientListStoresRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientListStoresRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListStoresRequestInterface_GetOptions_Call) Return(_a0 *client.ClientListStoresOptions) *MockSdkClientListStoresRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListStoresRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientListStoresOptions) *MockSdkClientListStoresRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientListStoresRequestInterface) Options(options client.ClientListStoresOptions) client.SdkClientListStoresRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientListStoresRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientListStoresOptions) client.SdkClientListStoresRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListStoresRequestInterface) + } + } + + return r0 +} + +// MockSdkClientListStoresRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientListStoresRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientListStoresOptions +func (_e *MockSdkClientListStoresRequestInterface_Expecter) Options(options interface{}) *MockSdkClientListStoresRequestInterface_Options_Call { + return &MockSdkClientListStoresRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientListStoresRequestInterface_Options_Call) Run(run func(options client.ClientListStoresOptions)) *MockSdkClientListStoresRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientListStoresOptions)) + }) + return _c +} + +func (_c *MockSdkClientListStoresRequestInterface_Options_Call) Return(_a0 client.SdkClientListStoresRequestInterface) *MockSdkClientListStoresRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListStoresRequestInterface_Options_Call) RunAndReturn(run func(client.ClientListStoresOptions) client.SdkClientListStoresRequestInterface) *MockSdkClientListStoresRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientListStoresRequestInterface creates a new instance of MockSdkClientListStoresRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientListStoresRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientListStoresRequestInterface { + mock := &MockSdkClientListStoresRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientListUsersRequestInterface.go b/fgax/mockery/mock_SdkClientListUsersRequestInterface.go new file mode 100644 index 0000000..0ec6be1 --- /dev/null +++ b/fgax/mockery/mock_SdkClientListUsersRequestInterface.go @@ -0,0 +1,428 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientListUsersRequestInterface is an autogenerated mock type for the SdkClientListUsersRequestInterface type +type MockSdkClientListUsersRequestInterface struct { + mock.Mock +} + +type MockSdkClientListUsersRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientListUsersRequestInterface) EXPECT() *MockSdkClientListUsersRequestInterface_Expecter { + return &MockSdkClientListUsersRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientListUsersRequestInterface) Body(body client.ClientListUsersRequest) client.SdkClientListUsersRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientListUsersRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientListUsersRequest) client.SdkClientListUsersRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListUsersRequestInterface) + } + } + + return r0 +} + +// MockSdkClientListUsersRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientListUsersRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body client.ClientListUsersRequest +func (_e *MockSdkClientListUsersRequestInterface_Expecter) Body(body interface{}) *MockSdkClientListUsersRequestInterface_Body_Call { + return &MockSdkClientListUsersRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientListUsersRequestInterface_Body_Call) Run(run func(body client.ClientListUsersRequest)) *MockSdkClientListUsersRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientListUsersRequest)) + }) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_Body_Call) Return(_a0 client.SdkClientListUsersRequestInterface) *MockSdkClientListUsersRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_Body_Call) RunAndReturn(run func(client.ClientListUsersRequest) client.SdkClientListUsersRequestInterface) *MockSdkClientListUsersRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientListUsersRequestInterface) Execute() (*openfga.ListUsersResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.ListUsersResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.ListUsersResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.ListUsersResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ListUsersResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientListUsersRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientListUsersRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientListUsersRequestInterface_Expecter) Execute() *MockSdkClientListUsersRequestInterface_Execute_Call { + return &MockSdkClientListUsersRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientListUsersRequestInterface_Execute_Call) Run(run func()) *MockSdkClientListUsersRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_Execute_Call) Return(_a0 *openfga.ListUsersResponse, _a1 error) *MockSdkClientListUsersRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.ListUsersResponse, error)) *MockSdkClientListUsersRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetAuthorizationModelIdOverride provides a mock function with given fields: +func (_m *MockSdkClientListUsersRequestInterface) GetAuthorizationModelIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetAuthorizationModelIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientListUsersRequestInterface_GetAuthorizationModelIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizationModelIdOverride' +type MockSdkClientListUsersRequestInterface_GetAuthorizationModelIdOverride_Call struct { + *mock.Call +} + +// GetAuthorizationModelIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientListUsersRequestInterface_Expecter) GetAuthorizationModelIdOverride() *MockSdkClientListUsersRequestInterface_GetAuthorizationModelIdOverride_Call { + return &MockSdkClientListUsersRequestInterface_GetAuthorizationModelIdOverride_Call{Call: _e.mock.On("GetAuthorizationModelIdOverride")} +} + +func (_c *MockSdkClientListUsersRequestInterface_GetAuthorizationModelIdOverride_Call) Run(run func()) *MockSdkClientListUsersRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_GetAuthorizationModelIdOverride_Call) Return(_a0 *string) *MockSdkClientListUsersRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_GetAuthorizationModelIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientListUsersRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientListUsersRequestInterface) GetBody() *client.ClientListUsersRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *client.ClientListUsersRequest + if rf, ok := ret.Get(0).(func() *client.ClientListUsersRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientListUsersRequest) + } + } + + return r0 +} + +// MockSdkClientListUsersRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientListUsersRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientListUsersRequestInterface_Expecter) GetBody() *MockSdkClientListUsersRequestInterface_GetBody_Call { + return &MockSdkClientListUsersRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientListUsersRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientListUsersRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_GetBody_Call) Return(_a0 *client.ClientListUsersRequest) *MockSdkClientListUsersRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_GetBody_Call) RunAndReturn(run func() *client.ClientListUsersRequest) *MockSdkClientListUsersRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientListUsersRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientListUsersRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientListUsersRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientListUsersRequestInterface_Expecter) GetContext() *MockSdkClientListUsersRequestInterface_GetContext_Call { + return &MockSdkClientListUsersRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientListUsersRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientListUsersRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientListUsersRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientListUsersRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientListUsersRequestInterface) GetOptions() *client.ClientListUsersOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientListUsersOptions + if rf, ok := ret.Get(0).(func() *client.ClientListUsersOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientListUsersOptions) + } + } + + return r0 +} + +// MockSdkClientListUsersRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientListUsersRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientListUsersRequestInterface_Expecter) GetOptions() *MockSdkClientListUsersRequestInterface_GetOptions_Call { + return &MockSdkClientListUsersRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientListUsersRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientListUsersRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_GetOptions_Call) Return(_a0 *client.ClientListUsersOptions) *MockSdkClientListUsersRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientListUsersOptions) *MockSdkClientListUsersRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientListUsersRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientListUsersRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientListUsersRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientListUsersRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientListUsersRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientListUsersRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientListUsersRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientListUsersRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientListUsersRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientListUsersRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientListUsersRequestInterface) Options(options client.ClientListUsersOptions) client.SdkClientListUsersRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientListUsersRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientListUsersOptions) client.SdkClientListUsersRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientListUsersRequestInterface) + } + } + + return r0 +} + +// MockSdkClientListUsersRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientListUsersRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientListUsersOptions +func (_e *MockSdkClientListUsersRequestInterface_Expecter) Options(options interface{}) *MockSdkClientListUsersRequestInterface_Options_Call { + return &MockSdkClientListUsersRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientListUsersRequestInterface_Options_Call) Run(run func(options client.ClientListUsersOptions)) *MockSdkClientListUsersRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientListUsersOptions)) + }) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_Options_Call) Return(_a0 client.SdkClientListUsersRequestInterface) *MockSdkClientListUsersRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientListUsersRequestInterface_Options_Call) RunAndReturn(run func(client.ClientListUsersOptions) client.SdkClientListUsersRequestInterface) *MockSdkClientListUsersRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientListUsersRequestInterface creates a new instance of MockSdkClientListUsersRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientListUsersRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientListUsersRequestInterface { + mock := &MockSdkClientListUsersRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientReadAssertionsRequestInterface.go b/fgax/mockery/mock_SdkClientReadAssertionsRequestInterface.go new file mode 100644 index 0000000..6baca08 --- /dev/null +++ b/fgax/mockery/mock_SdkClientReadAssertionsRequestInterface.go @@ -0,0 +1,333 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientReadAssertionsRequestInterface is an autogenerated mock type for the SdkClientReadAssertionsRequestInterface type +type MockSdkClientReadAssertionsRequestInterface struct { + mock.Mock +} + +type MockSdkClientReadAssertionsRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientReadAssertionsRequestInterface) EXPECT() *MockSdkClientReadAssertionsRequestInterface_Expecter { + return &MockSdkClientReadAssertionsRequestInterface_Expecter{mock: &_m.Mock} +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientReadAssertionsRequestInterface) Execute() (*openfga.ReadAssertionsResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.ReadAssertionsResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.ReadAssertionsResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.ReadAssertionsResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadAssertionsResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientReadAssertionsRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientReadAssertionsRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientReadAssertionsRequestInterface_Expecter) Execute() *MockSdkClientReadAssertionsRequestInterface_Execute_Call { + return &MockSdkClientReadAssertionsRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_Execute_Call) Run(run func()) *MockSdkClientReadAssertionsRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_Execute_Call) Return(_a0 *openfga.ReadAssertionsResponse, _a1 error) *MockSdkClientReadAssertionsRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.ReadAssertionsResponse, error)) *MockSdkClientReadAssertionsRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetAuthorizationModelIdOverride provides a mock function with given fields: +func (_m *MockSdkClientReadAssertionsRequestInterface) GetAuthorizationModelIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetAuthorizationModelIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientReadAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizationModelIdOverride' +type MockSdkClientReadAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call struct { + *mock.Call +} + +// GetAuthorizationModelIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientReadAssertionsRequestInterface_Expecter) GetAuthorizationModelIdOverride() *MockSdkClientReadAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call { + return &MockSdkClientReadAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call{Call: _e.mock.On("GetAuthorizationModelIdOverride")} +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call) Run(run func()) *MockSdkClientReadAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call) Return(_a0 *string) *MockSdkClientReadAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientReadAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientReadAssertionsRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientReadAssertionsRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientReadAssertionsRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientReadAssertionsRequestInterface_Expecter) GetContext() *MockSdkClientReadAssertionsRequestInterface_GetContext_Call { + return &MockSdkClientReadAssertionsRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientReadAssertionsRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientReadAssertionsRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientReadAssertionsRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientReadAssertionsRequestInterface) GetOptions() *client.ClientReadAssertionsOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientReadAssertionsOptions + if rf, ok := ret.Get(0).(func() *client.ClientReadAssertionsOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientReadAssertionsOptions) + } + } + + return r0 +} + +// MockSdkClientReadAssertionsRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientReadAssertionsRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientReadAssertionsRequestInterface_Expecter) GetOptions() *MockSdkClientReadAssertionsRequestInterface_GetOptions_Call { + return &MockSdkClientReadAssertionsRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientReadAssertionsRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetOptions_Call) Return(_a0 *client.ClientReadAssertionsOptions) *MockSdkClientReadAssertionsRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientReadAssertionsOptions) *MockSdkClientReadAssertionsRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientReadAssertionsRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientReadAssertionsRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientReadAssertionsRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientReadAssertionsRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientReadAssertionsRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientReadAssertionsRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientReadAssertionsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientReadAssertionsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientReadAssertionsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientReadAssertionsRequestInterface) Options(options client.ClientReadAssertionsOptions) client.SdkClientReadAssertionsRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientReadAssertionsRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientReadAssertionsOptions) client.SdkClientReadAssertionsRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadAssertionsRequestInterface) + } + } + + return r0 +} + +// MockSdkClientReadAssertionsRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientReadAssertionsRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientReadAssertionsOptions +func (_e *MockSdkClientReadAssertionsRequestInterface_Expecter) Options(options interface{}) *MockSdkClientReadAssertionsRequestInterface_Options_Call { + return &MockSdkClientReadAssertionsRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_Options_Call) Run(run func(options client.ClientReadAssertionsOptions)) *MockSdkClientReadAssertionsRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientReadAssertionsOptions)) + }) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_Options_Call) Return(_a0 client.SdkClientReadAssertionsRequestInterface) *MockSdkClientReadAssertionsRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAssertionsRequestInterface_Options_Call) RunAndReturn(run func(client.ClientReadAssertionsOptions) client.SdkClientReadAssertionsRequestInterface) *MockSdkClientReadAssertionsRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientReadAssertionsRequestInterface creates a new instance of MockSdkClientReadAssertionsRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientReadAssertionsRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientReadAssertionsRequestInterface { + mock := &MockSdkClientReadAssertionsRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientReadAuthorizationModelRequestInterface.go b/fgax/mockery/mock_SdkClientReadAuthorizationModelRequestInterface.go new file mode 100644 index 0000000..0ac3da3 --- /dev/null +++ b/fgax/mockery/mock_SdkClientReadAuthorizationModelRequestInterface.go @@ -0,0 +1,428 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientReadAuthorizationModelRequestInterface is an autogenerated mock type for the SdkClientReadAuthorizationModelRequestInterface type +type MockSdkClientReadAuthorizationModelRequestInterface struct { + mock.Mock +} + +type MockSdkClientReadAuthorizationModelRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientReadAuthorizationModelRequestInterface) EXPECT() *MockSdkClientReadAuthorizationModelRequestInterface_Expecter { + return &MockSdkClientReadAuthorizationModelRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientReadAuthorizationModelRequestInterface) Body(body client.ClientReadAuthorizationModelRequest) client.SdkClientReadAuthorizationModelRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientReadAuthorizationModelRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientReadAuthorizationModelRequest) client.SdkClientReadAuthorizationModelRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadAuthorizationModelRequestInterface) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientReadAuthorizationModelRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body client.ClientReadAuthorizationModelRequest +func (_e *MockSdkClientReadAuthorizationModelRequestInterface_Expecter) Body(body interface{}) *MockSdkClientReadAuthorizationModelRequestInterface_Body_Call { + return &MockSdkClientReadAuthorizationModelRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_Body_Call) Run(run func(body client.ClientReadAuthorizationModelRequest)) *MockSdkClientReadAuthorizationModelRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientReadAuthorizationModelRequest)) + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_Body_Call) Return(_a0 client.SdkClientReadAuthorizationModelRequestInterface) *MockSdkClientReadAuthorizationModelRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_Body_Call) RunAndReturn(run func(client.ClientReadAuthorizationModelRequest) client.SdkClientReadAuthorizationModelRequestInterface) *MockSdkClientReadAuthorizationModelRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientReadAuthorizationModelRequestInterface) Execute() (*openfga.ReadAuthorizationModelResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.ReadAuthorizationModelResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.ReadAuthorizationModelResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.ReadAuthorizationModelResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadAuthorizationModelResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientReadAuthorizationModelRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientReadAuthorizationModelRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientReadAuthorizationModelRequestInterface_Expecter) Execute() *MockSdkClientReadAuthorizationModelRequestInterface_Execute_Call { + return &MockSdkClientReadAuthorizationModelRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_Execute_Call) Run(run func()) *MockSdkClientReadAuthorizationModelRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_Execute_Call) Return(_a0 *openfga.ReadAuthorizationModelResponse, _a1 error) *MockSdkClientReadAuthorizationModelRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.ReadAuthorizationModelResponse, error)) *MockSdkClientReadAuthorizationModelRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetAuthorizationModelIdOverride provides a mock function with given fields: +func (_m *MockSdkClientReadAuthorizationModelRequestInterface) GetAuthorizationModelIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetAuthorizationModelIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelRequestInterface_GetAuthorizationModelIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizationModelIdOverride' +type MockSdkClientReadAuthorizationModelRequestInterface_GetAuthorizationModelIdOverride_Call struct { + *mock.Call +} + +// GetAuthorizationModelIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientReadAuthorizationModelRequestInterface_Expecter) GetAuthorizationModelIdOverride() *MockSdkClientReadAuthorizationModelRequestInterface_GetAuthorizationModelIdOverride_Call { + return &MockSdkClientReadAuthorizationModelRequestInterface_GetAuthorizationModelIdOverride_Call{Call: _e.mock.On("GetAuthorizationModelIdOverride")} +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetAuthorizationModelIdOverride_Call) Run(run func()) *MockSdkClientReadAuthorizationModelRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetAuthorizationModelIdOverride_Call) Return(_a0 *string) *MockSdkClientReadAuthorizationModelRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetAuthorizationModelIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientReadAuthorizationModelRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientReadAuthorizationModelRequestInterface) GetBody() *client.ClientReadAuthorizationModelRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *client.ClientReadAuthorizationModelRequest + if rf, ok := ret.Get(0).(func() *client.ClientReadAuthorizationModelRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientReadAuthorizationModelRequest) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientReadAuthorizationModelRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientReadAuthorizationModelRequestInterface_Expecter) GetBody() *MockSdkClientReadAuthorizationModelRequestInterface_GetBody_Call { + return &MockSdkClientReadAuthorizationModelRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientReadAuthorizationModelRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetBody_Call) Return(_a0 *client.ClientReadAuthorizationModelRequest) *MockSdkClientReadAuthorizationModelRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetBody_Call) RunAndReturn(run func() *client.ClientReadAuthorizationModelRequest) *MockSdkClientReadAuthorizationModelRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientReadAuthorizationModelRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientReadAuthorizationModelRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientReadAuthorizationModelRequestInterface_Expecter) GetContext() *MockSdkClientReadAuthorizationModelRequestInterface_GetContext_Call { + return &MockSdkClientReadAuthorizationModelRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientReadAuthorizationModelRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientReadAuthorizationModelRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientReadAuthorizationModelRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientReadAuthorizationModelRequestInterface) GetOptions() *client.ClientReadAuthorizationModelOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientReadAuthorizationModelOptions + if rf, ok := ret.Get(0).(func() *client.ClientReadAuthorizationModelOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientReadAuthorizationModelOptions) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientReadAuthorizationModelRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientReadAuthorizationModelRequestInterface_Expecter) GetOptions() *MockSdkClientReadAuthorizationModelRequestInterface_GetOptions_Call { + return &MockSdkClientReadAuthorizationModelRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientReadAuthorizationModelRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetOptions_Call) Return(_a0 *client.ClientReadAuthorizationModelOptions) *MockSdkClientReadAuthorizationModelRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientReadAuthorizationModelOptions) *MockSdkClientReadAuthorizationModelRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientReadAuthorizationModelRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientReadAuthorizationModelRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientReadAuthorizationModelRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientReadAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientReadAuthorizationModelRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientReadAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientReadAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientReadAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientReadAuthorizationModelRequestInterface) Options(options client.ClientReadAuthorizationModelOptions) client.SdkClientReadAuthorizationModelRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientReadAuthorizationModelRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientReadAuthorizationModelOptions) client.SdkClientReadAuthorizationModelRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadAuthorizationModelRequestInterface) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientReadAuthorizationModelRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientReadAuthorizationModelOptions +func (_e *MockSdkClientReadAuthorizationModelRequestInterface_Expecter) Options(options interface{}) *MockSdkClientReadAuthorizationModelRequestInterface_Options_Call { + return &MockSdkClientReadAuthorizationModelRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_Options_Call) Run(run func(options client.ClientReadAuthorizationModelOptions)) *MockSdkClientReadAuthorizationModelRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientReadAuthorizationModelOptions)) + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_Options_Call) Return(_a0 client.SdkClientReadAuthorizationModelRequestInterface) *MockSdkClientReadAuthorizationModelRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelRequestInterface_Options_Call) RunAndReturn(run func(client.ClientReadAuthorizationModelOptions) client.SdkClientReadAuthorizationModelRequestInterface) *MockSdkClientReadAuthorizationModelRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientReadAuthorizationModelRequestInterface creates a new instance of MockSdkClientReadAuthorizationModelRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientReadAuthorizationModelRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientReadAuthorizationModelRequestInterface { + mock := &MockSdkClientReadAuthorizationModelRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientReadAuthorizationModelsRequestInterface.go b/fgax/mockery/mock_SdkClientReadAuthorizationModelsRequestInterface.go new file mode 100644 index 0000000..db5550f --- /dev/null +++ b/fgax/mockery/mock_SdkClientReadAuthorizationModelsRequestInterface.go @@ -0,0 +1,286 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientReadAuthorizationModelsRequestInterface is an autogenerated mock type for the SdkClientReadAuthorizationModelsRequestInterface type +type MockSdkClientReadAuthorizationModelsRequestInterface struct { + mock.Mock +} + +type MockSdkClientReadAuthorizationModelsRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientReadAuthorizationModelsRequestInterface) EXPECT() *MockSdkClientReadAuthorizationModelsRequestInterface_Expecter { + return &MockSdkClientReadAuthorizationModelsRequestInterface_Expecter{mock: &_m.Mock} +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientReadAuthorizationModelsRequestInterface) Execute() (*openfga.ReadAuthorizationModelsResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.ReadAuthorizationModelsResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.ReadAuthorizationModelsResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.ReadAuthorizationModelsResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadAuthorizationModelsResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientReadAuthorizationModelsRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientReadAuthorizationModelsRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientReadAuthorizationModelsRequestInterface_Expecter) Execute() *MockSdkClientReadAuthorizationModelsRequestInterface_Execute_Call { + return &MockSdkClientReadAuthorizationModelsRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_Execute_Call) Run(run func()) *MockSdkClientReadAuthorizationModelsRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_Execute_Call) Return(_a0 *openfga.ReadAuthorizationModelsResponse, _a1 error) *MockSdkClientReadAuthorizationModelsRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.ReadAuthorizationModelsResponse, error)) *MockSdkClientReadAuthorizationModelsRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientReadAuthorizationModelsRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelsRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientReadAuthorizationModelsRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientReadAuthorizationModelsRequestInterface_Expecter) GetContext() *MockSdkClientReadAuthorizationModelsRequestInterface_GetContext_Call { + return &MockSdkClientReadAuthorizationModelsRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientReadAuthorizationModelsRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientReadAuthorizationModelsRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientReadAuthorizationModelsRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientReadAuthorizationModelsRequestInterface) GetOptions() *client.ClientReadAuthorizationModelsOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientReadAuthorizationModelsOptions + if rf, ok := ret.Get(0).(func() *client.ClientReadAuthorizationModelsOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientReadAuthorizationModelsOptions) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelsRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientReadAuthorizationModelsRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientReadAuthorizationModelsRequestInterface_Expecter) GetOptions() *MockSdkClientReadAuthorizationModelsRequestInterface_GetOptions_Call { + return &MockSdkClientReadAuthorizationModelsRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientReadAuthorizationModelsRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_GetOptions_Call) Return(_a0 *client.ClientReadAuthorizationModelsOptions) *MockSdkClientReadAuthorizationModelsRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientReadAuthorizationModelsOptions) *MockSdkClientReadAuthorizationModelsRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientReadAuthorizationModelsRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelsRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientReadAuthorizationModelsRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientReadAuthorizationModelsRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientReadAuthorizationModelsRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientReadAuthorizationModelsRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientReadAuthorizationModelsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientReadAuthorizationModelsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientReadAuthorizationModelsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientReadAuthorizationModelsRequestInterface) Options(options client.ClientReadAuthorizationModelsOptions) client.SdkClientReadAuthorizationModelsRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientReadAuthorizationModelsRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientReadAuthorizationModelsOptions) client.SdkClientReadAuthorizationModelsRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadAuthorizationModelsRequestInterface) + } + } + + return r0 +} + +// MockSdkClientReadAuthorizationModelsRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientReadAuthorizationModelsRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientReadAuthorizationModelsOptions +func (_e *MockSdkClientReadAuthorizationModelsRequestInterface_Expecter) Options(options interface{}) *MockSdkClientReadAuthorizationModelsRequestInterface_Options_Call { + return &MockSdkClientReadAuthorizationModelsRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_Options_Call) Run(run func(options client.ClientReadAuthorizationModelsOptions)) *MockSdkClientReadAuthorizationModelsRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientReadAuthorizationModelsOptions)) + }) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_Options_Call) Return(_a0 client.SdkClientReadAuthorizationModelsRequestInterface) *MockSdkClientReadAuthorizationModelsRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadAuthorizationModelsRequestInterface_Options_Call) RunAndReturn(run func(client.ClientReadAuthorizationModelsOptions) client.SdkClientReadAuthorizationModelsRequestInterface) *MockSdkClientReadAuthorizationModelsRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientReadAuthorizationModelsRequestInterface creates a new instance of MockSdkClientReadAuthorizationModelsRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientReadAuthorizationModelsRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientReadAuthorizationModelsRequestInterface { + mock := &MockSdkClientReadAuthorizationModelsRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientReadChangesRequestInterface.go b/fgax/mockery/mock_SdkClientReadChangesRequestInterface.go new file mode 100644 index 0000000..6513301 --- /dev/null +++ b/fgax/mockery/mock_SdkClientReadChangesRequestInterface.go @@ -0,0 +1,381 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientReadChangesRequestInterface is an autogenerated mock type for the SdkClientReadChangesRequestInterface type +type MockSdkClientReadChangesRequestInterface struct { + mock.Mock +} + +type MockSdkClientReadChangesRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientReadChangesRequestInterface) EXPECT() *MockSdkClientReadChangesRequestInterface_Expecter { + return &MockSdkClientReadChangesRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientReadChangesRequestInterface) Body(body client.ClientReadChangesRequest) client.SdkClientReadChangesRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientReadChangesRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientReadChangesRequest) client.SdkClientReadChangesRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadChangesRequestInterface) + } + } + + return r0 +} + +// MockSdkClientReadChangesRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientReadChangesRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body client.ClientReadChangesRequest +func (_e *MockSdkClientReadChangesRequestInterface_Expecter) Body(body interface{}) *MockSdkClientReadChangesRequestInterface_Body_Call { + return &MockSdkClientReadChangesRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientReadChangesRequestInterface_Body_Call) Run(run func(body client.ClientReadChangesRequest)) *MockSdkClientReadChangesRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientReadChangesRequest)) + }) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_Body_Call) Return(_a0 client.SdkClientReadChangesRequestInterface) *MockSdkClientReadChangesRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_Body_Call) RunAndReturn(run func(client.ClientReadChangesRequest) client.SdkClientReadChangesRequestInterface) *MockSdkClientReadChangesRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientReadChangesRequestInterface) Execute() (*openfga.ReadChangesResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.ReadChangesResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.ReadChangesResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.ReadChangesResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadChangesResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientReadChangesRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientReadChangesRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientReadChangesRequestInterface_Expecter) Execute() *MockSdkClientReadChangesRequestInterface_Execute_Call { + return &MockSdkClientReadChangesRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientReadChangesRequestInterface_Execute_Call) Run(run func()) *MockSdkClientReadChangesRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_Execute_Call) Return(_a0 *openfga.ReadChangesResponse, _a1 error) *MockSdkClientReadChangesRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.ReadChangesResponse, error)) *MockSdkClientReadChangesRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientReadChangesRequestInterface) GetBody() *client.ClientReadChangesRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *client.ClientReadChangesRequest + if rf, ok := ret.Get(0).(func() *client.ClientReadChangesRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientReadChangesRequest) + } + } + + return r0 +} + +// MockSdkClientReadChangesRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientReadChangesRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientReadChangesRequestInterface_Expecter) GetBody() *MockSdkClientReadChangesRequestInterface_GetBody_Call { + return &MockSdkClientReadChangesRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientReadChangesRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetBody_Call) Return(_a0 *client.ClientReadChangesRequest) *MockSdkClientReadChangesRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetBody_Call) RunAndReturn(run func() *client.ClientReadChangesRequest) *MockSdkClientReadChangesRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientReadChangesRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientReadChangesRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientReadChangesRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientReadChangesRequestInterface_Expecter) GetContext() *MockSdkClientReadChangesRequestInterface_GetContext_Call { + return &MockSdkClientReadChangesRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientReadChangesRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientReadChangesRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientReadChangesRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientReadChangesRequestInterface) GetOptions() *client.ClientReadChangesOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientReadChangesOptions + if rf, ok := ret.Get(0).(func() *client.ClientReadChangesOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientReadChangesOptions) + } + } + + return r0 +} + +// MockSdkClientReadChangesRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientReadChangesRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientReadChangesRequestInterface_Expecter) GetOptions() *MockSdkClientReadChangesRequestInterface_GetOptions_Call { + return &MockSdkClientReadChangesRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientReadChangesRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetOptions_Call) Return(_a0 *client.ClientReadChangesOptions) *MockSdkClientReadChangesRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientReadChangesOptions) *MockSdkClientReadChangesRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientReadChangesRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientReadChangesRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientReadChangesRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientReadChangesRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientReadChangesRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientReadChangesRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientReadChangesRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientReadChangesRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientReadChangesRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientReadChangesRequestInterface) Options(options client.ClientReadChangesOptions) client.SdkClientReadChangesRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientReadChangesRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientReadChangesOptions) client.SdkClientReadChangesRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadChangesRequestInterface) + } + } + + return r0 +} + +// MockSdkClientReadChangesRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientReadChangesRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientReadChangesOptions +func (_e *MockSdkClientReadChangesRequestInterface_Expecter) Options(options interface{}) *MockSdkClientReadChangesRequestInterface_Options_Call { + return &MockSdkClientReadChangesRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientReadChangesRequestInterface_Options_Call) Run(run func(options client.ClientReadChangesOptions)) *MockSdkClientReadChangesRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientReadChangesOptions)) + }) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_Options_Call) Return(_a0 client.SdkClientReadChangesRequestInterface) *MockSdkClientReadChangesRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadChangesRequestInterface_Options_Call) RunAndReturn(run func(client.ClientReadChangesOptions) client.SdkClientReadChangesRequestInterface) *MockSdkClientReadChangesRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientReadChangesRequestInterface creates a new instance of MockSdkClientReadChangesRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientReadChangesRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientReadChangesRequestInterface { + mock := &MockSdkClientReadChangesRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientReadLatestAuthorizationModelRequestInterface.go b/fgax/mockery/mock_SdkClientReadLatestAuthorizationModelRequestInterface.go new file mode 100644 index 0000000..f7c3509 --- /dev/null +++ b/fgax/mockery/mock_SdkClientReadLatestAuthorizationModelRequestInterface.go @@ -0,0 +1,286 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientReadLatestAuthorizationModelRequestInterface is an autogenerated mock type for the SdkClientReadLatestAuthorizationModelRequestInterface type +type MockSdkClientReadLatestAuthorizationModelRequestInterface struct { + mock.Mock +} + +type MockSdkClientReadLatestAuthorizationModelRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientReadLatestAuthorizationModelRequestInterface) EXPECT() *MockSdkClientReadLatestAuthorizationModelRequestInterface_Expecter { + return &MockSdkClientReadLatestAuthorizationModelRequestInterface_Expecter{mock: &_m.Mock} +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientReadLatestAuthorizationModelRequestInterface) Execute() (*openfga.ReadAuthorizationModelResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.ReadAuthorizationModelResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.ReadAuthorizationModelResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.ReadAuthorizationModelResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadAuthorizationModelResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientReadLatestAuthorizationModelRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientReadLatestAuthorizationModelRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientReadLatestAuthorizationModelRequestInterface_Expecter) Execute() *MockSdkClientReadLatestAuthorizationModelRequestInterface_Execute_Call { + return &MockSdkClientReadLatestAuthorizationModelRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_Execute_Call) Run(run func()) *MockSdkClientReadLatestAuthorizationModelRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_Execute_Call) Return(_a0 *openfga.ReadAuthorizationModelResponse, _a1 error) *MockSdkClientReadLatestAuthorizationModelRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.ReadAuthorizationModelResponse, error)) *MockSdkClientReadLatestAuthorizationModelRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientReadLatestAuthorizationModelRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientReadLatestAuthorizationModelRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientReadLatestAuthorizationModelRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientReadLatestAuthorizationModelRequestInterface_Expecter) GetContext() *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetContext_Call { + return &MockSdkClientReadLatestAuthorizationModelRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientReadLatestAuthorizationModelRequestInterface) GetOptions() *client.ClientReadLatestAuthorizationModelOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientReadLatestAuthorizationModelOptions + if rf, ok := ret.Get(0).(func() *client.ClientReadLatestAuthorizationModelOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientReadLatestAuthorizationModelOptions) + } + } + + return r0 +} + +// MockSdkClientReadLatestAuthorizationModelRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientReadLatestAuthorizationModelRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientReadLatestAuthorizationModelRequestInterface_Expecter) GetOptions() *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetOptions_Call { + return &MockSdkClientReadLatestAuthorizationModelRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetOptions_Call) Return(_a0 *client.ClientReadLatestAuthorizationModelOptions) *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientReadLatestAuthorizationModelOptions) *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientReadLatestAuthorizationModelRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientReadLatestAuthorizationModelRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientReadLatestAuthorizationModelRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientReadLatestAuthorizationModelRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientReadLatestAuthorizationModelRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientReadLatestAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientReadLatestAuthorizationModelRequestInterface) Options(options client.ClientReadLatestAuthorizationModelOptions) client.SdkClientReadLatestAuthorizationModelRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientReadLatestAuthorizationModelRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientReadLatestAuthorizationModelOptions) client.SdkClientReadLatestAuthorizationModelRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadLatestAuthorizationModelRequestInterface) + } + } + + return r0 +} + +// MockSdkClientReadLatestAuthorizationModelRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientReadLatestAuthorizationModelRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientReadLatestAuthorizationModelOptions +func (_e *MockSdkClientReadLatestAuthorizationModelRequestInterface_Expecter) Options(options interface{}) *MockSdkClientReadLatestAuthorizationModelRequestInterface_Options_Call { + return &MockSdkClientReadLatestAuthorizationModelRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_Options_Call) Run(run func(options client.ClientReadLatestAuthorizationModelOptions)) *MockSdkClientReadLatestAuthorizationModelRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientReadLatestAuthorizationModelOptions)) + }) + return _c +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_Options_Call) Return(_a0 client.SdkClientReadLatestAuthorizationModelRequestInterface) *MockSdkClientReadLatestAuthorizationModelRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadLatestAuthorizationModelRequestInterface_Options_Call) RunAndReturn(run func(client.ClientReadLatestAuthorizationModelOptions) client.SdkClientReadLatestAuthorizationModelRequestInterface) *MockSdkClientReadLatestAuthorizationModelRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientReadLatestAuthorizationModelRequestInterface creates a new instance of MockSdkClientReadLatestAuthorizationModelRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientReadLatestAuthorizationModelRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientReadLatestAuthorizationModelRequestInterface { + mock := &MockSdkClientReadLatestAuthorizationModelRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientReadRequestInterface.go b/fgax/mockery/mock_SdkClientReadRequestInterface.go new file mode 100644 index 0000000..2c1ff40 --- /dev/null +++ b/fgax/mockery/mock_SdkClientReadRequestInterface.go @@ -0,0 +1,381 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientReadRequestInterface is an autogenerated mock type for the SdkClientReadRequestInterface type +type MockSdkClientReadRequestInterface struct { + mock.Mock +} + +type MockSdkClientReadRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientReadRequestInterface) EXPECT() *MockSdkClientReadRequestInterface_Expecter { + return &MockSdkClientReadRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientReadRequestInterface) Body(body client.ClientReadRequest) client.SdkClientReadRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientReadRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientReadRequest) client.SdkClientReadRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadRequestInterface) + } + } + + return r0 +} + +// MockSdkClientReadRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientReadRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body client.ClientReadRequest +func (_e *MockSdkClientReadRequestInterface_Expecter) Body(body interface{}) *MockSdkClientReadRequestInterface_Body_Call { + return &MockSdkClientReadRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientReadRequestInterface_Body_Call) Run(run func(body client.ClientReadRequest)) *MockSdkClientReadRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientReadRequest)) + }) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_Body_Call) Return(_a0 client.SdkClientReadRequestInterface) *MockSdkClientReadRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_Body_Call) RunAndReturn(run func(client.ClientReadRequest) client.SdkClientReadRequestInterface) *MockSdkClientReadRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientReadRequestInterface) Execute() (*openfga.ReadResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.ReadResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.ReadResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.ReadResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.ReadResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientReadRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientReadRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientReadRequestInterface_Expecter) Execute() *MockSdkClientReadRequestInterface_Execute_Call { + return &MockSdkClientReadRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientReadRequestInterface_Execute_Call) Run(run func()) *MockSdkClientReadRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_Execute_Call) Return(_a0 *openfga.ReadResponse, _a1 error) *MockSdkClientReadRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.ReadResponse, error)) *MockSdkClientReadRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientReadRequestInterface) GetBody() *client.ClientReadRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *client.ClientReadRequest + if rf, ok := ret.Get(0).(func() *client.ClientReadRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientReadRequest) + } + } + + return r0 +} + +// MockSdkClientReadRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientReadRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientReadRequestInterface_Expecter) GetBody() *MockSdkClientReadRequestInterface_GetBody_Call { + return &MockSdkClientReadRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientReadRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientReadRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_GetBody_Call) Return(_a0 *client.ClientReadRequest) *MockSdkClientReadRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_GetBody_Call) RunAndReturn(run func() *client.ClientReadRequest) *MockSdkClientReadRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientReadRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientReadRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientReadRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientReadRequestInterface_Expecter) GetContext() *MockSdkClientReadRequestInterface_GetContext_Call { + return &MockSdkClientReadRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientReadRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientReadRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientReadRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientReadRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientReadRequestInterface) GetOptions() *client.ClientReadOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientReadOptions + if rf, ok := ret.Get(0).(func() *client.ClientReadOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientReadOptions) + } + } + + return r0 +} + +// MockSdkClientReadRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientReadRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientReadRequestInterface_Expecter) GetOptions() *MockSdkClientReadRequestInterface_GetOptions_Call { + return &MockSdkClientReadRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientReadRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientReadRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_GetOptions_Call) Return(_a0 *client.ClientReadOptions) *MockSdkClientReadRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientReadOptions) *MockSdkClientReadRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientReadRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientReadRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientReadRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientReadRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientReadRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientReadRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientReadRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientReadRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientReadRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientReadRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientReadRequestInterface) Options(options client.ClientReadOptions) client.SdkClientReadRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientReadRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientReadOptions) client.SdkClientReadRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientReadRequestInterface) + } + } + + return r0 +} + +// MockSdkClientReadRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientReadRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientReadOptions +func (_e *MockSdkClientReadRequestInterface_Expecter) Options(options interface{}) *MockSdkClientReadRequestInterface_Options_Call { + return &MockSdkClientReadRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientReadRequestInterface_Options_Call) Run(run func(options client.ClientReadOptions)) *MockSdkClientReadRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientReadOptions)) + }) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_Options_Call) Return(_a0 client.SdkClientReadRequestInterface) *MockSdkClientReadRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientReadRequestInterface_Options_Call) RunAndReturn(run func(client.ClientReadOptions) client.SdkClientReadRequestInterface) *MockSdkClientReadRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientReadRequestInterface creates a new instance of MockSdkClientReadRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientReadRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientReadRequestInterface { + mock := &MockSdkClientReadRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientWriteAssertionsRequestInterface.go b/fgax/mockery/mock_SdkClientWriteAssertionsRequestInterface.go new file mode 100644 index 0000000..92ae716 --- /dev/null +++ b/fgax/mockery/mock_SdkClientWriteAssertionsRequestInterface.go @@ -0,0 +1,426 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" +) + +// MockSdkClientWriteAssertionsRequestInterface is an autogenerated mock type for the SdkClientWriteAssertionsRequestInterface type +type MockSdkClientWriteAssertionsRequestInterface struct { + mock.Mock +} + +type MockSdkClientWriteAssertionsRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientWriteAssertionsRequestInterface) EXPECT() *MockSdkClientWriteAssertionsRequestInterface_Expecter { + return &MockSdkClientWriteAssertionsRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientWriteAssertionsRequestInterface) Body(body []client.ClientAssertion) client.SdkClientWriteAssertionsRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientWriteAssertionsRequestInterface + if rf, ok := ret.Get(0).(func([]client.ClientAssertion) client.SdkClientWriteAssertionsRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteAssertionsRequestInterface) + } + } + + return r0 +} + +// MockSdkClientWriteAssertionsRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientWriteAssertionsRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body []client.ClientAssertion +func (_e *MockSdkClientWriteAssertionsRequestInterface_Expecter) Body(body interface{}) *MockSdkClientWriteAssertionsRequestInterface_Body_Call { + return &MockSdkClientWriteAssertionsRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_Body_Call) Run(run func(body []client.ClientAssertion)) *MockSdkClientWriteAssertionsRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].([]client.ClientAssertion)) + }) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_Body_Call) Return(_a0 client.SdkClientWriteAssertionsRequestInterface) *MockSdkClientWriteAssertionsRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_Body_Call) RunAndReturn(run func([]client.ClientAssertion) client.SdkClientWriteAssertionsRequestInterface) *MockSdkClientWriteAssertionsRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientWriteAssertionsRequestInterface) Execute() (*client.ClientWriteAssertionsResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *client.ClientWriteAssertionsResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*client.ClientWriteAssertionsResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *client.ClientWriteAssertionsResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteAssertionsResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientWriteAssertionsRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientWriteAssertionsRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientWriteAssertionsRequestInterface_Expecter) Execute() *MockSdkClientWriteAssertionsRequestInterface_Execute_Call { + return &MockSdkClientWriteAssertionsRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_Execute_Call) Run(run func()) *MockSdkClientWriteAssertionsRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_Execute_Call) Return(_a0 *client.ClientWriteAssertionsResponse, _a1 error) *MockSdkClientWriteAssertionsRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_Execute_Call) RunAndReturn(run func() (*client.ClientWriteAssertionsResponse, error)) *MockSdkClientWriteAssertionsRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetAuthorizationModelIdOverride provides a mock function with given fields: +func (_m *MockSdkClientWriteAssertionsRequestInterface) GetAuthorizationModelIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetAuthorizationModelIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientWriteAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizationModelIdOverride' +type MockSdkClientWriteAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call struct { + *mock.Call +} + +// GetAuthorizationModelIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientWriteAssertionsRequestInterface_Expecter) GetAuthorizationModelIdOverride() *MockSdkClientWriteAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call { + return &MockSdkClientWriteAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call{Call: _e.mock.On("GetAuthorizationModelIdOverride")} +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call) Run(run func()) *MockSdkClientWriteAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call) Return(_a0 *string) *MockSdkClientWriteAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientWriteAssertionsRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientWriteAssertionsRequestInterface) GetBody() *[]client.ClientAssertion { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *[]client.ClientAssertion + if rf, ok := ret.Get(0).(func() *[]client.ClientAssertion); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*[]client.ClientAssertion) + } + } + + return r0 +} + +// MockSdkClientWriteAssertionsRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientWriteAssertionsRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientWriteAssertionsRequestInterface_Expecter) GetBody() *MockSdkClientWriteAssertionsRequestInterface_GetBody_Call { + return &MockSdkClientWriteAssertionsRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientWriteAssertionsRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetBody_Call) Return(_a0 *[]client.ClientAssertion) *MockSdkClientWriteAssertionsRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetBody_Call) RunAndReturn(run func() *[]client.ClientAssertion) *MockSdkClientWriteAssertionsRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientWriteAssertionsRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientWriteAssertionsRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientWriteAssertionsRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientWriteAssertionsRequestInterface_Expecter) GetContext() *MockSdkClientWriteAssertionsRequestInterface_GetContext_Call { + return &MockSdkClientWriteAssertionsRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientWriteAssertionsRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientWriteAssertionsRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientWriteAssertionsRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientWriteAssertionsRequestInterface) GetOptions() *client.ClientWriteAssertionsOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientWriteAssertionsOptions + if rf, ok := ret.Get(0).(func() *client.ClientWriteAssertionsOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteAssertionsOptions) + } + } + + return r0 +} + +// MockSdkClientWriteAssertionsRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientWriteAssertionsRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientWriteAssertionsRequestInterface_Expecter) GetOptions() *MockSdkClientWriteAssertionsRequestInterface_GetOptions_Call { + return &MockSdkClientWriteAssertionsRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientWriteAssertionsRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetOptions_Call) Return(_a0 *client.ClientWriteAssertionsOptions) *MockSdkClientWriteAssertionsRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientWriteAssertionsOptions) *MockSdkClientWriteAssertionsRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientWriteAssertionsRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientWriteAssertionsRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientWriteAssertionsRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientWriteAssertionsRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientWriteAssertionsRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientWriteAssertionsRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientWriteAssertionsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientWriteAssertionsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientWriteAssertionsRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientWriteAssertionsRequestInterface) Options(options client.ClientWriteAssertionsOptions) client.SdkClientWriteAssertionsRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientWriteAssertionsRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientWriteAssertionsOptions) client.SdkClientWriteAssertionsRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteAssertionsRequestInterface) + } + } + + return r0 +} + +// MockSdkClientWriteAssertionsRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientWriteAssertionsRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientWriteAssertionsOptions +func (_e *MockSdkClientWriteAssertionsRequestInterface_Expecter) Options(options interface{}) *MockSdkClientWriteAssertionsRequestInterface_Options_Call { + return &MockSdkClientWriteAssertionsRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_Options_Call) Run(run func(options client.ClientWriteAssertionsOptions)) *MockSdkClientWriteAssertionsRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientWriteAssertionsOptions)) + }) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_Options_Call) Return(_a0 client.SdkClientWriteAssertionsRequestInterface) *MockSdkClientWriteAssertionsRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAssertionsRequestInterface_Options_Call) RunAndReturn(run func(client.ClientWriteAssertionsOptions) client.SdkClientWriteAssertionsRequestInterface) *MockSdkClientWriteAssertionsRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientWriteAssertionsRequestInterface creates a new instance of MockSdkClientWriteAssertionsRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientWriteAssertionsRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientWriteAssertionsRequestInterface { + mock := &MockSdkClientWriteAssertionsRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientWriteAuthorizationModelRequestInterface.go b/fgax/mockery/mock_SdkClientWriteAuthorizationModelRequestInterface.go new file mode 100644 index 0000000..3e9ccf8 --- /dev/null +++ b/fgax/mockery/mock_SdkClientWriteAuthorizationModelRequestInterface.go @@ -0,0 +1,381 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientWriteAuthorizationModelRequestInterface is an autogenerated mock type for the SdkClientWriteAuthorizationModelRequestInterface type +type MockSdkClientWriteAuthorizationModelRequestInterface struct { + mock.Mock +} + +type MockSdkClientWriteAuthorizationModelRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientWriteAuthorizationModelRequestInterface) EXPECT() *MockSdkClientWriteAuthorizationModelRequestInterface_Expecter { + return &MockSdkClientWriteAuthorizationModelRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientWriteAuthorizationModelRequestInterface) Body(body openfga.WriteAuthorizationModelRequest) client.SdkClientWriteAuthorizationModelRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientWriteAuthorizationModelRequestInterface + if rf, ok := ret.Get(0).(func(openfga.WriteAuthorizationModelRequest) client.SdkClientWriteAuthorizationModelRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteAuthorizationModelRequestInterface) + } + } + + return r0 +} + +// MockSdkClientWriteAuthorizationModelRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientWriteAuthorizationModelRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body openfga.WriteAuthorizationModelRequest +func (_e *MockSdkClientWriteAuthorizationModelRequestInterface_Expecter) Body(body interface{}) *MockSdkClientWriteAuthorizationModelRequestInterface_Body_Call { + return &MockSdkClientWriteAuthorizationModelRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_Body_Call) Run(run func(body openfga.WriteAuthorizationModelRequest)) *MockSdkClientWriteAuthorizationModelRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(openfga.WriteAuthorizationModelRequest)) + }) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_Body_Call) Return(_a0 client.SdkClientWriteAuthorizationModelRequestInterface) *MockSdkClientWriteAuthorizationModelRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_Body_Call) RunAndReturn(run func(openfga.WriteAuthorizationModelRequest) client.SdkClientWriteAuthorizationModelRequestInterface) *MockSdkClientWriteAuthorizationModelRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientWriteAuthorizationModelRequestInterface) Execute() (*openfga.WriteAuthorizationModelResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *openfga.WriteAuthorizationModelResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*openfga.WriteAuthorizationModelResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *openfga.WriteAuthorizationModelResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.WriteAuthorizationModelResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientWriteAuthorizationModelRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientWriteAuthorizationModelRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientWriteAuthorizationModelRequestInterface_Expecter) Execute() *MockSdkClientWriteAuthorizationModelRequestInterface_Execute_Call { + return &MockSdkClientWriteAuthorizationModelRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_Execute_Call) Run(run func()) *MockSdkClientWriteAuthorizationModelRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_Execute_Call) Return(_a0 *openfga.WriteAuthorizationModelResponse, _a1 error) *MockSdkClientWriteAuthorizationModelRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_Execute_Call) RunAndReturn(run func() (*openfga.WriteAuthorizationModelResponse, error)) *MockSdkClientWriteAuthorizationModelRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientWriteAuthorizationModelRequestInterface) GetBody() *openfga.WriteAuthorizationModelRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *openfga.WriteAuthorizationModelRequest + if rf, ok := ret.Get(0).(func() *openfga.WriteAuthorizationModelRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*openfga.WriteAuthorizationModelRequest) + } + } + + return r0 +} + +// MockSdkClientWriteAuthorizationModelRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientWriteAuthorizationModelRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientWriteAuthorizationModelRequestInterface_Expecter) GetBody() *MockSdkClientWriteAuthorizationModelRequestInterface_GetBody_Call { + return &MockSdkClientWriteAuthorizationModelRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientWriteAuthorizationModelRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetBody_Call) Return(_a0 *openfga.WriteAuthorizationModelRequest) *MockSdkClientWriteAuthorizationModelRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetBody_Call) RunAndReturn(run func() *openfga.WriteAuthorizationModelRequest) *MockSdkClientWriteAuthorizationModelRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientWriteAuthorizationModelRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientWriteAuthorizationModelRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientWriteAuthorizationModelRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientWriteAuthorizationModelRequestInterface_Expecter) GetContext() *MockSdkClientWriteAuthorizationModelRequestInterface_GetContext_Call { + return &MockSdkClientWriteAuthorizationModelRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientWriteAuthorizationModelRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientWriteAuthorizationModelRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientWriteAuthorizationModelRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientWriteAuthorizationModelRequestInterface) GetOptions() *client.ClientWriteAuthorizationModelOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientWriteAuthorizationModelOptions + if rf, ok := ret.Get(0).(func() *client.ClientWriteAuthorizationModelOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteAuthorizationModelOptions) + } + } + + return r0 +} + +// MockSdkClientWriteAuthorizationModelRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientWriteAuthorizationModelRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientWriteAuthorizationModelRequestInterface_Expecter) GetOptions() *MockSdkClientWriteAuthorizationModelRequestInterface_GetOptions_Call { + return &MockSdkClientWriteAuthorizationModelRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientWriteAuthorizationModelRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetOptions_Call) Return(_a0 *client.ClientWriteAuthorizationModelOptions) *MockSdkClientWriteAuthorizationModelRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientWriteAuthorizationModelOptions) *MockSdkClientWriteAuthorizationModelRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientWriteAuthorizationModelRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientWriteAuthorizationModelRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientWriteAuthorizationModelRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientWriteAuthorizationModelRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientWriteAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientWriteAuthorizationModelRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientWriteAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientWriteAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientWriteAuthorizationModelRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientWriteAuthorizationModelRequestInterface) Options(options client.ClientWriteAuthorizationModelOptions) client.SdkClientWriteAuthorizationModelRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientWriteAuthorizationModelRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientWriteAuthorizationModelOptions) client.SdkClientWriteAuthorizationModelRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteAuthorizationModelRequestInterface) + } + } + + return r0 +} + +// MockSdkClientWriteAuthorizationModelRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientWriteAuthorizationModelRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientWriteAuthorizationModelOptions +func (_e *MockSdkClientWriteAuthorizationModelRequestInterface_Expecter) Options(options interface{}) *MockSdkClientWriteAuthorizationModelRequestInterface_Options_Call { + return &MockSdkClientWriteAuthorizationModelRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_Options_Call) Run(run func(options client.ClientWriteAuthorizationModelOptions)) *MockSdkClientWriteAuthorizationModelRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientWriteAuthorizationModelOptions)) + }) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_Options_Call) Return(_a0 client.SdkClientWriteAuthorizationModelRequestInterface) *MockSdkClientWriteAuthorizationModelRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteAuthorizationModelRequestInterface_Options_Call) RunAndReturn(run func(client.ClientWriteAuthorizationModelOptions) client.SdkClientWriteAuthorizationModelRequestInterface) *MockSdkClientWriteAuthorizationModelRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientWriteAuthorizationModelRequestInterface creates a new instance of MockSdkClientWriteAuthorizationModelRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientWriteAuthorizationModelRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientWriteAuthorizationModelRequestInterface { + mock := &MockSdkClientWriteAuthorizationModelRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientWriteRequestInterface.go b/fgax/mockery/mock_SdkClientWriteRequestInterface.go new file mode 100644 index 0000000..b1ad2c9 --- /dev/null +++ b/fgax/mockery/mock_SdkClientWriteRequestInterface.go @@ -0,0 +1,426 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" +) + +// MockSdkClientWriteRequestInterface is an autogenerated mock type for the SdkClientWriteRequestInterface type +type MockSdkClientWriteRequestInterface struct { + mock.Mock +} + +type MockSdkClientWriteRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientWriteRequestInterface) EXPECT() *MockSdkClientWriteRequestInterface_Expecter { + return &MockSdkClientWriteRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientWriteRequestInterface) Body(body client.ClientWriteRequest) client.SdkClientWriteRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientWriteRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientWriteRequest) client.SdkClientWriteRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteRequestInterface) + } + } + + return r0 +} + +// MockSdkClientWriteRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientWriteRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body client.ClientWriteRequest +func (_e *MockSdkClientWriteRequestInterface_Expecter) Body(body interface{}) *MockSdkClientWriteRequestInterface_Body_Call { + return &MockSdkClientWriteRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientWriteRequestInterface_Body_Call) Run(run func(body client.ClientWriteRequest)) *MockSdkClientWriteRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientWriteRequest)) + }) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_Body_Call) Return(_a0 client.SdkClientWriteRequestInterface) *MockSdkClientWriteRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_Body_Call) RunAndReturn(run func(client.ClientWriteRequest) client.SdkClientWriteRequestInterface) *MockSdkClientWriteRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientWriteRequestInterface) Execute() (*client.ClientWriteResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *client.ClientWriteResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*client.ClientWriteResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *client.ClientWriteResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientWriteRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientWriteRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientWriteRequestInterface_Expecter) Execute() *MockSdkClientWriteRequestInterface_Execute_Call { + return &MockSdkClientWriteRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientWriteRequestInterface_Execute_Call) Run(run func()) *MockSdkClientWriteRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_Execute_Call) Return(_a0 *client.ClientWriteResponse, _a1 error) *MockSdkClientWriteRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_Execute_Call) RunAndReturn(run func() (*client.ClientWriteResponse, error)) *MockSdkClientWriteRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetAuthorizationModelIdOverride provides a mock function with given fields: +func (_m *MockSdkClientWriteRequestInterface) GetAuthorizationModelIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetAuthorizationModelIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientWriteRequestInterface_GetAuthorizationModelIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAuthorizationModelIdOverride' +type MockSdkClientWriteRequestInterface_GetAuthorizationModelIdOverride_Call struct { + *mock.Call +} + +// GetAuthorizationModelIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientWriteRequestInterface_Expecter) GetAuthorizationModelIdOverride() *MockSdkClientWriteRequestInterface_GetAuthorizationModelIdOverride_Call { + return &MockSdkClientWriteRequestInterface_GetAuthorizationModelIdOverride_Call{Call: _e.mock.On("GetAuthorizationModelIdOverride")} +} + +func (_c *MockSdkClientWriteRequestInterface_GetAuthorizationModelIdOverride_Call) Run(run func()) *MockSdkClientWriteRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_GetAuthorizationModelIdOverride_Call) Return(_a0 *string) *MockSdkClientWriteRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_GetAuthorizationModelIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientWriteRequestInterface_GetAuthorizationModelIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientWriteRequestInterface) GetBody() *client.ClientWriteRequest { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *client.ClientWriteRequest + if rf, ok := ret.Get(0).(func() *client.ClientWriteRequest); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteRequest) + } + } + + return r0 +} + +// MockSdkClientWriteRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientWriteRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientWriteRequestInterface_Expecter) GetBody() *MockSdkClientWriteRequestInterface_GetBody_Call { + return &MockSdkClientWriteRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientWriteRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientWriteRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_GetBody_Call) Return(_a0 *client.ClientWriteRequest) *MockSdkClientWriteRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_GetBody_Call) RunAndReturn(run func() *client.ClientWriteRequest) *MockSdkClientWriteRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientWriteRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientWriteRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientWriteRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientWriteRequestInterface_Expecter) GetContext() *MockSdkClientWriteRequestInterface_GetContext_Call { + return &MockSdkClientWriteRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientWriteRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientWriteRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientWriteRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientWriteRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientWriteRequestInterface) GetOptions() *client.ClientWriteOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientWriteOptions + if rf, ok := ret.Get(0).(func() *client.ClientWriteOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteOptions) + } + } + + return r0 +} + +// MockSdkClientWriteRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientWriteRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientWriteRequestInterface_Expecter) GetOptions() *MockSdkClientWriteRequestInterface_GetOptions_Call { + return &MockSdkClientWriteRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientWriteRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientWriteRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_GetOptions_Call) Return(_a0 *client.ClientWriteOptions) *MockSdkClientWriteRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientWriteOptions) *MockSdkClientWriteRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// GetStoreIdOverride provides a mock function with given fields: +func (_m *MockSdkClientWriteRequestInterface) GetStoreIdOverride() *string { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetStoreIdOverride") + } + + var r0 *string + if rf, ok := ret.Get(0).(func() *string); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*string) + } + } + + return r0 +} + +// MockSdkClientWriteRequestInterface_GetStoreIdOverride_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStoreIdOverride' +type MockSdkClientWriteRequestInterface_GetStoreIdOverride_Call struct { + *mock.Call +} + +// GetStoreIdOverride is a helper method to define mock.On call +func (_e *MockSdkClientWriteRequestInterface_Expecter) GetStoreIdOverride() *MockSdkClientWriteRequestInterface_GetStoreIdOverride_Call { + return &MockSdkClientWriteRequestInterface_GetStoreIdOverride_Call{Call: _e.mock.On("GetStoreIdOverride")} +} + +func (_c *MockSdkClientWriteRequestInterface_GetStoreIdOverride_Call) Run(run func()) *MockSdkClientWriteRequestInterface_GetStoreIdOverride_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_GetStoreIdOverride_Call) Return(_a0 *string) *MockSdkClientWriteRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_GetStoreIdOverride_Call) RunAndReturn(run func() *string) *MockSdkClientWriteRequestInterface_GetStoreIdOverride_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientWriteRequestInterface) Options(options client.ClientWriteOptions) client.SdkClientWriteRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientWriteRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientWriteOptions) client.SdkClientWriteRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteRequestInterface) + } + } + + return r0 +} + +// MockSdkClientWriteRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientWriteRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientWriteOptions +func (_e *MockSdkClientWriteRequestInterface_Expecter) Options(options interface{}) *MockSdkClientWriteRequestInterface_Options_Call { + return &MockSdkClientWriteRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientWriteRequestInterface_Options_Call) Run(run func(options client.ClientWriteOptions)) *MockSdkClientWriteRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientWriteOptions)) + }) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_Options_Call) Return(_a0 client.SdkClientWriteRequestInterface) *MockSdkClientWriteRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteRequestInterface_Options_Call) RunAndReturn(run func(client.ClientWriteOptions) client.SdkClientWriteRequestInterface) *MockSdkClientWriteRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientWriteRequestInterface creates a new instance of MockSdkClientWriteRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientWriteRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientWriteRequestInterface { + mock := &MockSdkClientWriteRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/mockery/mock_SdkClientWriteTuplesRequestInterface.go b/fgax/mockery/mock_SdkClientWriteTuplesRequestInterface.go new file mode 100644 index 0000000..5848414 --- /dev/null +++ b/fgax/mockery/mock_SdkClientWriteTuplesRequestInterface.go @@ -0,0 +1,334 @@ +// Code generated by mockery. DO NOT EDIT. + +package client + +import ( + context "context" + + client "github.com/openfga/go-sdk/client" + + mock "github.com/stretchr/testify/mock" + + openfga "github.com/openfga/go-sdk" +) + +// MockSdkClientWriteTuplesRequestInterface is an autogenerated mock type for the SdkClientWriteTuplesRequestInterface type +type MockSdkClientWriteTuplesRequestInterface struct { + mock.Mock +} + +type MockSdkClientWriteTuplesRequestInterface_Expecter struct { + mock *mock.Mock +} + +func (_m *MockSdkClientWriteTuplesRequestInterface) EXPECT() *MockSdkClientWriteTuplesRequestInterface_Expecter { + return &MockSdkClientWriteTuplesRequestInterface_Expecter{mock: &_m.Mock} +} + +// Body provides a mock function with given fields: body +func (_m *MockSdkClientWriteTuplesRequestInterface) Body(body []openfga.TupleKey) client.SdkClientWriteTuplesRequestInterface { + ret := _m.Called(body) + + if len(ret) == 0 { + panic("no return value specified for Body") + } + + var r0 client.SdkClientWriteTuplesRequestInterface + if rf, ok := ret.Get(0).(func([]openfga.TupleKey) client.SdkClientWriteTuplesRequestInterface); ok { + r0 = rf(body) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteTuplesRequestInterface) + } + } + + return r0 +} + +// MockSdkClientWriteTuplesRequestInterface_Body_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Body' +type MockSdkClientWriteTuplesRequestInterface_Body_Call struct { + *mock.Call +} + +// Body is a helper method to define mock.On call +// - body []openfga.TupleKey +func (_e *MockSdkClientWriteTuplesRequestInterface_Expecter) Body(body interface{}) *MockSdkClientWriteTuplesRequestInterface_Body_Call { + return &MockSdkClientWriteTuplesRequestInterface_Body_Call{Call: _e.mock.On("Body", body)} +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_Body_Call) Run(run func(body []openfga.TupleKey)) *MockSdkClientWriteTuplesRequestInterface_Body_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].([]openfga.TupleKey)) + }) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_Body_Call) Return(_a0 client.SdkClientWriteTuplesRequestInterface) *MockSdkClientWriteTuplesRequestInterface_Body_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_Body_Call) RunAndReturn(run func([]openfga.TupleKey) client.SdkClientWriteTuplesRequestInterface) *MockSdkClientWriteTuplesRequestInterface_Body_Call { + _c.Call.Return(run) + return _c +} + +// Execute provides a mock function with given fields: +func (_m *MockSdkClientWriteTuplesRequestInterface) Execute() (*client.ClientWriteResponse, error) { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for Execute") + } + + var r0 *client.ClientWriteResponse + var r1 error + if rf, ok := ret.Get(0).(func() (*client.ClientWriteResponse, error)); ok { + return rf() + } + if rf, ok := ret.Get(0).(func() *client.ClientWriteResponse); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteResponse) + } + } + + if rf, ok := ret.Get(1).(func() error); ok { + r1 = rf() + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// MockSdkClientWriteTuplesRequestInterface_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute' +type MockSdkClientWriteTuplesRequestInterface_Execute_Call struct { + *mock.Call +} + +// Execute is a helper method to define mock.On call +func (_e *MockSdkClientWriteTuplesRequestInterface_Expecter) Execute() *MockSdkClientWriteTuplesRequestInterface_Execute_Call { + return &MockSdkClientWriteTuplesRequestInterface_Execute_Call{Call: _e.mock.On("Execute")} +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_Execute_Call) Run(run func()) *MockSdkClientWriteTuplesRequestInterface_Execute_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_Execute_Call) Return(_a0 *client.ClientWriteResponse, _a1 error) *MockSdkClientWriteTuplesRequestInterface_Execute_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_Execute_Call) RunAndReturn(run func() (*client.ClientWriteResponse, error)) *MockSdkClientWriteTuplesRequestInterface_Execute_Call { + _c.Call.Return(run) + return _c +} + +// GetBody provides a mock function with given fields: +func (_m *MockSdkClientWriteTuplesRequestInterface) GetBody() *[]openfga.TupleKey { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetBody") + } + + var r0 *[]openfga.TupleKey + if rf, ok := ret.Get(0).(func() *[]openfga.TupleKey); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*[]openfga.TupleKey) + } + } + + return r0 +} + +// MockSdkClientWriteTuplesRequestInterface_GetBody_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBody' +type MockSdkClientWriteTuplesRequestInterface_GetBody_Call struct { + *mock.Call +} + +// GetBody is a helper method to define mock.On call +func (_e *MockSdkClientWriteTuplesRequestInterface_Expecter) GetBody() *MockSdkClientWriteTuplesRequestInterface_GetBody_Call { + return &MockSdkClientWriteTuplesRequestInterface_GetBody_Call{Call: _e.mock.On("GetBody")} +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_GetBody_Call) Run(run func()) *MockSdkClientWriteTuplesRequestInterface_GetBody_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_GetBody_Call) Return(_a0 *[]openfga.TupleKey) *MockSdkClientWriteTuplesRequestInterface_GetBody_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_GetBody_Call) RunAndReturn(run func() *[]openfga.TupleKey) *MockSdkClientWriteTuplesRequestInterface_GetBody_Call { + _c.Call.Return(run) + return _c +} + +// GetContext provides a mock function with given fields: +func (_m *MockSdkClientWriteTuplesRequestInterface) GetContext() context.Context { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetContext") + } + + var r0 context.Context + if rf, ok := ret.Get(0).(func() context.Context); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(context.Context) + } + } + + return r0 +} + +// MockSdkClientWriteTuplesRequestInterface_GetContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetContext' +type MockSdkClientWriteTuplesRequestInterface_GetContext_Call struct { + *mock.Call +} + +// GetContext is a helper method to define mock.On call +func (_e *MockSdkClientWriteTuplesRequestInterface_Expecter) GetContext() *MockSdkClientWriteTuplesRequestInterface_GetContext_Call { + return &MockSdkClientWriteTuplesRequestInterface_GetContext_Call{Call: _e.mock.On("GetContext")} +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_GetContext_Call) Run(run func()) *MockSdkClientWriteTuplesRequestInterface_GetContext_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_GetContext_Call) Return(_a0 context.Context) *MockSdkClientWriteTuplesRequestInterface_GetContext_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_GetContext_Call) RunAndReturn(run func() context.Context) *MockSdkClientWriteTuplesRequestInterface_GetContext_Call { + _c.Call.Return(run) + return _c +} + +// GetOptions provides a mock function with given fields: +func (_m *MockSdkClientWriteTuplesRequestInterface) GetOptions() *client.ClientWriteOptions { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for GetOptions") + } + + var r0 *client.ClientWriteOptions + if rf, ok := ret.Get(0).(func() *client.ClientWriteOptions); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*client.ClientWriteOptions) + } + } + + return r0 +} + +// MockSdkClientWriteTuplesRequestInterface_GetOptions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetOptions' +type MockSdkClientWriteTuplesRequestInterface_GetOptions_Call struct { + *mock.Call +} + +// GetOptions is a helper method to define mock.On call +func (_e *MockSdkClientWriteTuplesRequestInterface_Expecter) GetOptions() *MockSdkClientWriteTuplesRequestInterface_GetOptions_Call { + return &MockSdkClientWriteTuplesRequestInterface_GetOptions_Call{Call: _e.mock.On("GetOptions")} +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_GetOptions_Call) Run(run func()) *MockSdkClientWriteTuplesRequestInterface_GetOptions_Call { + _c.Call.Run(func(args mock.Arguments) { + run() + }) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_GetOptions_Call) Return(_a0 *client.ClientWriteOptions) *MockSdkClientWriteTuplesRequestInterface_GetOptions_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_GetOptions_Call) RunAndReturn(run func() *client.ClientWriteOptions) *MockSdkClientWriteTuplesRequestInterface_GetOptions_Call { + _c.Call.Return(run) + return _c +} + +// Options provides a mock function with given fields: options +func (_m *MockSdkClientWriteTuplesRequestInterface) Options(options client.ClientWriteOptions) client.SdkClientWriteTuplesRequestInterface { + ret := _m.Called(options) + + if len(ret) == 0 { + panic("no return value specified for Options") + } + + var r0 client.SdkClientWriteTuplesRequestInterface + if rf, ok := ret.Get(0).(func(client.ClientWriteOptions) client.SdkClientWriteTuplesRequestInterface); ok { + r0 = rf(options) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(client.SdkClientWriteTuplesRequestInterface) + } + } + + return r0 +} + +// MockSdkClientWriteTuplesRequestInterface_Options_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Options' +type MockSdkClientWriteTuplesRequestInterface_Options_Call struct { + *mock.Call +} + +// Options is a helper method to define mock.On call +// - options client.ClientWriteOptions +func (_e *MockSdkClientWriteTuplesRequestInterface_Expecter) Options(options interface{}) *MockSdkClientWriteTuplesRequestInterface_Options_Call { + return &MockSdkClientWriteTuplesRequestInterface_Options_Call{Call: _e.mock.On("Options", options)} +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_Options_Call) Run(run func(options client.ClientWriteOptions)) *MockSdkClientWriteTuplesRequestInterface_Options_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(client.ClientWriteOptions)) + }) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_Options_Call) Return(_a0 client.SdkClientWriteTuplesRequestInterface) *MockSdkClientWriteTuplesRequestInterface_Options_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockSdkClientWriteTuplesRequestInterface_Options_Call) RunAndReturn(run func(client.ClientWriteOptions) client.SdkClientWriteTuplesRequestInterface) *MockSdkClientWriteTuplesRequestInterface_Options_Call { + _c.Call.Return(run) + return _c +} + +// NewMockSdkClientWriteTuplesRequestInterface creates a new instance of MockSdkClientWriteTuplesRequestInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockSdkClientWriteTuplesRequestInterface(t interface { + mock.TestingT + Cleanup(func()) +}) *MockSdkClientWriteTuplesRequestInterface { + mock := &MockSdkClientWriteTuplesRequestInterface{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/fgax/model.go b/fgax/model.go new file mode 100644 index 0000000..cd9c834 --- /dev/null +++ b/fgax/model.go @@ -0,0 +1,321 @@ +package fgax + +import ( + "context" + "encoding/json" + "os" + + openfga "github.com/openfga/go-sdk" + ofgaclient "github.com/openfga/go-sdk/client" + language "github.com/openfga/language/pkg/go/transformer" + typesystem "github.com/openfga/openfga/pkg/typesystem" + + "github.com/pkg/errors" + "google.golang.org/protobuf/encoding/protojson" +) + +// CreateModelFromFile creates a new fine grained authorization model and returns the model ID +func (c *Client) CreateModelFromFile(ctx context.Context, fn string, forceCreate bool) (string, error) { + options := ofgaclient.ClientReadAuthorizationModelsOptions{} + + models, err := c.Ofga.ReadAuthorizationModels(context.Background()).Options(options).Execute() + if err != nil { + return "", err + } + + // Only create a new test model if one does not exist and we aren't forcing a new model to be created + if !forceCreate { + if len(models.AuthorizationModels) > 0 { + modelID := models.GetAuthorizationModels()[0].Id + c.Logger.Infow("fga model exists", "model_id", modelID) + + return modelID, nil + } + } + + // Create new model + dsl, err := os.ReadFile(fn) + if err != nil { + return "", err + } + + return c.CreateModelFromDSL(ctx, dsl) +} + +// CreateModelFromDSL creates a new fine grained authorization model from the DSL and returns the model ID +func (c *Client) CreateModelFromDSL(ctx context.Context, dsl []byte) (string, error) { + // convert to json + dslJSON, err := dslToJSON(dsl) + if err != nil { + return "", err + } + + var body ofgaclient.ClientWriteAuthorizationModelRequest + if err := json.Unmarshal(dslJSON, &body); err != nil { + return "", err + } + + return c.CreateModel(ctx, body) +} + +// CreateModel creates a new authorization model and returns the new model ID +func (c *Client) CreateModel(ctx context.Context, model ofgaclient.ClientWriteAuthorizationModelRequest) (string, error) { + resp, err := c.Ofga.WriteAuthorizationModel(ctx).Body(model).Execute() + if err != nil { + return "", err + } + + modelID := resp.GetAuthorizationModelId() + + c.Logger.Infow("fga model created", "model_id", modelID) + + return modelID, nil +} + +// dslToJSON converts fga model to JSON +func dslToJSON(dslString []byte) ([]byte, error) { + parsedAuthModel, err := language.TransformDSLToProto(string(dslString)) + if err != nil { + return []byte{}, errors.Wrap(err, ErrFailedToTransformModel.Error()) + } + + return protojson.Marshal(parsedAuthModel) +} + +// RoleRequest is the request to add a role to the model for an existing object +type RoleRequest struct { + // Role is the relation to add to the model + Role string + // Relation is the relation to the object + Relations []RelationSetting + // RelationCombination is the combination of the relation + RelationCombination RelationCombination + // ObjectType is the object type to add the role to + ObjectType string +} + +// RelationCombination is the combination of the relation as an `and`, `or`, or `not` +type RelationCombination string + +const ( + // Union is an `or` relation + Union RelationCombination = "union" + // Intersection is an `and` relation + Intersection RelationCombination = "intersection" + // Difference is a `not` relation, currently not supported + // Difference RelationCombination = "difference" +) + +// RelationSetting includes the name of the relation as well as flags to determine the type of relation +type RelationSetting struct { + // Relation is the relation to the object + Relation string + // IsDirect is the direct relation to another fga object type + IsDirect bool + // FromRelation is the relation from another relation, leave empty if not a from relation + FromRelation string +} + +// AddOrReplaceRole adds (or replaces the existing) the role to the model and updates the config with the new model id +func (c *Client) AddOrReplaceRole(ctx context.Context, r RoleRequest) error { + // read the latest model + model, err := c.Ofga.ReadLatestAuthorizationModel(ctx).Execute() + if err != nil { + return err + } + + // get the model + m := model.GetAuthorizationModel() + + // get the type definitions from the existing model + td := m.TypeDefinitions + + addedRole := false + + for i, t := range td { + if t.Type == r.ObjectType { + // initialize the relation map + relations := t.GetRelations() + + // add the role to the relation map + var metadata *openfga.Metadata + relations[r.Role], metadata = generateUserset(r) + + // set the relation map and metadata + t.SetRelations(relations) + // t.SetMetadata(metadata) + + metadataRelations := t.Metadata.GetRelations() + for k, v := range *metadata.Relations { + metadataRelations[k] = v + } + + t.Metadata.SetRelations(metadataRelations) + + // set the updated type definition + m.TypeDefinitions[i] = t + + // track that we added the role + addedRole = true + } + } + + // if we didn't add the role, create a new type definition + if !addedRole { + m.TypeDefinitions = append(m.TypeDefinitions, + createNewTypeDefinition(r)) + } + + // create the request to write the model + request := ofgaclient.ClientWriteAuthorizationModelRequest{ + SchemaVersion: m.SchemaVersion, + Conditions: m.Conditions, + TypeDefinitions: m.TypeDefinitions, + } + + // write the model back + resp, err := c.Ofga.WriteAuthorizationModel(ctx).Body(request).Execute() + if err != nil { + return err + } + + // update to the new model ID in the config + c.Config.AuthorizationModelId = resp.GetAuthorizationModelId() + + return nil +} + +// createNewTypeDefinition creates a new type definition for the model +func createNewTypeDefinition(r RoleRequest) openfga.TypeDefinition { + relation := make(map[string]openfga.Userset) + td := openfga.TypeDefinition{ + Type: r.ObjectType, + } + + // get all the usersets + us, metadata := generateUserset(r) + + relation[r.Role] = us + td.Relations = &relation + td.Metadata = metadata + + return td +} + +// generateUserset creates the userset and metadata for the role request +func generateUserset(r RoleRequest) (us openfga.Userset, metadata *openfga.Metadata) { + // create the default metadata + metadata = openfga.NewMetadataWithDefaults() + + // create the usersets and determine if we have a direct relation + uses, directRelation := createUsersets(r) + + // generate the metadata + md := createNewMetadata(r.Role, directRelation) + metadata.SetRelations(md) + + // now combine the usersets + switch r.RelationCombination { + case Intersection: + us.Intersection = &openfga.Usersets{ + Child: uses, + } + case Union: + us.Union = &openfga.Usersets{ + Child: uses, + } + default: + // if we only have one userset, just return it + if len(uses) == 1 { + us = uses[0] + } else { // default to union + us.Union = &openfga.Usersets{ + Child: uses, + } + } + } + + return us, metadata +} + +// createUsersets creates the usersets for the role request and determines if there is a direct relation +func createUsersets(r RoleRequest) (uses []openfga.Userset, directRelation string) { + for _, relation := range r.Relations { + rel := relation + + switch { + case relation.IsDirect: + // create direct relation + relations := newDirectRelation(r.Role) + uses = append(uses, relations) + + directRelation = relation.Relation + case relation.FromRelation != "": + // create tuple set for a from relation + uses = append(uses, newTupleUsersetRelation(rel.Relation, rel.FromRelation)) + default: + // create computed userset, which is a relation to another relation + uses = append(uses, newComputedUsersetRelation(rel.Relation)) + } + } + + return +} + +// createNewMetadata creates a new metadata for the relations +func createNewMetadata(r string, userType string) map[string]openfga.RelationMetadata { + rd := make(map[string]openfga.RelationMetadata) + rd[r] = openfga.RelationMetadata{ + DirectlyRelatedUserTypes: &[]openfga.RelationReference{}, + } + + if userType != "" { + rd[r] = openfga.RelationMetadata{ + DirectlyRelatedUserTypes: &[]openfga.RelationReference{ + { + Type: userType, + }, + }, + } + } + + return rd +} + +// newDirectRelation creates a new relation to an existing object +func newDirectRelation(role string) openfga.Userset { + // create the user set + thisRelation := make(map[string]interface{}) + thisRelation[role] = typesystem.This() + + us := openfga.Userset{ + This: &thisRelation, + } + + return us +} + +// newComputedUsersetRelation creates a new computed relation to another relation +func newComputedUsersetRelation(relation string) openfga.Userset { + return openfga.Userset{ + ComputedUserset: &openfga.ObjectRelation{ + Relation: &relation, + }, + } +} + +// newTupleUsersetRelation creates a new tuple relation to another relation +func newTupleUsersetRelation(relation, fromRelation string) openfga.Userset { + ts := openfga.TupleToUserset{ + Tupleset: openfga.ObjectRelation{ + Relation: &fromRelation, + }, + ComputedUserset: openfga.ObjectRelation{ + Relation: &relation, + }, + } + + return openfga.Userset{ + TupleToUserset: &ts, + } +} diff --git a/fgax/model_test.go b/fgax/model_test.go new file mode 100644 index 0000000..7d84096 --- /dev/null +++ b/fgax/model_test.go @@ -0,0 +1,414 @@ +package fgax + +import ( + "testing" + + openfga "github.com/openfga/go-sdk" + typesystem "github.com/openfga/openfga/pkg/typesystem" + "github.com/samber/lo" + "github.com/stretchr/testify/assert" +) + +func TestNewDirectRelation(t *testing.T) { + testCases := []struct { + name string + role string + expectedRes openfga.Userset + }{ + { + name: "new admin role", + role: "admin", + expectedRes: openfga.Userset{ + This: &map[string]interface{}{ + "admin": typesystem.This(), + }, + }, + }, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + userset := newDirectRelation(tc.role) + + assert.Equal(t, tc.expectedRes, userset) + }) + } +} + +func TestNewComputedUsersetRelation(t *testing.T) { + testCases := []struct { + name string + relation string + expectedRes openfga.Userset + }{ + { + name: "new relation", + relation: "meow", + expectedRes: openfga.Userset{ + ComputedUserset: &openfga.ObjectRelation{ + Relation: lo.ToPtr("meow"), + }, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + userset := newComputedUsersetRelation(tc.relation) + + assert.Equal(t, tc.expectedRes, userset) + }) + } +} + +func TestNewTupleUsersetRelation(t *testing.T) { + testCases := []struct { + name string + relation string + fromRelation string + expectedRes openfga.Userset + }{ + { + name: "new tuple userset relation", + relation: "relation", + fromRelation: "fromRelation", + expectedRes: openfga.Userset{ + TupleToUserset: &openfga.TupleToUserset{ + Tupleset: openfga.ObjectRelation{ + Relation: lo.ToPtr("fromRelation"), + }, + ComputedUserset: openfga.ObjectRelation{ + Relation: lo.ToPtr("relation"), + }, + }, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + userset := newTupleUsersetRelation(tc.relation, tc.fromRelation) + + assert.Equal(t, tc.expectedRes, userset) + }) + } +} + +func TestCreateNewMetadata(t *testing.T) { + testCases := []struct { + name string + relation string + userType string + expectedRD map[string]openfga.RelationMetadata + }{ + { + name: "empty user type, not direct", + relation: "relation", + userType: "", + expectedRD: map[string]openfga.RelationMetadata{ + "relation": { + DirectlyRelatedUserTypes: &[]openfga.RelationReference{}, + }, + }, + }, + { + name: "non-empty user type, direct relation", + relation: "relation", + userType: "user", + expectedRD: map[string]openfga.RelationMetadata{ + "relation": { + DirectlyRelatedUserTypes: &[]openfga.RelationReference{ + { + Type: "user", + }, + }, + }, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + rd := createNewMetadata(tc.relation, tc.userType) + + assert.Equal(t, tc.expectedRD, rd) + }) + } +} + +func TestCreateUsersets(t *testing.T) { + testCases := []struct { + name string + role string + relations []RelationSetting + expectedUses []openfga.Userset + expectedDirect string + }{ + { + name: "direct relation", + role: "admin", + relations: []RelationSetting{ + { + IsDirect: true, + Relation: "admin", + }, + }, + expectedUses: []openfga.Userset{ + { + This: &map[string]interface{}{ + "admin": typesystem.This(), + }, + }, + }, + expectedDirect: "admin", + }, + { + name: "tuple set for a from relation", + role: "user", + relations: []RelationSetting{ + { + Relation: "relation", + FromRelation: "fromRelation", + }, + }, + expectedUses: []openfga.Userset{ + { + TupleToUserset: &openfga.TupleToUserset{ + Tupleset: openfga.ObjectRelation{ + Relation: lo.ToPtr("fromRelation"), + }, + ComputedUserset: openfga.ObjectRelation{ + Relation: lo.ToPtr("relation"), + }, + }, + }, + }, + expectedDirect: "", + }, + { + name: "computed userset", + role: "user", + relations: []RelationSetting{ + { + Relation: "relation", + }, + }, + expectedUses: []openfga.Userset{ + { + ComputedUserset: &openfga.ObjectRelation{ + Relation: lo.ToPtr("relation"), + }, + }, + }, + expectedDirect: "", + }, + { + name: "multiple relations with direct", + role: "user", + relations: []RelationSetting{ + { + Relation: "relation", + }, + { + IsDirect: true, + Relation: "admin", + }, + }, + expectedUses: []openfga.Userset{ + { + ComputedUserset: &openfga.ObjectRelation{ + Relation: lo.ToPtr("relation"), + }, + }, + { + This: &map[string]interface{}{ + "user": typesystem.This(), + }, + }, + }, + expectedDirect: "admin", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + uses, directRelation := createUsersets(RoleRequest{ + Role: tc.role, + Relations: tc.relations, + }) + + assert.Equal(t, tc.expectedUses, uses) + assert.Equal(t, tc.expectedDirect, directRelation) + }) + } +} + +func TestGenerateUserset(t *testing.T) { + testCases := []struct { + name string + role string + relations []RelationSetting + relationCombination RelationCombination + expectedUserset openfga.Userset + expectedMetadata *openfga.Metadata + }{ + { + name: "intersection combination", + role: "admin", + relations: []RelationSetting{ + { + IsDirect: true, + Relation: "user", + }, + { + Relation: "member", + }, + }, + relationCombination: Intersection, + expectedUserset: openfga.Userset{ + Intersection: &openfga.Usersets{ + Child: []openfga.Userset{ + { + This: &map[string]interface{}{ + "admin": typesystem.This(), + }, + }, + { + ComputedUserset: &openfga.ObjectRelation{ + Relation: lo.ToPtr("member"), + }, + }, + }, + }, + }, + expectedMetadata: &openfga.Metadata{ + Relations: &map[string]openfga.RelationMetadata{ + "admin": { + DirectlyRelatedUserTypes: &[]openfga.RelationReference{ + { + Type: "user", + }, + }, + }, + }, + }, + }, + { + name: "union combination", + role: "user", + relations: []RelationSetting{ + { + Relation: "relation", + FromRelation: "fromRelation", + }, + { + Relation: "member", + }, + }, + relationCombination: Union, + expectedUserset: openfga.Userset{ + Union: &openfga.Usersets{ + Child: []openfga.Userset{ + { + TupleToUserset: &openfga.TupleToUserset{ + Tupleset: openfga.ObjectRelation{ + Relation: lo.ToPtr("fromRelation"), + }, + ComputedUserset: openfga.ObjectRelation{ + Relation: lo.ToPtr("relation"), + }, + }, + }, + { + ComputedUserset: &openfga.ObjectRelation{ + Relation: lo.ToPtr("member"), + }, + }, + }, + }, + }, + expectedMetadata: &openfga.Metadata{ + Relations: &map[string]openfga.RelationMetadata{ + "user": { + DirectlyRelatedUserTypes: &[]openfga.RelationReference{}, + }, + }, + }, + }, + { + name: "default combination with one userset", + role: "user", + relations: []RelationSetting{ + { + Relation: "relation", + }, + }, + relationCombination: "", + expectedUserset: openfga.Userset{ + ComputedUserset: &openfga.ObjectRelation{ + Relation: lo.ToPtr("relation"), + }, + }, + expectedMetadata: &openfga.Metadata{ + Relations: &map[string]openfga.RelationMetadata{ + "user": { + DirectlyRelatedUserTypes: &[]openfga.RelationReference{}, + }, + }, + }, + }, + { + name: "default combination with multiple usersets", + role: "user", + relations: []RelationSetting{ + { + Relation: "relation", + }, + { + IsDirect: true, + Relation: "admin", + }, + }, + relationCombination: "", + expectedUserset: openfga.Userset{ + Union: &openfga.Usersets{ + Child: []openfga.Userset{ + { + ComputedUserset: &openfga.ObjectRelation{ + Relation: lo.ToPtr("relation"), + }, + }, + { + This: &map[string]interface{}{ + "user": typesystem.This(), + }, + }, + }, + }, + }, + expectedMetadata: &openfga.Metadata{ + Relations: &map[string]openfga.RelationMetadata{ + "user": { + DirectlyRelatedUserTypes: &[]openfga.RelationReference{ + { + Type: "admin", + }, + }, + }, + }, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + userset, metadata := generateUserset(RoleRequest{ + Role: tc.role, + Relations: tc.relations, + RelationCombination: tc.relationCombination, + }) + + assert.Equal(t, tc.expectedUserset, userset) + assert.Equal(t, tc.expectedMetadata, metadata) + }) + } +} diff --git a/fgax/test_tools.go b/fgax/test_tools.go new file mode 100644 index 0000000..5f095ea --- /dev/null +++ b/fgax/test_tools.go @@ -0,0 +1,27 @@ +package fgax + +import ( + "testing" + + openfga "github.com/openfga/go-sdk" + ofgaclient "github.com/openfga/go-sdk/client" + "go.uber.org/zap" + + mock_fga "github.com/theopenlane/iam/fgax/mockery" +) + +// NewMockFGAClient is a mock client based on the mockery testing framework +func NewMockFGAClient(t *testing.T, c *mock_fga.MockSdkClient) *Client { + client := Client{ + Config: ofgaclient.ClientConfiguration{ + // The api host is the only required field when setting up a new FGA client connection + ApiHost: "fga.theopenlane.io", + AuthorizationModelId: *openfga.PtrString("test-model-id"), + StoreId: *openfga.PtrString("test-store-id"), + }, + Ofga: c, + Logger: zap.NewNop().Sugar(), + } + + return &client +} diff --git a/fgax/tools.go b/fgax/tools.go new file mode 100644 index 0000000..3da76e0 --- /dev/null +++ b/fgax/tools.go @@ -0,0 +1,10 @@ +//go:build tools +// +build tools + +package tools + +import ( + _ "github.com/99designs/gqlgen" + _ "github.com/99designs/gqlgen/graphql/introspection" + _ "github.com/Yamashou/gqlgenc" +) diff --git a/fgax/tuples.go b/fgax/tuples.go new file mode 100644 index 0000000..b427d43 --- /dev/null +++ b/fgax/tuples.go @@ -0,0 +1,318 @@ +package fgax + +import ( + "context" + "regexp" + "strings" + + openfga "github.com/openfga/go-sdk" + ofgaclient "github.com/openfga/go-sdk/client" +) + +// setup relations for use in creating tuples +const ( + // SystemAdminRole is the role for system admins that have the highest level of access + SystemAdminRole = "system_admin" + // MemberRelation is the relation for members of an entity + MemberRelation = "member" + // AdminRelation is the relation for admins of an entity + AdminRelation = "admin" + // OwnerRelation is the relation for owners of an entity + OwnerRelation = "owner" + // ParentRelation is the relation for parents of an entity + ParentRelation = "parent" + // AssigneeRoleRelation is the relation for assignees of an entity + RoleRelation = "assignee" + // CanView is the relation for viewing an entity + CanView = "can_view" + // CanEdit is the relation for editing an entity + CanEdit = "can_edit" + // CanDelete is the relation for deleting an entity + CanDelete = "can_delete" +) + +const ( + // defaultPageSize is based on the openfga max of 100 + defaultPageSize = 100 + // maxWrites is the maximum number of Writes and Deletes supported by the OpenFGA transactional write api + // see https://openfga.dev/docs/interacting/transactional-writes for more details + maxWrites = 10 +) + +// TupleKey represents a relationship tuple in OpenFGA +type TupleKey struct { + // Subject is the entity that is the subject of the relationship, usually a user + Subject Entity + // Object is the entity that is the object of the relationship, (e.g. organization, project, document, etc) + Object Entity + // Relation is the relationship between the subject and object + Relation Relation `json:"relation"` +} + +// TupleRequest is the fields needed to check a tuple in the FGA store +type TupleRequest struct { + // ObjectID is the identifier of the object that the subject is related to + ObjectID string + // ObjectType is the type of object that the subject is related to + ObjectType string + // SubjectID is the identifier of the subject that is related to the object + SubjectID string + // SubjectType is the type of subject that is related to the object + SubjectType string + // Relation is the relationship between the subject and object + Relation string +} + +func NewTupleKey() TupleKey { return TupleKey{} } + +// entityRegex is used to validate that a string represents an Entity/EntitySet +// and helps to convert from a string representation into an Entity struct. +var entityRegex = regexp.MustCompile(`([A-za-z0-9_][A-za-z0-9_-]*):([A-za-z0-9_][A-za-z0-9_@.+-]*)(#([A-za-z0-9_][A-za-z0-9_-]*))?`) + +// Kind represents the type of the entity in OpenFGA. +type Kind string + +// String implements the Stringer interface. +func (k Kind) String() string { + return strings.ToLower(string(k)) +} + +// Relation represents the type of relation between entities in OpenFGA. +type Relation string + +// String implements the Stringer interface. +func (r Relation) String() string { + return strings.ToLower(string(r)) +} + +// Entity represents an entity/entity-set in OpenFGA. +// Example: `user:`, `org:#member` +type Entity struct { + Kind Kind + Identifier string + Relation Relation +} + +// String returns a string representation of the entity/entity-set. +func (e *Entity) String() string { + if e.Relation == "" { + return e.Kind.String() + ":" + e.Identifier + } + + return e.Kind.String() + ":" + e.Identifier + "#" + e.Relation.String() +} + +// ParseEntity will parse a string representation into an Entity. It expects to +// find entities of the form: +// - : +// eg. organization:openlane +// - :# +// eg. organization:openlane#member +func ParseEntity(s string) (Entity, error) { + // entities should only contain a single colon + c := strings.Count(s, ":") + if c != 1 { + return Entity{}, newInvalidEntityError(s) + } + + match := entityRegex.FindStringSubmatch(s) + if match == nil { + return Entity{}, newInvalidEntityError(s) + } + + // Extract and return the relevant information from the sub-matches. + return Entity{ + Kind: Kind(match[1]), + Identifier: match[2], + Relation: Relation(match[4]), + }, nil +} + +// tupleKeyToWriteRequest converts a TupleKey to a ClientTupleKey to send to FGA +func tupleKeyToWriteRequest(writes []TupleKey) (w []ofgaclient.ClientTupleKey) { + for _, k := range writes { + ctk := ofgaclient.ClientTupleKey{} + ctk.SetObject(k.Object.String()) + ctk.SetUser(k.Subject.String()) + ctk.SetRelation(k.Relation.String()) + + w = append(w, ctk) + } + + return +} + +// tupleKeyToDeleteRequest converts a TupleKey to a TupleKeyWithoutCondition to send to FGA +func tupleKeyToDeleteRequest(deletes []TupleKey) (d []openfga.TupleKeyWithoutCondition) { + for _, k := range deletes { + ctk := openfga.TupleKeyWithoutCondition{} + ctk.SetObject(k.Object.String()) + ctk.SetUser(k.Subject.String()) + ctk.SetRelation(k.Relation.String()) + + d = append(d, ctk) + } + + return +} + +// WriteTupleKeys takes a tuples keys, converts them to a client write request, which can contain up to 10 writes and deletes, +// and executes in a single transaction +func (c *Client) WriteTupleKeys(ctx context.Context, writes []TupleKey, deletes []TupleKey) (*ofgaclient.ClientWriteResponse, error) { + opts := ofgaclient.ClientWriteOptions{AuthorizationModelId: openfga.PtrString(c.Config.AuthorizationModelId)} + + body := ofgaclient.ClientWriteRequest{ + Writes: tupleKeyToWriteRequest(writes), + Deletes: tupleKeyToDeleteRequest(deletes), + } + + resp, err := c.Ofga.Write(ctx).Body(body).Options(opts).Execute() + if err != nil { + c.Logger.Infow("error writing relationship tuples", "error", err.Error(), "user", resp.Writes) + + return resp, err + } + + for _, writes := range resp.Writes { + if writes.Error != nil { + c.Logger.Errorw("error creating relationship tuples", "user", writes.TupleKey.User, "relation", writes.TupleKey.Relation, "object", writes.TupleKey.Object) + + return resp, newWritingTuplesError(writes.TupleKey.User, writes.TupleKey.Relation, writes.TupleKey.Object, "writing", err) + } + } + + for _, deletes := range resp.Deletes { + if deletes.Error != nil { + c.Logger.Errorw("error deleting relationship tuples", "user", deletes.TupleKey.User, "relation", deletes.TupleKey.Relation, "object", deletes.TupleKey.Object) + + return resp, newWritingTuplesError(deletes.TupleKey.User, deletes.TupleKey.Relation, deletes.TupleKey.Object, "writing", err) + } + } + + return resp, nil +} + +// deleteRelationshipTuple deletes a relationship tuple in the openFGA store +func (c *Client) deleteRelationshipTuple(ctx context.Context, tuples []openfga.TupleKeyWithoutCondition) (*ofgaclient.ClientWriteResponse, error) { + if len(tuples) == 0 { + return nil, nil + } + + opts := ofgaclient.ClientWriteOptions{AuthorizationModelId: openfga.PtrString(c.Config.AuthorizationModelId)} + + resp, err := c.Ofga.DeleteTuples(ctx).Body(tuples).Options(opts).Execute() + if err != nil { + c.Logger.Errorw("error deleting relationship tuples", "error", err.Error()) + + return resp, err + } + + for _, del := range resp.Deletes { + if del.Error != nil { + c.Logger.Errorw("error deleting relationship tuples", "user", del.TupleKey.User, "relation", del.TupleKey.Relation, "object", del.TupleKey.Object) + + return resp, newWritingTuplesError(del.TupleKey.User, del.TupleKey.Relation, del.TupleKey.Object, "deleting", err) + } + } + + return resp, nil +} + +// getAllTuples gets all the relationship tuples in the openFGA store +func (c *Client) getAllTuples(ctx context.Context) ([]openfga.Tuple, error) { + var tuples []openfga.Tuple + + opts := ofgaclient.ClientReadOptions{ + PageSize: openfga.PtrInt32(defaultPageSize), + ContinuationToken: openfga.PtrString(" "), + } + + notComplete := true + + // paginate through all the tuples + for notComplete { + resp, err := c.Ofga.Read(ctx).Options(opts).Execute() + if err != nil { + c.Logger.Errorw("error getting relationship tuples", "error", err.Error()) + + return nil, err + } + + tuples = append(tuples, resp.GetTuples()...) + + if resp.ContinuationToken == "" { + notComplete = false + } else { + opts.ContinuationToken = &resp.ContinuationToken + } + } + + return tuples, nil +} + +// DeleteAllObjectRelations deletes all the relationship tuples for a given object +func (c *Client) DeleteAllObjectRelations(ctx context.Context, object string) error { + // validate object is not empty + if object == "" { + return ErrMissingObjectOnDeletion + } + + match := entityRegex.FindStringSubmatch(object) + if match == nil { + return newInvalidEntityError(object) + } + + tuples, err := c.getAllTuples(ctx) + if err != nil { + return err + } + + var tuplesToDelete []openfga.TupleKeyWithoutCondition + + // check all the tuples for the object + for _, t := range tuples { + if t.Key.Object == object { + k := openfga.TupleKeyWithoutCondition{ + User: t.Key.User, + Relation: t.Key.Relation, + Object: t.Key.Object, + } + tuplesToDelete = append(tuplesToDelete, k) + } + } + + // delete the tuples in batches of 10, the max supported by the OpenFGA transactional write api + for i := 0; i < len(tuplesToDelete); i += maxWrites { + end := i + maxWrites + if end > len(tuplesToDelete) { + end = len(tuplesToDelete) + } + + allTuples := tuplesToDelete[i:end] + + if _, err := c.deleteRelationshipTuple(ctx, allTuples); err != nil { + return err + } + } + + return nil +} + +// GetTupleKey creates a Tuple key with the provided subject, object, and role +func GetTupleKey(req TupleRequest) TupleKey { + sub := Entity{ + Kind: Kind(req.SubjectType), + Identifier: req.SubjectID, + } + + object := Entity{ + Kind: Kind(req.ObjectType), + Identifier: req.ObjectID, + } + + return TupleKey{ + Subject: sub, + Object: object, + Relation: Relation(req.Relation), + } +} diff --git a/fgax/tuples_test.go b/fgax/tuples_test.go new file mode 100644 index 0000000..ba920c8 --- /dev/null +++ b/fgax/tuples_test.go @@ -0,0 +1,494 @@ +package fgax + +import ( + "context" + "fmt" + "testing" + + openfga "github.com/openfga/go-sdk" + "github.com/stretchr/testify/assert" + + mock_fga "github.com/theopenlane/iam/fgax/mockery" +) + +func TestEntityString(t *testing.T) { + memberRelation := Relation("member") + + testCases := []struct { + name string + entity Entity + expectedRes string + }{ + { + name: "relationship empty", + entity: Entity{ + Kind: "user", + Identifier: "bz0yOLsL460V-6L9HauX4", + Relation: "", + }, + expectedRes: "user:bz0yOLsL460V-6L9HauX4", + }, + { + name: "relationship member", + entity: Entity{ + Kind: "organization", + Identifier: "yKreKfzq3-iG-rhj0N9o9", + Relation: memberRelation, + }, + expectedRes: "organization:yKreKfzq3-iG-rhj0N9o9#member", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + res := tc.entity.String() + + // result should never be empty + assert.NotEmpty(t, res) + assert.Equal(t, tc.expectedRes, res) + }) + } +} + +func TestParseEntity(t *testing.T) { + memberRelation := Relation("member") + + testCases := []struct { + name string + entity string + expectedRes Entity + errRes string + }{ + { + name: "happy path, user", + + entity: "user:bz0yOLsL460V-6L9HauX4", + expectedRes: Entity{ + Kind: "user", + Identifier: "bz0yOLsL460V-6L9HauX4", + Relation: "", + }, + errRes: "", + }, + { + name: "relationship member", + entity: "organization:yKreKfzq3-iG-rhj0N9o9#member", + expectedRes: Entity{ + Kind: "organization", + Identifier: "yKreKfzq3-iG-rhj0N9o9", + Relation: memberRelation, + }, + errRes: "", + }, + { + name: "missing parts", + entity: "organization", + expectedRes: Entity{}, + errRes: "invalid entity representation", + }, + { + name: "too many parts", + entity: "organization:yKreKfzq3-iG-rhj0N9o9#member:user:bz0yOLsL460V-6L9HauX4", + expectedRes: Entity{}, + errRes: "invalid entity representation", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + res, err := ParseEntity(tc.entity) + + // if we expect an error, check that first + if tc.errRes != "" { + assert.Error(t, err) + assert.ErrorContains(t, err, tc.errRes) + assert.Empty(t, res) + + return + } + + assert.NoError(t, err) + assert.NotEmpty(t, res) + assert.Equal(t, tc.expectedRes, res) + }) + } +} + +func TestTupleKeyToWriteRequest(t *testing.T) { + testCases := []struct { + name string + writes []TupleKey + expectedUser string + expectedRelation string + expectedObject string + expectedCount int + }{ + { + name: "happy path, user", + writes: []TupleKey{ + { + Subject: Entity{ + Kind: "user", + Identifier: "THEBESTUSER", + }, + Relation: "member", + Object: Entity{ + Kind: "organization", + Identifier: "IDOFTHEORG", + }, + }, + }, + expectedUser: "user:THEBESTUSER", + expectedRelation: "member", + expectedObject: "organization:IDOFTHEORG", + expectedCount: 1, + }, + { + name: "happy path, should lowercase kind and relations", + writes: []TupleKey{ + { + Subject: Entity{ + Kind: "USER", + Identifier: "THEBESTUSER", + }, + Relation: "MEMBER", + Object: Entity{ + Kind: "ORGANIZATION", + Identifier: "IDOFTHEORG", + }, + }, + }, + expectedUser: "user:THEBESTUSER", + expectedRelation: "member", + expectedObject: "organization:IDOFTHEORG", + expectedCount: 1, + }, + { + name: "happy path, group", + writes: []TupleKey{ + { + Subject: Entity{ + Kind: "group", + Identifier: "AOPENLANEGROUP", + }, + Relation: "parent", + Object: Entity{ + Kind: "organization", + Identifier: "IDOFTHEORG", + Relation: "member", + }, + }, + }, + expectedUser: "group:AOPENLANEGROUP", + expectedRelation: "parent", + expectedObject: "organization:IDOFTHEORG#member", + expectedCount: 1, + }, + { + name: "happy path, multiple", + writes: []TupleKey{ + { + Subject: Entity{ + Kind: "user", + Identifier: "SITB", + }, + Relation: "member", + Object: Entity{ + Kind: "organization", + Identifier: "IDOFTHEORG", + }, + }, + { + Subject: Entity{ + Kind: "user", + Identifier: "MITB", + }, + Relation: "admin", + Object: Entity{ + Kind: "organization", + Identifier: "IDOFTHEORG", + }, + }, + }, + expectedCount: 2, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + ctk := tupleKeyToWriteRequest(tc.writes) + assert.NotEmpty(t, ctk) + + if tc.expectedCount == 1 { + assert.Equal(t, tc.expectedUser, ctk[0].User) + assert.Equal(t, tc.expectedRelation, ctk[0].Relation) + assert.Equal(t, tc.expectedObject, ctk[0].Object) + } else { + assert.Len(t, ctk, tc.expectedCount) + } + }) + } +} + +func TestTupleKeyToDeleteRequest(t *testing.T) { + testCases := []struct { + name string + writes []TupleKey + expectedUser string + expectedRelation string + expectedObject string + expectedCount int + }{ + { + name: "happy path, user", + writes: []TupleKey{ + { + Subject: Entity{ + Kind: "user", + Identifier: "THEBESTUSER", + }, + Relation: "member", + Object: Entity{ + Kind: "organization", + Identifier: "IDOFTHEORG", + }, + }, + }, + expectedUser: "user:THEBESTUSER", + expectedRelation: "member", + expectedObject: "organization:IDOFTHEORG", + expectedCount: 1, + }, + { + name: "happy path, uppercase", + writes: []TupleKey{ + { + Subject: Entity{ + Kind: "USER", + Identifier: "THEBESTUSER", + }, + Relation: "MEMBER", + Object: Entity{ + Kind: "ORGANIZATION", + Identifier: "IDOFTHEORG", + }, + }, + }, + expectedUser: "user:THEBESTUSER", + expectedRelation: "member", + expectedObject: "organization:IDOFTHEORG", + expectedCount: 1, + }, + { + name: "happy path, group", + writes: []TupleKey{ + { + Subject: Entity{ + Kind: "group", + Identifier: "AOPENLANEGROUP", + }, + Relation: "parent", + Object: Entity{ + Kind: "organization", + Identifier: "IDOFTHEORG", + Relation: "member", + }, + }, + }, + expectedUser: "group:AOPENLANEGROUP", + expectedRelation: "parent", + expectedObject: "organization:IDOFTHEORG#member", + expectedCount: 1, + }, + { + name: "happy path, multiple", + writes: []TupleKey{ + { + Subject: Entity{ + Kind: "user", + Identifier: "SITB", + }, + Relation: "member", + Object: Entity{ + Kind: "organization", + Identifier: "IDOFTHEORG", + }, + }, + { + Subject: Entity{ + Kind: "user", + Identifier: "MITB", + }, + Relation: "admin", + Object: Entity{ + Kind: "organization", + Identifier: "IDOFTHEORG", + }, + }, + }, + expectedCount: 2, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + ctk := tupleKeyToDeleteRequest(tc.writes) + assert.NotEmpty(t, ctk) + + if tc.expectedCount == 1 { + assert.Equal(t, tc.expectedUser, ctk[0].User) + assert.Equal(t, tc.expectedRelation, ctk[0].Relation) + assert.Equal(t, tc.expectedObject, ctk[0].Object) + } else { + assert.Len(t, ctk, tc.expectedCount) + } + }) + } +} + +func TestWriteTupleKeys(t *testing.T) { + // setup mock client + c := mock_fga.NewMockSdkClient(t) + + fc := NewMockFGAClient(t, c) + + testCases := []struct { + name string + writes []TupleKey + deletes []TupleKey + }{ + { + name: "happy path with relation", + writes: []TupleKey{ + { + Subject: Entity{ + Kind: "user", + Identifier: "THEBESTUSER", + }, + Relation: "member", + Object: Entity{ + Kind: "organization", + Identifier: "IDOFTHEORG", + }, + }, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + mock_fga.WriteAny(t, c) + + _, err := fc.WriteTupleKeys(context.Background(), tc.writes, tc.deletes) + assert.NoError(t, err) + }) + } +} + +func TestDeleteRelationshipTuple(t *testing.T) { + // setup mock client + c := mock_fga.NewMockSdkClient(t) + + fc := NewMockFGAClient(t, c) + + testCases := []struct { + name string + relation string + object string + expectedRes string + errRes string + numTuplesToDelete int + }{ + { + name: "happy path with relation", + object: "organization:openlane", + relation: "member", + expectedRes: "", + numTuplesToDelete: 12, + errRes: "", + }, + { + name: "error, missing relation", + object: "organization:openlane", + relation: "", + expectedRes: "", + numTuplesToDelete: 1, + errRes: "Reason: the 'relation' field is malformed", + }, + { + name: "error, missing object", + object: "", + relation: "member", + expectedRes: "", + numTuplesToDelete: 1, + errRes: "Reason: invalid 'object' field format", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + defer mock_fga.ClearMocks(c) + + tuples := []openfga.TupleKeyWithoutCondition{} + + for i := range tc.numTuplesToDelete { + tuples = append(tuples, openfga.TupleKeyWithoutCondition{ + User: fmt.Sprintf("user:ulid-of-member-%d", i), + Relation: tc.relation, + Object: tc.object, + }) + } + + mock_fga.DeleteAny(t, c, tc.errRes) + + _, err := fc.deleteRelationshipTuple(context.Background(), tuples) + + if tc.errRes != "" { + assert.Error(t, err) + assert.ErrorContains(t, err, tc.errRes) + + return + } + + assert.NoError(t, err) + }) + } +} + +func TestGetTupleKey(t *testing.T) { + tests := []struct { + name string + req TupleRequest + want TupleKey + wantErr bool + }{ + { + name: "happy path", + req: TupleRequest{ + SubjectID: "HIITSME", + SubjectType: "user", + ObjectType: "organization", + ObjectID: "MIDNIGHTSAFTERNOON", + Relation: "member", + }, + want: TupleKey{ + Subject: Entity{ + Kind: "user", + Identifier: "HIITSME", + }, + Relation: "member", + Object: Entity{ + Kind: "organization", + Identifier: "MIDNIGHTSAFTERNOON", + }, + }, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := GetTupleKey(tt.req) + assert.Equal(t, tt.want, got) + }) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f1e38f0 --- /dev/null +++ b/go.mod @@ -0,0 +1,119 @@ +module github.com/theopenlane/iam + +go 1.23.0 + +require ( + entgo.io/ent v0.14.0 + github.com/99designs/gqlgen v0.17.49 + github.com/Yamashou/gqlgenc v0.24.0 + github.com/alicebob/miniredis/v2 v2.33.0 + github.com/golang-jwt/jwt/v5 v5.2.1 + github.com/openfga/go-sdk v0.5.0 + github.com/openfga/language/pkg/go v0.0.0-20240611203201-b6bbf9c4bb3a + github.com/openfga/openfga v1.5.9 + github.com/pkg/errors v0.9.1 + github.com/redis/go-redis/v9 v9.6.1 + github.com/samber/lo v1.47.0 + github.com/stoewer/go-strcase v1.3.0 + github.com/stretchr/testify v1.9.0 + github.com/theopenlane/core v0.1.1 + go.uber.org/zap v1.27.0 + golang.org/x/tools v0.24.0 + google.golang.org/protobuf v1.34.2 +) + +require ( + github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/goccy/go-json v0.10.3 // indirect + github.com/lestrrat-go/blackmagic v1.0.2 // indirect + github.com/lestrrat-go/httpcc v1.0.1 // indirect + github.com/lestrrat-go/httprc v1.0.6 // indirect + github.com/lestrrat-go/iter v1.0.2 // indirect + github.com/lestrrat-go/jwx/v2 v2.1.1 // indirect + github.com/lestrrat-go/option v1.0.1 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/segmentio/asm v1.2.0 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasttemplate v1.2.2 // indirect + github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect + github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect + github.com/yuin/gopher-lua v1.1.1 // indirect + golang.org/x/crypto v0.26.0 // indirect + golang.org/x/time v0.6.0 // indirect +) + +require ( + ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 // indirect + github.com/agext/levenshtein v1.2.3 // indirect + github.com/agnivade/levenshtein v1.1.1 // indirect + github.com/antlr4-go/antlr/v4 v4.13.1 // indirect + github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/emirpasic/gods v1.18.1 // indirect + github.com/envoyproxy/protoc-gen-validate v1.0.4 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-openapi/inflect v0.19.0 // indirect + github.com/google/cel-go v0.20.1 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/gorilla/securecookie v1.1.2 + github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/hashicorp/hcl/v2 v2.19.1 // indirect + github.com/karlseguin/ccache/v3 v3.0.5 // indirect + github.com/magiconair/properties v1.8.7 // indirect + github.com/mitchellh/go-wordwrap v1.0.1 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/natefinch/wrap v0.2.0 // indirect + github.com/oklog/ulid/v2 v2.1.0 // indirect + github.com/openfga/api/proto v0.0.0-20240807201305-c96ec773cae9 // indirect + github.com/pelletier/go-toml/v2 v2.1.1 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/prometheus/client_golang v1.20.0 // indirect + github.com/prometheus/client_model v0.6.1 // indirect + github.com/prometheus/common v0.55.0 // indirect + github.com/prometheus/procfs v0.15.1 // indirect + github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/sagikazarmark/locafero v0.4.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/sosodev/duration v1.3.1 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.11.0 // indirect + github.com/spf13/cast v1.6.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/spf13/viper v1.18.2 // indirect + github.com/stretchr/objx v0.5.2 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + github.com/theopenlane/echox v0.1.0 + github.com/theopenlane/utils v0.1.0 + github.com/urfave/cli/v2 v2.27.2 // indirect + github.com/vektah/gqlparser/v2 v2.5.16 // indirect + github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 // indirect + github.com/zclconf/go-cty v1.14.1 // indirect + go.opentelemetry.io/otel v1.28.0 // indirect + go.opentelemetry.io/otel/metric v1.28.0 // indirect + go.opentelemetry.io/otel/trace v1.28.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa // indirect + golang.org/x/mod v0.20.0 // indirect + golang.org/x/net v0.28.0 // indirect + golang.org/x/oauth2 v0.22.0 + golang.org/x/sync v0.8.0 // indirect + golang.org/x/sys v0.23.0 // indirect + golang.org/x/text v0.17.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20240725223205-93522f1f2a9f // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240730163845-b1a4ccb954bf // indirect + google.golang.org/grpc v1.65.0 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b3597ab --- /dev/null +++ b/go.sum @@ -0,0 +1,284 @@ +ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43 h1:GwdJbXydHCYPedeeLt4x/lrlIISQ4JTH1mRWuE5ZZ14= +ariga.io/atlas v0.19.1-0.20240203083654-5948b60a8e43/go.mod h1:uj3pm+hUTVN/X5yfdBexHlZv+1Xu5u5ZbZx7+CDavNU= +entgo.io/ent v0.14.0 h1:EO3Z9aZ5bXJatJeGqu/EVdnNr6K4mRq3rWe5owt0MC4= +entgo.io/ent v0.14.0/go.mod h1:qCEmo+biw3ccBn9OyL4ZK5dfpwg++l1Gxwac5B1206A= +github.com/99designs/gqlgen v0.17.49 h1:b3hNGexHd33fBSAd4NDT/c3NCcQzcAVkknhN9ym36YQ= +github.com/99designs/gqlgen v0.17.49/go.mod h1:tC8YFVZMed81x7UJ7ORUwXF4Kn6SXuucFqQBhN8+BU0= +github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= +github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= +github.com/Yamashou/gqlgenc v0.24.0 h1:Aeufjb2zF0XxkeSTAVQ+DfiHL+ney/M2ovShZozBmHw= +github.com/Yamashou/gqlgenc v0.24.0/go.mod h1:3QQD8ZoeEyVXuzqcMDsl8OfCCCTk+ulaxkvFFQDupIA= +github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= +github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/agnivade/levenshtein v1.1.1 h1:QY8M92nrzkmr798gCo3kmMyqXFzdQVpxLlGPRBij0P8= +github.com/agnivade/levenshtein v1.1.1/go.mod h1:veldBMzWxcCG2ZvUTKD2kJNRdCk5hVbJomOvKkmgYbo= +github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZpUGpz5+4FfNmIU+FmZg2P3Xaj2v2bfNWmk= +github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis/v2 v2.33.0 h1:uvTF0EDeu9RLnUEG27Db5I68ESoIxTiXbNUiji6lZrA= +github.com/alicebob/miniredis/v2 v2.33.0/go.mod h1:MhP4a3EU7aENRi9aO+tHfTBZicLqQevyi/DJpoj6mi0= +github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= +github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= +github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ= +github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= +github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY= +github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4= +github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q= +github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4= +github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 h1:rpfIENRNNilwHwZeG5+P150SMrnNEcHYvcCuK6dPZSg= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48 h1:fRzb/w+pyskVMQ+UbP35JkH8yB7MYb4q/qhBarqZE6g= +github.com/dgryski/trifles v0.0.0-20200323201526-dd97f9abfb48/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA= +github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= +github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= +github.com/envoyproxy/protoc-gen-validate v1.0.4 h1:gVPz/FMfvh57HdSJQyvBtF00j8JU4zdyUgIUNhlgg0A= +github.com/envoyproxy/protoc-gen-validate v1.0.4/go.mod h1:qys6tmnRsYrQqIhm2bvKZH4Blx/1gTIZ2UKVY1M+Yew= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4= +github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4= +github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= +github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/google/cel-go v0.20.1 h1:nDx9r8S3L4pE61eDdt8igGj8rf5kjYR3ILxWIpWNi84= +github.com/google/cel-go v0.20.1/go.mod h1:kWcIzTsPX0zmQ+H3TirHstLLf9ep5QTsZBN9u4dOYLg= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= +github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 h1:bkypFPDjIYGfCYD5mRBvpqxfYX1YCS1PXdKYWi8FsN0= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0/go.mod h1:P+Lt/0by1T8bfcF3z737NnSbmxQAppXMRziHUxPOC8k= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-retryablehttp v0.7.7 h1:C8hUCYzor8PIfXHa4UrZkU4VvK8o9ISHxT2Q8+VepXU= +github.com/hashicorp/go-retryablehttp v0.7.7/go.mod h1:pkQpWZeYWskR+D1tR2O5OcBFOxfA7DoAO6xtkuQnHTk= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/hcl/v2 v2.19.1 h1://i05Jqznmb2EXqa39Nsvyan2o5XyMowW5fnCKW5RPI= +github.com/hashicorp/hcl/v2 v2.19.1/go.mod h1:ThLC89FV4p9MPW804KVbe/cEXoQ8NZEh+JtMeeGErHE= +github.com/jarcoal/httpmock v1.3.1 h1:iUx3whfZWVf3jT01hQTO/Eo5sAYtB2/rqaUuOtpInww= +github.com/jarcoal/httpmock v1.3.1/go.mod h1:3yb8rc4BI7TCBhFY8ng0gjuLKJNquuDNiPaZjnENuYg= +github.com/karlseguin/ccache/v3 v3.0.5 h1:hFX25+fxzNjsRlREYsoGNa2LoVEw5mPF8wkWq/UnevQ= +github.com/karlseguin/ccache/v3 v3.0.5/go.mod h1:qxC372+Qn+IBj8Pe3KvGjHPj0sWwEF7AeZVhsNPZ6uY= +github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= +github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lestrrat-go/blackmagic v1.0.2 h1:Cg2gVSc9h7sz9NOByczrbUvLopQmXrfFx//N+AkAr5k= +github.com/lestrrat-go/blackmagic v1.0.2/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU= +github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE= +github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E= +github.com/lestrrat-go/httprc v1.0.6 h1:qgmgIRhpvBqexMJjA/PmwSvhNk679oqD1RbovdCGW8k= +github.com/lestrrat-go/httprc v1.0.6/go.mod h1:mwwz3JMTPBjHUkkDv/IGJ39aALInZLrhBp0X7KGUZlo= +github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI= +github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4= +github.com/lestrrat-go/jwx/v2 v2.1.1 h1:Y2ltVl8J6izLYFs54BVcpXLv5msSW4o8eXwnzZLI32E= +github.com/lestrrat-go/jwx/v2 v2.1.1/go.mod h1:4LvZg7oxu6Q5VJwn7Mk/UwooNRnTHUpXBj2C4j3HNx0= +github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU= +github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= +github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/natefinch/wrap v0.2.0 h1:IXzc/pw5KqxJv55gV0lSOcKHYuEZPGbQrOOXr/bamRk= +github.com/natefinch/wrap v0.2.0/go.mod h1:6gMHlAl12DwYEfKP3TkuykYUfLSEAvHw67itm4/KAS8= +github.com/oklog/ulid/v2 v2.1.0 h1:+9lhoxAP56we25tyYETBBY1YLA2SaoLvUFgrP2miPJU= +github.com/oklog/ulid/v2 v2.1.0/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= +github.com/openfga/api/proto v0.0.0-20240807201305-c96ec773cae9 h1:Y0fIAHrYECcf5lpa/o1AbH21bS7rsco/FoH4A4NGlZE= +github.com/openfga/api/proto v0.0.0-20240807201305-c96ec773cae9/go.mod h1:gil5LBD8tSdFQbUkCQdnXsoeU9kDJdJgbGdHkgJfcd0= +github.com/openfga/go-sdk v0.5.0 h1:1IuAu6Xf4eBxgc2AyMfosK7QzApxuZ5yi7jmFaftnl0= +github.com/openfga/go-sdk v0.5.0/go.mod h1:AoMnFlPw65sU/7O4xOPpCb2vXA8ZD9K9xp2hZjcvt4g= +github.com/openfga/language/pkg/go v0.0.0-20240611203201-b6bbf9c4bb3a h1:0/nEaNWtDb8win9p9GTM3WTt0LcGjg1J/o2LNx6nZ+Y= +github.com/openfga/language/pkg/go v0.0.0-20240611203201-b6bbf9c4bb3a/go.mod h1:mCwEY2IQvyNgfEwbfH0C0ERUwtL8z6UjSAF8zgn5Xbg= +github.com/openfga/openfga v1.5.9 h1:1x+9YdBOzbYPbkEUZjPPYt255GXDUbouC0ConpMRtL8= +github.com/openfga/openfga v1.5.9/go.mod h1:1OF1qR8nXdIirtosRZq0mPx5B6nuY5phPGk61Yh+9Lc= +github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= +github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= +github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.20.0 h1:jBzTZ7B099Rg24tny+qngoynol8LtVYlA2bqx3vEloI= +github.com/prometheus/client_golang v1.20.0/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= +github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= +github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= +github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc= +github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8= +github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= +github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= +github.com/redis/go-redis/v9 v9.6.1 h1:HHDteefn6ZkTtY5fGUE8tj8uy85AHk6zP7CpzIAM0y4= +github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJCQLgE9+RA= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= +github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= +github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= +github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/samber/lo v1.47.0 h1:z7RynLwP5nbyRscyvcD043DWYoOcYRv3mV8lBeqOCLc= +github.com/samber/lo v1.47.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU= +github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys= +github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= +github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= +github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= +github.com/sosodev/duration v1.3.1 h1:qtHBDMQ6lvMQsL15g4aopM4HEfOaYuhWBw3NPTtlqq4= +github.com/sosodev/duration v1.3.1/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= +github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= +github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ= +github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk= +github.com/stoewer/go-strcase v1.3.0 h1:g0eASXYtp+yvN9fK8sH94oCIk0fau9uV1/ZdJ0AVEzs= +github.com/stoewer/go-strcase v1.3.0/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/theopenlane/core v0.1.1 h1:nBJ9NEMUu3CqIVLJsydWs4AKyCuJxaY44BMzBZpRZ7g= +github.com/theopenlane/core v0.1.1/go.mod h1:qEaMYQK5iy3wekSbG6TVE7Nf37o1quqtTNJCd1v9n3s= +github.com/theopenlane/echox v0.1.0 h1:y4Z2shaODCLwXHsHBrY/EkH/2sIuo49xdIfxx7h+Zvg= +github.com/theopenlane/echox v0.1.0/go.mod h1:RaynhPvY9qbLOVlcO7Js1NqZ66+CP9hVBa0c7ehNYA4= +github.com/theopenlane/utils v0.1.0 h1:PjKNn1FuYERYzMuEvdilHJxiiMYkcMlnCqImItrJTK0= +github.com/theopenlane/utils v0.1.0/go.mod h1:37sJeeuIsmMbMFE2nKglmEQUJenTccxh5WxkJtyuZUw= +github.com/urfave/cli/v2 v2.27.2 h1:6e0H+AkS+zDckwPCUrZkKX38mRaau4nL2uipkJpbkcI= +github.com/urfave/cli/v2 v2.27.2/go.mod h1:g0+79LmHHATl7DAcHO99smiR/T7uGLw84w8Y42x+4eM= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= +github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +github.com/vektah/gqlparser/v2 v2.5.16 h1:1gcmLTvs3JLKXckwCwlUagVn/IlV2bwqle0vJ0vy5p8= +github.com/vektah/gqlparser/v2 v2.5.16/go.mod h1:1lz1OeCqgQbQepsGxPVywrjdBHW2T08PUS3pJqepRww= +github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= +github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= +github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= +github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= +github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 h1:+qGGcbkzsfDQNPPe9UDgpxAWQrhbbBXOYJFQDq/dtJw= +github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913/go.mod h1:4aEEwZQutDLsQv2Deui4iYQ6DWTxR14g6m8Wv88+Xqk= +github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= +github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= +github.com/zclconf/go-cty v1.14.1 h1:t9fyA35fwjjUMcmL5hLER+e/rEPqrbCK1/OSE4SI9KA= +github.com/zclconf/go-cty v1.14.1/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE= +go.opentelemetry.io/otel v1.28.0 h1:/SqNcYk+idO0CxKEUOtKQClMK/MimZihKYMruSMViUo= +go.opentelemetry.io/otel v1.28.0/go.mod h1:q68ijF8Fc8CnMHKyzqL6akLO46ePnjkgfIMIjUIX9z4= +go.opentelemetry.io/otel/metric v1.28.0 h1:f0HGvSl1KRAU1DLgLGFjrwVyismPlnuU6JD6bOeuA5Q= +go.opentelemetry.io/otel/metric v1.28.0/go.mod h1:Fb1eVBFZmLVTMb6PPohq3TO9IIhUisDsbJoL/+uQW4s= +go.opentelemetry.io/otel/trace v1.28.0 h1:GhQ9cUuQGmNDd5BTCP2dAvv75RdMxEfTmYejp+lkx9g= +go.opentelemetry.io/otel/trace v1.28.0/go.mod h1:jPyXzNPg6da9+38HEwElrQiHlVMTnVfM3/yv2OlIHaI= +go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0= +go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= +go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw= +golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54= +golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa h1:ELnwvuAXPNtPk1TJRuGkI9fDTwym6AYBu0qzT8AcHdI= +golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ= +golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0= +golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= +golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= +golang.org/x/oauth2 v0.22.0 h1:BzDx2FehcG7jJwgWLELCdmLuxk2i+x9UDpSiss2u0ZA= +golang.org/x/oauth2 v0.22.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM= +golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= +golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/time v0.6.0 h1:eTDhh4ZXt5Qf0augr54TN6suAUudPcawVZeIAPU7D4U= +golang.org/x/time v0.6.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24= +golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ= +google.golang.org/genproto/googleapis/api v0.0.0-20240725223205-93522f1f2a9f h1:b1Ln/PG8orm0SsBbHZWke8dDp2lrCD4jSmfglFpTZbk= +google.golang.org/genproto/googleapis/api v0.0.0-20240725223205-93522f1f2a9f/go.mod h1:AHT0dDg3SoMOgZGnZk29b5xTbPHMoEC8qthmBLJCpys= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240730163845-b1a4ccb954bf h1:liao9UHurZLtiEwBgT9LMOnKYsHze6eA6w1KQCMVN2Q= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240730163845-b1a4ccb954bf/go.mod h1:Ue6ibwXGpU+dqIcODieyLOcgj7z8+IcskoNIgZxtrFY= +google.golang.org/grpc v1.65.0 h1:bs/cUb4lp1G5iImFFd3u5ixQzweKizoZJAwBNLR42lc= +google.golang.org/grpc v1.65.0/go.mod h1:WgYC2ypjlB0EiQi6wdKixMqukr6lBc0Vo+oOgjrM5ZQ= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..37f7bfa --- /dev/null +++ b/renovate.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "config:recommended" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "packageRules": [ + { + "excludePackagePatterns": [ + "github.com/theopenlane/iam" + ] + } + ], + "labels": [ + "dependencies" + ] +} \ No newline at end of file diff --git a/sessions/context.go b/sessions/context.go new file mode 100644 index 0000000..93dce46 --- /dev/null +++ b/sessions/context.go @@ -0,0 +1,98 @@ +package sessions + +import ( + "context" + "strings" + + "github.com/pkg/errors" + + "golang.org/x/oauth2" +) + +// SessionContextKey is the context key for the user claims +var SessionContextKey = &ContextKey{"SessionContextKey"} + +// ContextKey is the key name for the additional context +type ContextKey struct { + name string +} + +// OhAuthTokenFromContext returns the Token from the ctx +func OhAuthTokenFromContext(ctx context.Context) (*oauth2.Token, error) { + token, ok := ctx.Value(SessionContextKey).(*oauth2.Token) + if !ok { + return nil, errors.New("context missing Token") + } + + return token, nil +} + +// ContextWithToken returns a copy of ctx that stores the Token +func ContextWithToken(ctx context.Context, token *oauth2.Token) context.Context { + return context.WithValue(ctx, SessionContextKey, token) +} + +// UserIDFromContext returns the user ID from the ctx +// this function assumes the session data is stored in a string map +func UserIDFromContext(ctx context.Context) (string, error) { + sessionDetails, ok := ctx.Value(SessionContextKey).(*Session[any]) + if !ok { + return "", ErrInvalidSession + } + + sessionID := sessionDetails.GetKey() + + sessionData, ok := sessionDetails.GetOk(sessionID) + if !ok { + return "", ErrInvalidSession + } + + sd, ok := sessionData.(map[string]string) + if !ok { + return "", ErrInvalidSession + } + + userID, ok := sd["userID"] + if !ok { + return "", ErrInvalidSession + } + + return userID, nil +} + +// ContextWithUserID returns a copy of ctx that stores the user ID +func ContextWithUserID(ctx context.Context, userID string) context.Context { + if strings.TrimSpace(userID) == "" { + return ctx + } + + return context.WithValue(ctx, SessionContextKey, userID) +} + +// SessionToken returns the encoded session token +func SessionToken(ctx context.Context) (string, error) { + sd := getSessionDataFromContext(ctx) + if sd == nil { + return "", ErrInvalidSession + } + + sd.mu.Lock() + defer sd.mu.Unlock() + + return sd.store.EncodeCookie(sd) +} + +// addSessionDataToContext adds the session details to the context +func (s *Session[P]) addSessionDataToContext(ctx context.Context) context.Context { + return context.WithValue(ctx, SessionContextKey, s) +} + +// getSessionDataFromContext gets the session information from the context +func getSessionDataFromContext(ctx context.Context) *Session[map[string]any] { + c, ok := ctx.Value(SessionContextKey).(*Session[map[string]any]) + if !ok { + return nil + } + + return c +} diff --git a/sessions/cookie.go b/sessions/cookie.go new file mode 100644 index 0000000..ea6c97c --- /dev/null +++ b/sessions/cookie.go @@ -0,0 +1,176 @@ +package sessions + +import ( + "encoding/base64" + "net/http" + "time" +) + +const ( + defaultMaxAgeSeconds = 60 * 60 // 1 hour (in seconds) +) + +var ( + DefaultCookieName = "__Secure-SessionId" + DevCookieName = "temporary-cookie" +) + +// DefaultCookieConfig configures http.Cookie creation for production (AKA default secure values are set) +var DefaultCookieConfig = &CookieConfig{ + Path: "/", + Domain: "", + MaxAge: defaultMaxAgeSeconds, + HTTPOnly: true, + Secure: true, + SameSite: http.SameSiteStrictMode, +} + +// DebugCookieConfig configures http.Cookie creation for debugging +var DebugCookieConfig = &CookieConfig{ + Path: "/", + MaxAge: defaultMaxAgeSeconds, + HTTPOnly: true, + Secure: false, // allow to work over http + SameSite: http.SameSiteLaxMode, +} + +// DebugOnlyCookieConfig is different in that it's not a receiver and the name is set, so it can be called directly +var DebugOnlyCookieConfig = CookieConfig{ + Name: DevCookieName, + Path: "/", + MaxAge: defaultMaxAgeSeconds, + HTTPOnly: true, + Secure: false, // allow to work over http + SameSite: http.SameSiteLaxMode, +} + +// CookieConfig configures http.Cookie creation +type CookieConfig struct { + Name string + // Cookie domain/path scope (leave zeroed for requested resource scope) + // Defaults to the domain name of the responding server when unset + Domain string + // Defaults to the path of the responding URL when unset + Path string + // MaxAge=0 means no 'Max-Age' attribute specified. + // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'. + // MaxAge>0 means Max-Age attribute present and given in seconds + MaxAge int + // cookie may only be transferred over HTTPS. Recommend true + Secure bool + // browser should prohibit non-HTTP (i.e. javascript) cookie access. Recommend true + HTTPOnly bool + // prohibit sending in cross-site requests with SameSiteLaxMode or SameSiteStrictMode + SameSite http.SameSite +} + +// NewCookie returns a new chocolate chip http.Cookie with the given name, value, and properties from config +func NewCookie(name, value string, config *CookieConfig) *http.Cookie { + if name != "" { + cookie := &http.Cookie{ + Name: name, + Value: value, + Path: config.Path, + Domain: config.Domain, + MaxAge: config.MaxAge, + HttpOnly: config.HTTPOnly, + Secure: config.Secure, + SameSite: config.SameSite, + } + + if expires, ok := expiresTime(config.MaxAge); ok { + cookie.Expires = expires + } + + return cookie + } + + if name == "" { + cookie := &http.Cookie{ + Name: config.Name, + Value: value, + Path: config.Path, + Domain: config.Domain, + MaxAge: config.MaxAge, + HttpOnly: config.HTTPOnly, + Secure: config.Secure, + SameSite: config.SameSite, + } + + if expires, ok := expiresTime(config.MaxAge); ok { + cookie.Expires = expires + } + + return cookie + } + + return nil +} + +// expiresTime converts a maxAge time in seconds to a time.Time in the future +// ref http://golang.org/src/net/http/cookie.go?s=618:801#L23 +func expiresTime(maxAge int) (time.Time, bool) { + if maxAge > 0 { + d := time.Duration(maxAge) * time.Second + return time.Now().Add(d), true + } else if maxAge < 0 { + return time.Unix(1, 0), true + } + + return time.Time{}, false +} + +// GetCookie function retrieves a specific cookie from an HTTP request +func GetCookie(r *http.Request, cookieName string) (*http.Cookie, error) { + return r.Cookie(cookieName) +} + +// CookieExpired checks to see if a cookie is expired +func CookieExpired(cookie *http.Cookie) bool { + if !cookie.Expires.IsZero() && cookie.Expires.Before(time.Now()) { + return true + } + + if cookie.MaxAge < 0 { + return true + } + + return false +} + +// SetCookieB64 function sets a base64-encoded cookie with the given name and value in the HTTP response +func SetCookieB64(w http.ResponseWriter, body []byte, cookieName string, v CookieConfig) string { + cookieValue := base64.StdEncoding.EncodeToString(body) + // set the cookie + SetCookie(w, cookieValue, cookieName, v) + + return cookieValue +} + +// SetCookie function sets a cookie with the given value and name +func SetCookie(w http.ResponseWriter, value string, cookieName string, v CookieConfig) { + http.SetCookie(w, &http.Cookie{ + Name: cookieName, + Value: value, + Domain: v.Domain, + Path: v.Path, + MaxAge: v.MaxAge, + Secure: v.Secure, + SameSite: v.SameSite, + HttpOnly: v.HTTPOnly, + }) +} + +// RemoveCookie function removes a cookie from the HTTP response +func RemoveCookie(w http.ResponseWriter, cookieName string, v CookieConfig) { + http.SetCookie(w, &http.Cookie{ + Name: cookieName, + Value: "", + Domain: v.Domain, + Path: v.Path, + MaxAge: -1, + Secure: v.Secure, + SameSite: v.SameSite, + HttpOnly: v.HTTPOnly, + }) +} diff --git a/sessions/cookiestore.go b/sessions/cookiestore.go new file mode 100644 index 0000000..cf1dfa3 --- /dev/null +++ b/sessions/cookiestore.go @@ -0,0 +1,135 @@ +package sessions + +import ( + "net/http" + "net/url" + + "github.com/gorilla/securecookie" +) + +const ( + UserIDKey = "userID" + ExternalUserIDKey = "externalUserID" + SessionNameKey = "name" + UserTypeKey = "userType" + UsernameKey = "username" + EmailKey = "email" + WebAuthnKey = "webauthn" +) + +type Store[T any] interface { + // New returns a new named Session + New(name string) *Session[T] + // Get a named Session from the request + Get(req *http.Request, name string) (*Session[T], error) + // Save writes a Session to the ResponseWriter + Save(w http.ResponseWriter, session *Session[T]) error + // Destroy removes (expires) a named Session + Destroy(w http.ResponseWriter, name string) + // GetSessionIDFromCookie returns the key, which should be the sessionID, in the map + GetSessionIDFromCookie(sess *Session[T]) string + // GetSessionDataFromCookie returns the value stored map + GetSessionDataFromCookie(sess *Session[T]) any + // EncodeCookie encodes the cookie + EncodeCookie(session *Session[T]) (string, error) +} + +var _ Store[any] = &cookieStore[any]{} + +// cookieStore stores Sessions in secure cookies (i.e. client-side) +type cookieStore[T any] struct { + config *CookieConfig + // encodes and decodes signed and optionally encrypted cookie values + codecs []securecookie.Codec +} + +// NewCookieStore returns a new Store that signs and optionally encrypts +// session state in http cookies. +func NewCookieStore[T any](config *CookieConfig, keyPairs ...[]byte) Store[T] { + if config == nil { + config = DefaultCookieConfig + } + + return &cookieStore[T]{ + config: config, + codecs: securecookie.CodecsFromPairs(keyPairs...), + } +} + +// New returns a new named Session +func (s *cookieStore[T]) New(name string) *Session[T] { + return NewSession[T](s, name) +} + +// Get returns the named Session from the Request. Returns an error if the +// session cookie cannot be found, the cookie verification fails, or an error +// occurs decoding the cookie value. +func (s *cookieStore[T]) Get(req *http.Request, name string) (session *Session[T], err error) { + cookie, err := req.Cookie(name) + if err == nil { + // decode the session cookie, UIs like to encode the cookie value + decodedSession, err := url.QueryUnescape(cookie.Value) + if err != nil { + return nil, err + } + + session = s.New(name) + if err = securecookie.DecodeMulti(name, decodedSession, &session.values, s.codecs...); err != nil { + return nil, err + } + } + + return session, err +} + +// GetSessionIDFromCookie gets the cookies from the http.Request and gets the key (session ID) from the values +func (s *cookieStore[T]) GetSessionIDFromCookie(sess *Session[T]) string { + for k := range sess.values { + return k + } + + return "" +} + +// GetSessionDataFromCookie gets the cookies from the http.Request and gets session values +func (s *cookieStore[T]) GetSessionDataFromCookie(sess *Session[T]) any { + for _, v := range sess.values { + return v + } + + return "" +} + +// Save adds or updates the Session on the response via a signed and optionally +// encrypted session cookie. Session Values are encoded into the cookie value +// and the session Config sets cookie properties. +func (s *cookieStore[T]) Save(w http.ResponseWriter, session *Session[T]) error { + cookieValue, err := securecookie.EncodeMulti(session.Name(), &session.values, s.codecs...) + if err != nil { + return err + } + + http.SetCookie(w, NewCookie(session.Name(), cookieValue, s.config)) + + return nil +} + +func (s *cookieStore[T]) EncodeCookie(session *Session[T]) (string, error) { + return securecookie.EncodeMulti(session.Name(), &session.values, s.codecs...) +} + +// Destroy deletes the Session with the given name by issuing an expired +// session cookie with the same name. +func (s *cookieStore[T]) Destroy(w http.ResponseWriter, name string) { + http.SetCookie(w, NewCookie(name, "", &CookieConfig{MaxAge: -1, Path: s.config.Path})) +} + +// NewSessionCookie creates a cookie from a session id +func NewSessionCookie(session string) *http.Cookie { + return NewCookie(DefaultCookieName, session, DefaultCookieConfig) +} + +// NewDevSessionCookie creates a cookie from a session id using the dev cookie name +func NewDevSessionCookie(session string) *http.Cookie { + return NewCookie(DevCookieName, session, DefaultCookieConfig) +} diff --git a/sessions/cookiestore_test.go b/sessions/cookiestore_test.go new file mode 100644 index 0000000..31ca851 --- /dev/null +++ b/sessions/cookiestore_test.go @@ -0,0 +1,265 @@ +package sessions_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/theopenlane/utils/ulids" + + "github.com/theopenlane/iam/sessions" +) + +func TestNew(t *testing.T) { + tests := []struct { + name string + sessionName string + expectedName string + }{ + { + name: "happy path", + sessionName: "huddle", + expectedName: "huddle", + }, + { + name: "empty name, use default", + sessionName: "", + expectedName: "", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // test with a string first + cs := sessions.NewCookieStore[string](sessions.DefaultCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + session := cs.New(tc.sessionName) + + assert.Equal(t, tc.expectedName, session.Name()) + + // Again, with a string map + csMap := sessions.NewCookieStore[map[string]string](sessions.DefaultCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + sessionMap := csMap.New(tc.sessionName) + + assert.Equal(t, tc.expectedName, sessionMap.Name()) + }) + } +} + +func TestNewSessionCookie(t *testing.T) { + tests := []struct { + name string + sessionName string + session string + userID string + }{ + { + name: "happy path", + sessionName: "__Host-meow", + session: ulids.New().String(), + userID: ulids.New().String(), + }, + { + name: "empty string still results in session", + sessionName: "__Host-woof", + session: "", + userID: "", + }, + { + name: "empty session name", + sessionName: "__Host-meow", + session: "", + userID: "", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // test with a string first + cs := sessions.NewCookieStore[string](sessions.DebugCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + cooky := cs.New(tc.name) + + cooky.Set(sessions.SessionNameKey, tc.name) + cooky.Set("session", tc.session) + + name := cooky.Get(sessions.SessionNameKey) + session := cooky.Get("session") + + assert.Equal(t, tc.name, name) + assert.Equal(t, tc.session, session) + + // Again, with a string map + csMap := sessions.NewCookieStore[map[string]string](sessions.DebugCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + cookyMap := csMap.New(tc.sessionName) + + cookyMap.Set(tc.session, + map[string]string{ + sessions.SessionNameKey: tc.sessionName, + sessions.UserIDKey: tc.userID, + }, + ) + + assert.Equal(t, tc.sessionName, cookyMap.Get(tc.session)[sessions.SessionNameKey]) + assert.Equal(t, tc.userID, cookyMap.Get(tc.session)[sessions.UserIDKey]) + }) + } +} + +func TestSaveGet(t *testing.T) { + tests := []struct { + name string + sessionName string + session string + userID string + }{ + { + name: "happy path", + sessionName: "__Host-meow", + session: ulids.New().String(), + userID: "mitb", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + cs := sessions.NewCookieStore[map[string]string](sessions.DebugCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + // Set writer for tests that write on the response + recorder := httptest.NewRecorder() + + session := sessions.NewSession(cs, tc.sessionName) + + setSessionMap := map[string]string{} + setSessionMap[sessions.UserIDKey] = tc.userID + setSessionMap[sessions.SessionNameKey] = tc.sessionName + + session.Set(tc.session, setSessionMap) + + err := cs.Save(recorder, session) + require.NoError(t, err) + + // Copy the Cookie over to a new Request + res := recorder.Result() + defer res.Body.Close() + + cooky := res.Header["Set-Cookie"] + request := &http.Request{Header: http.Header{"Cookie": cooky}} + + sess, err := cs.Get(request, tc.sessionName) + require.NoError(t, err) + assert.Equal(t, tc.session, sess.GetKey()) + assert.Equal(t, tc.sessionName, sess.Get(sess.GetKey())[sessions.SessionNameKey]) + }) + } +} + +func TestGetSessionIDFromCookie(t *testing.T) { + tests := []struct { + name string + sessionName string + userID string + }{ + { + name: "happy path", + sessionName: "__Host-meow", + userID: "mitb", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + cs := sessions.NewCookieStore[map[string]string](sessions.DebugCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + // Set writer for tests that write on the response + recorder := httptest.NewRecorder() + + session := cs.New(tc.sessionName) + sessionID := sessions.GenerateSessionID() + + setSessionMap := map[string]string{} + setSessionMap[sessions.UserIDKey] = tc.userID + setSessionMap[sessions.SessionNameKey] = tc.sessionName + + session.Set(sessionID, setSessionMap) + + err := cs.Save(recorder, session) + require.NoError(t, err) + + // Copy the Cookie over to a new Request + res := recorder.Result() + defer res.Body.Close() + + cooky := res.Header["Set-Cookie"] + request := &http.Request{Header: http.Header{"Cookie": cooky}} + + session, err = cs.Get(request, tc.sessionName) + require.NoError(t, err) + + id := cs.GetSessionIDFromCookie(session) + + require.Equal(t, sessionID, id) + }) + } +} + +func TestGetSessionDataFromCookie(t *testing.T) { + tests := []struct { + name string + sessionName string + userID string + }{ + { + name: "happy path", + sessionName: "__Host-meow", + userID: "mitb", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + cs := sessions.NewCookieStore[map[string]string](sessions.DebugCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + // Set writer for tests that write on the response + recorder := httptest.NewRecorder() + + session := cs.New(tc.sessionName) + sessionID := sessions.GenerateSessionID() + + setSessionMap := map[string]string{} + setSessionMap[sessions.UserIDKey] = tc.userID + setSessionMap[sessions.SessionNameKey] = tc.sessionName + + session.Set(sessionID, setSessionMap) + + err := cs.Save(recorder, session) + require.NoError(t, err) + + // Copy the Cookie over to a new Request + res := recorder.Result() + defer res.Body.Close() + + cooky := res.Header["Set-Cookie"] + request := &http.Request{Header: http.Header{"Cookie": cooky}} + + session, err = cs.Get(request, tc.sessionName) + require.NoError(t, err) + + sd := cs.GetSessionDataFromCookie(session) + + require.Equal(t, setSessionMap, sd) + }) + } +} diff --git a/sessions/doc.go b/sessions/doc.go new file mode 100644 index 0000000..32598f9 --- /dev/null +++ b/sessions/doc.go @@ -0,0 +1,2 @@ +// Package sessions manages users sessions +package sessions diff --git a/sessions/errors.go b/sessions/errors.go new file mode 100644 index 0000000..ae00d89 --- /dev/null +++ b/sessions/errors.go @@ -0,0 +1,8 @@ +package sessions + +import "errors" + +var ( + // ErrInvalidSession is returned when the session is invalid + ErrInvalidSession = errors.New("invalid session provided") +) diff --git a/sessions/middleware.go b/sessions/middleware.go new file mode 100644 index 0000000..9202f07 --- /dev/null +++ b/sessions/middleware.go @@ -0,0 +1,211 @@ +package sessions + +import ( + "context" + "net/http" + "time" + + "github.com/redis/go-redis/v9" + echo "github.com/theopenlane/echox" + "github.com/theopenlane/echox/middleware" + "go.uber.org/zap" +) + +// SessionConfig is used to configure session management +type SessionConfig struct { + // Skipper is a function that determines whether a particular request should be skipped or not + Skipper middleware.Skipper + // BeforeFunc defines a function which is executed just before the middleware + BeforeFunc middleware.BeforeFunc + // SessionManager is responsible for managing the session cookies. It handles the creation, retrieval, and deletion of + // session cookies for each user session + SessionManager Store[map[string]any] + // CookieConfig contains the cookie settings for sessions + CookieConfig *CookieConfig + // RedisStore is used to store and retrieve session data in a persistent manner such as to a redis backend + RedisStore PersistentStore + // RedisClient establishes a connection to a Redis server and perform operations such as storing and retrieving data + RedisClient *redis.Client + // Logger is used to log errors in the middleware + Logger *zap.SugaredLogger +} + +// Option allows users to optionally supply configuration to the session middleware. +type Option func(opts *SessionConfig) + +// NewSessionConfig creates a new session config with options +func NewSessionConfig(sm Store[map[string]any], opts ...Option) (c SessionConfig) { + c = SessionConfig{ + Skipper: middleware.DefaultSkipper, // default skipper always returns false + Logger: zap.NewNop().Sugar(), // default logger if none is provided is a no-op + SessionManager: sm, // session manager should always be provided + } + + for _, opt := range opts { + opt(&c) + } + + if c.RedisClient != nil { + c.RedisStore = NewStore(c.RedisClient) + } + + return c +} + +// WithPersistence allows the user to specify a redis client for the middleware to persist sessions +func WithPersistence(client *redis.Client) Option { + return func(opts *SessionConfig) { + opts.RedisClient = client + } +} + +// WithLogger allows the user to specify a zap logger for the middleware +func WithLogger(l *zap.SugaredLogger) Option { + return func(opts *SessionConfig) { + opts.Logger = l + } +} + +// WithSkipperFunc allows the user to specify a skipper function for the middleware +func WithSkipperFunc(skipper middleware.Skipper) Option { + return func(opts *SessionConfig) { + opts.Skipper = skipper + } +} + +// WithBeforeFunc allows the user to specify a function to happen before the middleware +func WithBeforeFunc(before middleware.BeforeFunc) Option { + return func(opts *SessionConfig) { + opts.BeforeFunc = before + } +} + +// CreateAndStoreSession creates the session values with user ID and sets the cookie stores the session in +// the persistent store (redis) +func (sc *SessionConfig) CreateAndStoreSession(ctx echo.Context, userID string) error { + setSessionMap := map[string]any{} + setSessionMap[UserIDKey] = userID + + c, err := sc.SaveAndStoreSession(ctx.Request().Context(), ctx.Response().Writer, setSessionMap, userID) + if err != nil { + return err + } + + ctx.SetRequest(ctx.Request().WithContext(c)) + + return nil +} + +// SaveAndStoreSession saves the session to the cookie and to the persistent store (redis) with the provided map of values +func (sc *SessionConfig) SaveAndStoreSession(ctx context.Context, w http.ResponseWriter, sessionMap map[string]any, userID string) (context.Context, error) { + session := sc.SessionManager.New(sc.CookieConfig.Name) + sessionID := GenerateSessionID() + + session.Set(sessionID, sessionMap) + + // Add session to context + c := session.addSessionDataToContext(ctx) + + if err := session.Save(w); err != nil { + return c, err + } + + ttl := time.Duration(sc.CookieConfig.MaxAge * int(time.Second)) + if err := sc.RedisStore.StoreSessionWithExpiration(c, sessionID, userID, ttl); err != nil { + return c, err + } + + return c, nil +} + +// LoadAndSave is a middleware function that loads and saves session data using a +// provided session manager. It takes a `SessionManager` as input and returns a middleware function +// that can be used with an Echo framework application +func LoadAndSave(sm Store[map[string]any], opts ...Option) echo.MiddlewareFunc { + c := NewSessionConfig(sm, opts...) + + return LoadAndSaveWithConfig(c) +} + +// LoadAndSaveWithConfig is a middleware that loads and saves session data +// using a provided session manager configuration +// It takes a `SessionConfig` struct as input, which contains the skipper function and the session manager +func LoadAndSaveWithConfig(config SessionConfig) echo.MiddlewareFunc { + if config.Skipper == nil { + config.Skipper = middleware.DefaultSkipper + } + + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + // if skipper function returns true, skip this middleware + if config.Skipper(c) { + return next(c) + } + + // execute any before functions + if config.BeforeFunc != nil { + config.BeforeFunc(c) + } + + // get session from request cookies + session, err := config.SessionManager.Get(c.Request(), config.CookieConfig.Name) + if err != nil { + config.Logger.Errorw("unable to get session", "error", err) + + return err + } + + // get the session id from the session data + sessionID := config.SessionManager.GetSessionIDFromCookie(session) + sessionData := config.SessionManager.GetSessionDataFromCookie(session) + + // check session token on request matches cache + userIDFromCookie := sessionData.(map[string]any)[UserIDKey] + + // lookup userID in cache to ensure tokens match + userID, err := config.RedisStore.GetSession(c.Request().Context(), sessionID) + if err != nil { + config.Logger.Errorw("unable to get session from store", "error", err) + + return err + } + + if userIDFromCookie != userID { + config.Logger.Errorw("sessions do not match", "cookie", userIDFromCookie, "store", userID) + + return err + } + + // Add session to context to be used in request paths + ctx := session.addSessionDataToContext(c.Request().Context()) + c.SetRequest(c.Request().WithContext(ctx)) + + c.Response().Before(func() { + // refresh and save session cookie + if err := config.CreateAndStoreSession(c, sessionID); err != nil { + config.Logger.Errorw("unable to create and store new session", "error", err) + + panic(err) + } + + addHeaderIfMissing(c.Response(), "Cache-Control", `no-cache="Set-Cookie"`) + addHeaderIfMissing(c.Response(), "Vary", "Cookie") + }) + + return next(c) + } + } +} + +// addHeaderIfMissing function is used to add a header to the HTTP response if it is not already +// present. It takes in the response writer (`http.ResponseWriter`), the header key, and the header +// value as parameters +func addHeaderIfMissing(w http.ResponseWriter, key, value string) { + for _, h := range w.Header()[key] { + if h == value { + return + } + } + + w.Header().Add(key, value) +} diff --git a/sessions/redisstore.go b/sessions/redisstore.go new file mode 100644 index 0000000..39ae99b --- /dev/null +++ b/sessions/redisstore.go @@ -0,0 +1,74 @@ +package sessions + +import ( + "context" + "sync" + "time" + + "github.com/redis/go-redis/v9" +) + +// PersistentStore is defining an interface for session store +type PersistentStore interface { + Exists(ctx context.Context, key string) (int64, error) + GetSession(ctx context.Context, key string) (string, error) + StoreSession(ctx context.Context, key, value string) error + StoreSessionWithExpiration(ctx context.Context, key, value string, ttl time.Duration) error + DeleteSession(ctx context.Context, key string) error +} + +var _ PersistentStore = &persistentStore{} + +// persistentStore stores Sessions in a persisent data store (redis) +type persistentStore struct { + client *redis.Client + mu sync.Mutex +} + +// NewStore returns a new Store that stores to a persistent backend (redis) +func NewStore(client *redis.Client) PersistentStore { + return &persistentStore{ + client: client, + } +} + +// Exists checks to see if there is an existing session for the user +func (s *persistentStore) Exists(ctx context.Context, key string) (int64, error) { + s.mu.Lock() + defer s.mu.Unlock() + + return s.client.Exists(ctx, key).Result() +} + +// GetSession checks to see if there is an existing session for the user +func (s *persistentStore) GetSession(ctx context.Context, key string) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + + return s.client.Get(ctx, key).Result() +} + +// StoreSession is used to store a session in the store with a key and value +// the TTL is set to the defaultMaxAgeSeconds to align with the session cookie +func (s *persistentStore) StoreSession(ctx context.Context, key, value string) error { + s.mu.Lock() + defer s.mu.Unlock() + + return s.client.Set(ctx, key, value, defaultMaxAgeSeconds).Err() +} + +// StoreSessionWithExpiration is used to store a session in the store with a key and value and a time to live +func (s *persistentStore) StoreSessionWithExpiration(ctx context.Context, key, value string, ttl time.Duration) error { + s.mu.Lock() + defer s.mu.Unlock() + + return s.client.Set(ctx, key, value, ttl).Err() +} + +// DeleteSession is used to delete a session from the store +func (s *persistentStore) DeleteSession(ctx context.Context, userID string) error { + s.mu.Lock() + defer s.mu.Unlock() + + return s.client.Del(ctx, userID).Err() +} diff --git a/sessions/redisstore_test.go b/sessions/redisstore_test.go new file mode 100644 index 0000000..06b0175 --- /dev/null +++ b/sessions/redisstore_test.go @@ -0,0 +1,189 @@ +package sessions_test + +import ( + "context" + "log" + "testing" + "time" + + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/theopenlane/utils/ulids" + + "github.com/theopenlane/iam/sessions" +) + +var ( + mr *miniredis.Miniredis +) + +func TestExists(t *testing.T) { + tests := []struct { + name string + userID string + exists int64 + }{ + { + name: "happy path", + userID: "MITB", + exists: 1, + }, + { + name: "session does not exist", + userID: "SITB", + exists: 0, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + rc := newRedisClient() + ps := sessions.NewStore(rc) + + sessionID := sessions.GenerateSessionID() + if tc.exists == int64(1) { + err := ps.StoreSession(context.Background(), sessionID, tc.userID) + require.NoError(t, err) + } + + exists, err := ps.Exists(context.Background(), sessionID) + require.NoError(t, err) + assert.Equal(t, tc.exists, exists) + }) + } +} + +func TestGetSession(t *testing.T) { + tests := []struct { + name string + userID string + session string + exists bool + }{ + { + name: "happy path", + userID: "MITB", + session: ulids.New().String(), + exists: true, + }, + { + name: "session does not exist", + userID: "SITB", + exists: false, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + rc := newRedisClient() + ps := sessions.NewStore(rc) + + if tc.exists { + // store session in redis if the test expects it + err := ps.StoreSession(context.Background(), tc.session, tc.userID) + require.NoError(t, err) + } + + // get stored value from redis + value, err := ps.GetSession(context.Background(), tc.session) + + if tc.exists { + require.NoError(t, err) + assert.Equal(t, tc.userID, value) + } else { + assert.Error(t, err) + } + }) + } +} + +func TestStoreSessionWithExpiration(t *testing.T) { + tests := []struct { + name string + userID string + session string + ttl time.Duration + }{ + { + name: "happy path", + userID: "MITB", + session: ulids.New().String(), + ttl: 1 * time.Second, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + rc := newRedisClient() + ps := sessions.NewStore(rc) + + err := ps.StoreSessionWithExpiration(context.Background(), tc.session, tc.userID, tc.ttl) + require.NoError(t, err) + + sessionID, err := ps.GetSession(context.Background(), tc.session) + assert.NoError(t, err) + assert.NotEmpty(t, sessionID) + + // wait for the session to expire + mr.FastForward(tc.ttl) + sessionID, err = ps.GetSession(context.Background(), tc.session) + assert.Error(t, err) + assert.Empty(t, sessionID) + }) + } +} + +func TestDeleteSession(t *testing.T) { + tests := []struct { + name string + userID string + session string + exists bool + }{ + { + name: "happy path", + userID: "MITB", + session: ulids.New().String(), + exists: true, + }, + { + name: "session does not exist, should not error", + userID: "SITB", + exists: false, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + rc := newRedisClient() + ps := sessions.NewStore(rc) + + if tc.exists { + err := ps.StoreSession(context.Background(), tc.session, tc.userID) + require.NoError(t, err) + } + + err := ps.DeleteSession(context.Background(), tc.userID) + require.NoError(t, err) + }) + } +} + +func newRedisClient() *redis.Client { + var err error + + mr, err = miniredis.Run() + if err != nil { + log.Fatalf("an error '%s' was not expected when opening a stub database connection", err) + } + + client := redis.NewClient(&redis.Options{ + Addr: mr.Addr(), + DisableIndentity: true, // # spellcheck:off + }) + + return client +} diff --git a/sessions/sessions.go b/sessions/sessions.go new file mode 100644 index 0000000..5f1e69f --- /dev/null +++ b/sessions/sessions.go @@ -0,0 +1,86 @@ +package sessions + +import ( + "net/http" + "sync" + + "github.com/theopenlane/utils/ulids" +) + +// Config contains the configuration for the session store +type Config struct { + // SigningKey must be a 16, 32, or 64 character string used to encode the cookie + SigningKey string `json:"signingKey" koanf:"signingKey" default:"my-signing-secret"` + // EncryptionKey must be a 16, 32, or 64 character string used to encode the cookie + EncryptionKey string `json:"encryptionKey" koanf:"encryptionKey" default:"encryptionsecret"` + // Domain is the domain for the cookie, leave empty to use the default value of the server + Domain string `json:"domain" koanf:"domain" default:""` +} + +// Session represents state values maintained in a sessions Store +type Session[T any] struct { + name string + values map[string]T + mu sync.Mutex + store Store[T] +} + +// NewSession returns a new Session. +func NewSession[T any](store Store[T], name string) *Session[T] { + return &Session[T]{ + name: name, + values: make(map[string]T), + store: store, + } +} + +func (s *Session[T]) SetName(name string) { + s.name = name +} + +// Name returns the name of the session. +func (s *Session[T]) Name() string { + return s.name +} + +// Set sets a key/value pair in the session state. +func (s *Session[T]) Set(key string, value T) { + s.values[key] = value +} + +// Get returns the state value for the given key. +func (s *Session[T]) Get(key string) T { + return s.values[key] +} + +// GetKey returns the first key +func (s *Session[T]) GetKey() string { + for k := range s.values { + return k + } + + return "" +} + +// GetOk returns the state value for the given key and whether they key exists. +func (s *Session[T]) GetOk(key string) (T, bool) { + value, ok := s.values[key] + return value, ok +} + +// Save adds or updates the session. Identical to calling +// store.Save(w, session). +func (s *Session[T]) Save(w http.ResponseWriter) error { + return s.store.Save(w, s) +} + +// Destroy destroys the session. Identical to calling +// store.Destroy(w, session.name). +func (s *Session[T]) Destroy(w http.ResponseWriter) { + s.store.Destroy(w, s.name) +} + +// GenerateSessionID returns a random ulid +func GenerateSessionID() string { + return ulids.New().String() +} diff --git a/sessions/sessions_test.go b/sessions/sessions_test.go new file mode 100644 index 0000000..8f6312b --- /dev/null +++ b/sessions/sessions_test.go @@ -0,0 +1,109 @@ +package sessions_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/theopenlane/utils/ulids" + + "github.com/theopenlane/iam/sessions" +) + +func TestSet(t *testing.T) { + tests := []struct { + name string + sessionName string + + userID string + session string + }{ + { + name: "happy path", + sessionName: "__Secure-SessionId", + userID: "01HMDBSNBGH4DTEP0SR8118Y96", + session: ulids.New().String(), + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // with a string first + cs := sessions.NewCookieStore[string](sessions.DebugCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + session := cs.New(tc.sessionName) + + // Set sessions + session.Set(tc.userID, tc.session) + + assert.Equal(t, tc.session, session.Get(tc.userID)) + + // Again, with a string map + csMap := sessions.NewCookieStore[map[string]string](sessions.DebugCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + sessionMap := csMap.New(tc.sessionName) + + // Set sessions + sessionMap.Set(tc.session, map[string]string{sessions.UserIDKey: tc.userID}) + + assert.Equal(t, tc.userID, sessionMap.Get(tc.session)[sessions.UserIDKey]) + }) + } +} + +func TestGetOk(t *testing.T) { + tests := []struct { + name string + sessionName string + userID string + session string + }{ + { + name: "happy path", + sessionName: "__Secure-SessionId", + userID: "01HMDBSNBGH4DTEP0SR8118Y96", + session: ulids.New().String(), + }, + { + name: "another session name", + sessionName: "MeOWzErZ!", + userID: ulids.New().String(), + session: "01HMDBSNBGH4DTEP0SR8118Y96", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // test with a string + cs := sessions.NewCookieStore[string](sessions.DebugCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + s := cs.New(tc.sessionName) + + s.Set(sessions.UserIDKey, tc.userID) + s.Set("session", tc.session) + + uID, ok := s.GetOk(sessions.UserIDKey) + assert.True(t, ok) + + sess, ok := s.GetOk("session") + assert.True(t, ok) + + assert.Equal(t, tc.userID, uID) + assert.Equal(t, tc.session, sess) + + // Again, but with a string map this time + csMap := sessions.NewCookieStore[map[string]string](sessions.DebugCookieConfig, + []byte("my-signing-secret"), []byte("encryptionsecret")) + + sMap := csMap.New(tc.sessionName) + sMap.Set(tc.session, map[string]string{sessions.UserIDKey: tc.userID}) + + sessMap, ok := sMap.GetOk(tc.session) + assert.True(t, ok) + assert.Equal(t, tc.userID, sessMap[sessions.UserIDKey]) + }) + } +} diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 0000000..5366c0e --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,16 @@ +sonar.projectKey=theopenlane_iam +sonar.organization=theopenlane + +sonar.projectName=iam +sonar.projectVersion=1.0 + +sonar.sources=. + +sonar.exclusions= +sonar.tests=. +sonar.test.inclusions=*_test.go +sonar.exclusions=entfga/_examples/**,mockery/** + +sonar.sourceEncoding=UTF-8 +sonar.go.coverage.reportPaths=coverage.out +sonar.externalIssuesReportPaths=results.txt \ No newline at end of file