This is an autogenerated Go SDK for OpenFGA. It provides a wrapper around the OpenFGA API definition.
- About OpenFGA
- Resources
- Installation
- Getting Started
- Contributing
- License
OpenFGA is an open source Fine-Grained Authorization solution inspired by Google's Zanzibar paper. It was created by the FGA team at Auth0 based on Auth0 Fine-Grained Authorization (FGA), available under a permissive license (Apache-2) and welcomes community contributions.
OpenFGA is designed to make it easy for application builders to model their permission layer, and to add and integrate fine-grained authorization into their applications. OpenFGA’s design is optimized for reliability and low latency at a high scale.
- OpenFGA Documentation
- OpenFGA API Documentation
- OpenFGA Community
- Zanzibar Academy
- Google's Zanzibar Paper (2019)
To install:
go get -u github.com/openfga/go-sdk
In your code, import the module and use it:
import "github.com/openfga/go-sdk"
func Main() {
configuration, err := openfga.NewConfiguration(openfga.Configuration{})
}
You can then run
go mod tidy
to update go.mod
and go.sum
if you are using them.
Learn how to initialize your SDK
We strongly recommend you initialize the OpenFgaClient
only once and then re-use it throughout your app, otherwise you will incur the cost of having to re-initialize multiple times or at every request, the cost of reduced connection pooling and re-use, and would be particularly costly in the client credentials flow, as that flow will be preformed on every request.
The
openfgaClient
will by default retry API requests up to 15 times on 429 and 5xx errors.
import (
. "github.com/openfga/go-sdk/client"
"os"
)
func main() {
fgaClient, err := NewSdkClient(&ClientConfiguration{
ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example
StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
AuthorizationModelId: os.Getenv("FGA_MODEL_ID"), // optional, recommended to be set for production
})
if err != nil {
// .. Handle error
}
}
import (
. "github.com/openfga/go-sdk/client"
"github.com/openfga/go-sdk/credentials"
"os"
)
func main() {
fgaClient, err := NewSdkClient(&ClientConfiguration{
ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example
StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
AuthorizationModelId: os.Getenv("FGA_MODEL_ID"), // optional, recommended to be set for production
Credentials: &credentials.Credentials{
Method: credentials.CredentialsMethodApiToken,
Config: &credentials.Config{
ApiToken: os.Getenv("FGA_API_TOKEN"), // will be passed as the "Authorization: Bearer ${ApiToken}" request header
},
},
})
if err != nil {
// .. Handle error
}
}
import (
openfga "github.com/openfga/go-sdk"
. "github.com/openfga/go-sdk/client"
"github.com/openfga/go-sdk/credentials"
"os"
)
func main() {
fgaClient, err := NewSdkClient(&ClientConfiguration{
ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example
StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
AuthorizationModelId: os.Getenv("FGA_MODEL_ID"), // optional, recommended to be set for production
Credentials: &credentials.Credentials{
Method: credentials.CredentialsMethodClientCredentials,
Config: &credentials.Config{
ClientCredentialsClientId: os.Getenv("FGA_CLIENT_ID"),
ClientCredentialsClientSecret: os.Getenv("FGA_CLIENT_SECRET"),
ClientCredentialsApiAudience: os.Getenv("FGA_API_AUDIENCE"),
ClientCredentialsApiTokenIssuer: os.Getenv("FGA_API_TOKEN_ISSUER"),
},
},
})
if err != nil {
// .. Handle error
}
}
import (
openfga "github.com/openfga/go-sdk"
. "github.com/openfga/go-sdk/client"
"github.com/openfga/go-sdk/credentials"
"os"
)
func main() {
fgaClient, err := NewSdkClient(&ClientConfiguration{
ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example
StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
AuthorizationModelId: os.Getenv("FGA_MODEL_ID"), // optional, recommended to be set for production
Credentials: &credentials.Credentials{
Method: credentials.CredentialsMethodClientCredentials,
Config: &credentials.Config{
ClientCredentialsClientId: os.Getenv("FGA_CLIENT_ID"),
ClientCredentialsClientSecret: os.Getenv("FGA_CLIENT_SECRET"),
ClientCredentialsScopes: os.Getenv("FGA_API_SCOPES"), // optional space separated scopes
ClientCredentialsApiTokenIssuer: os.Getenv("FGA_API_TOKEN_ISSUER"),
},
},
})
if err != nil {
// .. Handle error
}
}
You need your store id to call the OpenFGA API (unless it is to call the CreateStore or ListStores methods).
If your server is configured with authentication enabled, you also need to have your credentials ready.
Get a paginated list of stores.
options := ClientListStoresOptions{
PageSize: openfga.PtrInt32(10),
ContinuationToken: openfga.PtrString("..."),
}
stores, err := fgaClient.ListStores(context.Background()).Options(options).Execute()
// stores = [{ "id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z" }]
Create and initialize a store.
body := ClientCreateStoreRequest{Name: "FGA Demo"}
store, err := fgaClient.CreateStore(context.Background()).Body(body).Execute()
if err != nil {
// handle error
}
// store.Id = "01FQH7V8BEG3GPQW93KTRFR8JB"
// store store.Id in database
// update the storeId of the current instance
fgaClient.SetStoreId(store.Id)
// continue calling the API normally, scoped to this store
Get information about the current store.
options := ClientGetStoreOptions{
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
store, err := fgaClient.GetStore(context.Background()).Options(options)Execute()
if err != nil {
// handle error
}
// store = { "id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z" }
Delete a store.
options := ClientDeleteStoreOptions{
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
_, err := fgaClient.DeleteStore(context.Background()).Options(options).Execute()
if err != nil {
// handle error
}
Read all authorization models in the store.
options := ClientReadAuthorizationModelsOptions{
PageSize: openfga.PtrInt32(10),
ContinuationToken: openfga.PtrString("..."),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
data, err := fgaClient.ReadAuthorizationModels(context.Background()).Options(options).Execute()
// data.AuthorizationModels = [
// { Id: "01GXSA8YR785C4FYS3C0RTG7B1", SchemaVersion: "1.1", TypeDefinitions: [...] },
// { Id: "01GXSBM5PVYHCJNRNKXMB4QZTW", SchemaVersion: "1.1", TypeDefinitions: [...] }];
Create a new authorization model.
Note: To learn how to build your authorization model, check the Docs at https://openfga.dev/docs.
Learn more about the OpenFGA configuration language.
You can use the OpenFGA Syntax Transformer to convert between the friendly DSL and the JSON authorization model.
body := ClientWriteAuthorizationModelRequest{
SchemaVersion: "1.1",
TypeDefinitions: []openfga.TypeDefinition{
{Type: "user", Relations: &map[string]openfga.Userset{}},
{
Type: "document",
Relations: &map[string]openfga.Userset{
"writer": {
This: &map[string]interface{}{},
},
"viewer": {Union: &openfga.Usersets{
Child: &[]openfga.Userset{
{This: &map[string]interface{}{}},
{ComputedUserset: &openfga.ObjectRelation{
Object: openfga.PtrString(""),
Relation: openfga.PtrString("writer"),
}},
},
}},
},
Metadata: &openfga.Metadata{
Relations: &map[string]openfga.RelationMetadata{
"writer": {
DirectlyRelatedUserTypes: &[]openfga.RelationReference{
{Type: "user"},
},
},
"viewer": {
DirectlyRelatedUserTypes: &[]openfga.RelationReference{
{Type: "user"},
},
},
},
},
}},
}
options := ClientWriteAuthorizationModelOptions{
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
data, err := fgaClient.WriteAuthorizationModel(context.Background()).Options(options).Body(body).Execute()
fmt.Printf("%s", data.AuthorizationModelId) // 01GXSA8YR785C4FYS3C0RTG7B1
Read a particular authorization model.
options := ClientReadAuthorizationModelOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString(modelId),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
data, err := fgaClient.ReadAuthorizationModel(context.Background()).Options(options).Execute()
// data = {"authorization_model":{"id":"01GXSA8YR785C4FYS3C0RTG7B1","schema_version":"1.1","type_definitions":[{"type":"document","relations":{"writer":{"this":{}},"viewer":{ ... }}},{"type":"user"}]}} // JSON
fmt.Printf("%s", data.AuthorizationModel.Id) // 01GXSA8YR785C4FYS3C0RTG7B1
Reads the latest authorization model (note: this ignores the model id in configuration).
options := ClientReadLatestAuthorizationModelOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString(modelId),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
data, err := fgaClient.ReadLatestAuthorizationModel(context.Background()).Options(options)Execute()
// data.AuthorizationModel.Id = "01GXSA8YR785C4FYS3C0RTG7B1"
// data.AuthorizationModel.SchemaVersion = "1.1"
// data.AuthorizationModel.TypeDefinitions = [{ "type": "document", "relations": { ... } }, { "type": "user", "relations": { ... }}]
fmt.Printf("%s", (*data.AuthorizationModel).GetId()) // 01GXSA8YR785C4FYS3C0RTG7B1
Reads the list of historical relationship tuple writes and deletes.
body := ClientReadChangesRequest{
Type: "document",
}
options := ClientReadChangesOptions{
PageSize: openfga.PtrInt32(10),
ContinuationToken: openfga.PtrString("eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
data, err := fgaClient.ReadChanges(context.Background()).Body(body).Options(options).Execute()
// data.ContinuationToken = ...
// data.Changes = [
// { TupleKey: { User, Relation, Object }, Operation: TupleOperation.WRITE, Timestamp: ... },
// { TupleKey: { User, Relation, Object }, Operation: TupleOperation.DELETE, Timestamp: ... }
// ]
Reads the relationship tuples stored in the database. It does not evaluate nor exclude invalid tuples according to the authorization model.
// Find if a relationship tuple stating that a certain user is a viewer of a certain document
body := ClientReadRequest{
User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("viewer"),
Object: openfga.PtrString("document:roadmap"),
}
// Find all relationship tuples where a certain user has a relationship as any relation to a certain document
body := ClientReadRequest{
User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
Object: openfga.PtrString("document:roadmap"),
}
// Find all relationship tuples where a certain user is a viewer of any document
body := ClientReadRequest{
User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("viewer"),
Object: openfga.PtrString("document:"),
}
// Find all relationship tuples where any user has a relationship as any relation with a particular document
body := ClientReadRequest{
Object: openfga.PtrString("document:roadmap"),
}
// Read all stored relationship tuples
body := ClientReadRequest{}
options := ClientReadOptions{
PageSize: openfga.PtrInt32(10),
ContinuationToken: openfga.PtrString("eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ=="),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
data, err := fgaClient.Read(context.Background()).Body(requestBody).Options(options).Execute()
// In all the above situations, the response will be of the form:
// data = { Tuples: [{ Key: { User, Relation, Object }, Timestamp }, ...]}
Create and/or delete relationship tuples to update the system state.
By default, write runs in a transaction mode where any invalid operation (deleting a non-existing tuple, creating an existing tuple, one of the tuples was invalid) or a server error will fail the entire operation.
body := ClientWriteRequest{
Writes: &[]ClientTupleKey{ {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "viewer",
Object: "document:roadmap",
}, {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "viewer",
Object: "document:budget",
} },
Deletes: &[]ClientTupleKeyWithoutCondition{ {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "writer",
Object: "document:roadmap",
} }
}
options := ClientWriteOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
data, err := fgaClient.Write(context.Background()).Body(body).Options(options).Execute()
Convenience WriteTuples
and DeleteTuples
methods are also available.
The SDK will split the writes into separate chunks and send them in separate requests. Each chunk is a transaction. By default, each chunk is set to 1, but you may override that.
body := ClientWriteRequest{
Writes: &[]ClientTupleKey{ {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "viewer",
Object: "document:roadmap",
}, {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "viewer",
Object: "document:budget",
} },
Deletes: &[]ClientTupleKeyWithoutCondition{ {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "writer",
Object: "document:roadmap",
} }
}
options := ClientWriteOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
Transaction: &TransactionOptions{
Disable: true,
MaxParallelRequests: 5, // Maximum number of requests to issue in parallel
MaxPerChunk: 1, // Maximum number of requests to be sent in a transaction in a particular chunk
},
}
data, err := fgaClient.Write(context.Background()).Body(body).Options(options).Execute()
// data.Writes = [{
// TupleKey: { User, Relation, Object },
// Status: "CLIENT_WRITE_STATUS_SUCCESS
// HttpResponse: ... // http response"
// }, {
// TupleKey: { User, Relation, Object },
// Status: "CLIENT_WRITE_STATUS_FAILURE
// HttpResponse: ... // http response"
// Error: ...
// }]
// data.Deletes = [{
// TupleKey: { User, Relation, Object },
// Status: "CLIENT_WRITE_STATUS_SUCCESS
// HttpResponse: ... // http response"
// }]
Check if a user has a particular relation with an object.
Provide a tuple and ask the OpenFGA API to check for a relationship
body := ClientCheckRequest{
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "viewer",
Object: "document:roadmap",
ContextualTuples: &[]ClientTupleKey{ {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "editor",
Object: "document:roadmap",
} },
}
options := ClientCheckOptions{
AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
data, err := fgaClient.Check(context.Background()).Body(body).Options(options).Execute()
// data = {"allowed":true,"resolution":""} // in JSON
fmt.Printf("%t", data.GetAllowed()) // True
Run a set of checks. Batch Check will return allowed: false
if it encounters an error, and will return the error in the body.
If 429s or 5xxs are encountered, the underlying check will retry up to 15 times before giving up.
options := ClientBatchCheckOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
MaxParallelRequests: openfga.PtrInt32(5), // Max number of requests to issue in parallel, defaults to 10
}
body := ClientBatchCheckBody{ {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "viewer",
Object: "document:roadmap",
ContextualTuples: &[]ClientTupleKey{ {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "editor",
Object: "document:roadmap",
} },
}, {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "admin",
Object: "document:roadmap",
ContextualTuples: &[]ClientTupleKey{ {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "editor",
Object: "document:roadmap",
} },
}, {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "creator",
Object: "document:roadmap",
}, {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "deleter",
Object: "document:roadmap",
} }
data, err := fgaClient.BatchCheck(context.Background()).Body(requestBody).Options(options).Execute()
/*
data = [{
Allowed: false,
Request: {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "viewer",
Object: "document:roadmap",
ContextualTuples: [{
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "editor",
Object: "document:roadmap"
}]
},
HttpResponse: ...
}, {
Allowed: false,
Request: {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "admin",
Object: "document:roadmap",
ContextualTuples: [{
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "editor",
Object: "document:roadmap"
}]
},
HttpResponse: ...
}, {
Allowed: false,
Request: {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "creator",
Object: "document:roadmap",
},
HttpResponse: ...,
Error: <FgaError ...>
}, {
Allowed: true,
Request: {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "deleter",
Object: "document:roadmap",
}},
HttpResponse: ...,
]
*/
Expands the relationships in userset tree format.
options := ClientExpandOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
body := ClientExpandRequest{
Relation: "viewer",
Object: "document:roadmap",
}
data, err := fgaClient.Expand(context.Background()).Body(requestBody).Options(options).Execute()
// data.Tree.Root = {"name":"document:roadmap#viewer","leaf":{"users":{"users":["user:81684243-9356-4421-8fbf-a4f8d36aa31b","user:f52a4f7a-054d-47ff-bb6e-3ac81269988f"]}}}
List the objects of a particular type a user has access to.
options := ClientListObjectsOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
body := ClientListObjectsRequest{
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "can_read",
Type: "document",
ContextualTuples: &[]ClientTupleKey{ {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "editor",
Object: "folder:product",
}, {
User: "folder:product",
Relation: "parent",
Object: "document:roadmap",
} },
}
data, err := fgaClient.ListObjects(context.Background()).
Body(requestBody).
Options(options).
Execute()
// data.Objects = ["document:roadmap"]
List the relations a user has on an object.
options := ClientListRelationsOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
// Max number of requests to issue in parallel, defaults to 10
MaxParallelRequests: openfga.PtrInt32(5),
}
body := ClientListRelationsRequest{
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Object: "document:roadmap",
Relations: []string{"can_view", "can_edit", "can_delete", "can_rename"},
ContextualTuples: &[]ClientTupleKey{ {
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "editor",
Object: "document:roadmap",
} },
}
data, err := fgaClient.ListRelations(context.Background()).
Body(requestBody).
Options(options).
Execute()
// data.Relations = ["can_view", "can_edit"]
List the users who have a certain relation to a particular type.
options := ClientListRelationsOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
// Max number of requests to issue in parallel, defaults to 10
MaxParallelRequests: openfga.PtrInt32(5),
}
// Only a single filter is allowed by the API for the time being
userFilters := []openfga.UserTypeFilter{{ Type: "user" }}
// user filters can also be of the form
// userFilters := []openfga.UserTypeFilter{{ Type: "team", Relation: openfga.PtrString("member") }}
requestBody := ClientListUsersRequest{
Object: openfga.FgaObject{
Type: "document",
Id: "roadmap",
},
Relation: "can_read",
UserFilters: userFilters,
ContextualTuples: []ClientContextualTupleKey{{
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "editor",
Object: "folder:product",
}, {
User: "folder:product",
Relation: "parent",
Object: "document:roadmap",
}},
Context: &map[string]interface{}{"ViewCount": 100},
}
data, err := fgaClient.ListRelations(context.Background()).
Body(requestBody).
Options(options).
Execute()
// response.users = [{object: {type: "user", id: "81684243-9356-4421-8fbf-a4f8d36aa31b"}}, {userset: { type: "user" }}, ...]
Read assertions for a particular authorization model.
options := ClientReadAssertionsOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId: openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
data, err := fgaClient.ReadAssertions(context.Background()).
Options(options).
Execute()
Update the assertions for a particular authorization model.
options := ClientWriteAssertionsOptions{
// You can rely on the model id set in the configuration or override it for this specific request
AuthorizationModelId: openfga.PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
// You can rely on the store id set in the configuration or override it for this specific request
StoreId:openfga.PtrString("01FQH7V8BEG3GPQW93KTRFR8JB"),
}
requestBody := ClientWriteAssertionsRequest{
ClientAssertion{
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "can_view",
Object: "document:roadmap",
Expectation: true,
},
}
data, err := fgaClient.WriteAssertions(context.Background()).
Body(requestBody).
Options(options).
Execute()
If a network request fails with a 429 or 5xx error from the server, the SDK will automatically retry the request up to 15 times with a minimum wait time of 100 milliseconds between each attempt.
To customize this behavior, create an openfga.RetryParams
struct and assign values to the MaxRetry
and MinWaitInMs
fields. MaxRetry
determines the maximum number of retries (up to 15), while MinWaitInMs
sets the minimum wait time between retries in milliseconds.
Apply your custom retry values by passing this struct to the ClientConfiguration
struct's RetryParams
parameter.
import (
"os"
openfga "github.com/openfga/go-sdk"
. "github.com/openfga/go-sdk/client"
)
func main() {
fgaClient, err := NewSdkClient(&ClientConfiguration{
ApiUrl: os.Getenv("FGA_API_URL"), // required, e.g. https://api.fga.example
StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
AuthorizationModelId: os.Getenv("FGA_MODEL_ID"), // optional, recommended to be set for production
RetryParams: &openfga.RetryParams{
MaxRetry: 3, // retry up to 3 times on API requests
MinWaitInMs: 250, // wait a minimum of 250 milliseconds between requests
},
})
if err != nil {
// .. Handle error
}
}
Class | Method | HTTP request | Description |
---|---|---|---|
OpenFgaApi | Check | Post /stores/{store_id}/check | Check whether a user is authorized to access an object |
OpenFgaApi | CreateStore | Post /stores | Create a store |
OpenFgaApi | DeleteStore | Delete /stores/{store_id} | Delete a store |
OpenFgaApi | Expand | Post /stores/{store_id}/expand | Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship |
OpenFgaApi | GetStore | Get /stores/{store_id} | Get a store |
OpenFgaApi | ListObjects | Post /stores/{store_id}/list-objects | List all objects of the given type that the user has a relation with |
OpenFgaApi | ListStores | Get /stores | List all stores |
OpenFgaApi | ListUsers | Post /stores/{store_id}/list-users | List the users matching the provided filter who have a certain relation to a particular type. |
OpenFgaApi | Read | Post /stores/{store_id}/read | Get tuples from the store that matches a query, without following userset rewrite rules |
OpenFgaApi | ReadAssertions | Get /stores/{store_id}/assertions/{authorization_model_id} | Read assertions for an authorization model ID |
OpenFgaApi | ReadAuthorizationModel | Get /stores/{store_id}/authorization-models/{id} | Return a particular version of an authorization model |
OpenFgaApi | ReadAuthorizationModels | Get /stores/{store_id}/authorization-models | Return all the authorization models for a particular store |
OpenFgaApi | ReadChanges | Get /stores/{store_id}/changes | Return a list of all the tuple changes |
OpenFgaApi | Write | Post /stores/{store_id}/write | Add or delete tuples from the store |
OpenFgaApi | WriteAssertions | Put /stores/{store_id}/assertions/{authorization_model_id} | Upsert assertions for an authorization model ID |
OpenFgaApi | WriteAuthorizationModel | Post /stores/{store_id}/authorization-models | Create a new authorization model |
- AbortedMessageResponse
- Any
- Assertion
- AssertionTupleKey
- AuthorizationModel
- CheckRequest
- CheckRequestTupleKey
- CheckResponse
- Computed
- Condition
- ConditionMetadata
- ConditionParamTypeRef
- ConsistencyPreference
- ContextualTupleKeys
- CreateStoreRequest
- CreateStoreResponse
- Difference
- ErrorCode
- ExpandRequest
- ExpandRequestTupleKey
- ExpandResponse
- FgaObject
- GetStoreResponse
- InternalErrorCode
- InternalErrorMessageResponse
- Leaf
- ListObjectsRequest
- ListObjectsResponse
- ListStoresResponse
- ListUsersRequest
- ListUsersResponse
- Metadata
- Node
- Nodes
- NotFoundErrorCode
- NullValue
- ObjectRelation
- PathUnknownErrorMessageResponse
- ReadAssertionsResponse
- ReadAuthorizationModelResponse
- ReadAuthorizationModelsResponse
- ReadChangesResponse
- ReadRequest
- ReadRequestTupleKey
- ReadResponse
- RelationMetadata
- RelationReference
- RelationshipCondition
- SourceInfo
- Status
- Store
- Tuple
- TupleChange
- TupleKey
- TupleKeyWithoutCondition
- TupleOperation
- TupleToUserset
- TypeDefinition
- TypeName
- TypedWildcard
- UnauthenticatedResponse
- UnprocessableContentErrorCode
- UnprocessableContentMessageResponse
- User
- UserTypeFilter
- Users
- Userset
- UsersetTree
- UsersetTreeDifference
- UsersetTreeTupleToUserset
- UsersetUser
- Usersets
- ValidationErrorMessageResponse
- WriteAssertionsRequest
- WriteAuthorizationModelRequest
- WriteAuthorizationModelResponse
- WriteRequest
- WriteRequestDeletes
- WriteRequestWrites
This SDK supports producing metrics that can be consumed as part of an OpenTelemetry setup. For more information, please see the documentation
If you have found a bug or if you have a feature request, please report them on the sdk-generator repo issues section. Please do not report security vulnerabilities on the public GitHub issue tracker.
While we accept Pull Requests on this repository, the SDKs are autogenerated so please consider additionally submitting your Pull Requests to the sdk-generator and linking the two PRs together and to the corresponding issue. This will greatly assist the OpenFGA team in being able to give timely reviews as well as deploying fixes and updates to our other SDKs as well.
This project is licensed under the Apache-2.0 license. See the LICENSE file for more info.
The code in this repo was auto generated by OpenAPI Generator from a template based on the go template, licensed under the Apache License 2.0.
This repo bundles some code from the golang.org/x/oauth2 package. You can find the code here and corresponding BSD-3 License.