DGuhr / go-sdk

OpenFGA SDK for Go

Home Page:https://openfga.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Go SDK for OpenFGA

Go Reference Release License FOSSA Status Discord Server Twitter

This is an autogenerated Go SDK for OpenFGA. It provides a wrapper around the OpenFGA API definition.

Table of Contents

About

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.

Resources

Installation

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.

Getting Started

Initializing the API Client

Learn how to initialize your SDK

Without an API Token

import (
    openfga "github.com/openfga/go-sdk"
    "os"
)

func main() {
    configuration, err := openfga.NewConfiguration(openfga.Configuration{
        ApiScheme:      os.Getenv("OPENFGA_API_SCHEME"), // optional, defaults to "https"
        ApiHost:        os.Getenv("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example)
        StoreId:        os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
    })

    if err != nil {
    // .. Handle error
    }

    apiClient := openfga.NewAPIClient(configuration)
}

With an API Token

import (
    openfga "github.com/openfga/go-sdk"
    "os"
)

func main() {
    configuration, err := openfga.NewConfiguration(openfga.Configuration{
        ApiScheme:      os.Getenv("OPENFGA_API_SCHEME"), // optional, defaults to "https"
        ApiHost:        os.Getenv("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example)
        StoreId:        os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
        Credentials: &credentials.Credentials{
            Method: credentials.CredentialsMethodApiToken,
            Config: {
                ApiToken: os.Getenv("OPENFGA_API_TOKEN"), // will be passed as the "Authorization: Bearer ${ApiToken}" request header
            },
        },
    })

    if err != nil {
    // .. Handle error
    }

    apiClient := openfga.NewAPIClient(configuration)
}

Get your Store ID

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.

Calling the API

List Stores

API Documentation

configuration, err := openfga.NewConfiguration(openfga.Configuration{
    ApiHost: "api.fga.example"
})

if err != nil {
// .. Handle error
}

apiClient := openfga.NewAPIClient(configuration)
stores, response, err := apiClient.OpenFgaApi.ListStores(context.Background()).Execute();

// stores = [{ "id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z" }]

Create Store

API Documentation

configuration, err := openfga.NewConfiguration(openfga.Configuration{
    ApiHost: "api.fga.example"
})

if err != nil {
// .. Handle error
}

apiClient := openfga.NewAPIClient(configuration)

store, _, err := apiClient.OpenFgaApi.CreateStore(context.Background()).Body(openfga.CreateStoreRequest{Name: "FGA Demo"}).Execute()
if err != nil {
    // handle error
}

// store.Id = "01FQH7V8BEG3GPQW93KTRFR8JB"

// store store.Id in database
// update the storeId of the current instance
apiClient.SetStoreId(*store.Id)
// continue calling the API normally

Get Store

API Documentation

Requires a client initialized with a storeId

store, _, err := apiClient.OpenFgaApi.GetStore(context.Background()).Execute()
if err != nil {
    // handle error
}

// store = { "id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z" }

Delete Store

API Documentation

Requires a client initialized with a storeId

_, err := apiClient.OpenFgaApi.DeleteStore(context.Background()).Execute()
if err != nil {
    // handle error
}

Write Authorization Model

API Documentation

Note: To learn how to build your authorization model, check the Docs at https://openfga.dev/docs.

Learn more about the OpenFGA configuration language.

body  := openfga.WriteAuthorizationModelRequest{TypeDefinitions: []openfga.TypeDefinition{
	{
		Type: "user",
	},
	{
		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"),
					}},
				},
			}},
		},
	},
}}
data, response, err := apiClient.OpenFgaApi.WriteAuthorizationModel(context.Background()).Body(body).Execute()

fmt.Printf("%s", data.AuthorizationModelId) // 1uHxCSuTP0VKPYSnkq1pbb1jeZw

Read a Single Authorization Model

API Documentation

// Assuming `1uHxCSuTP0VKPYSnkq1pbb1jeZw` is an id of a single model
data, response, err := apiClient.OpenFgaApi.ReadAuthorizationModel(context.Background(), "1uHxCSuTP0VKPYSnkq1pbb1jeZw").Execute()

// data = {"authorization_model":{"id":"1uHxCSuTP0VKPYSnkq1pbb1jeZw","type_definitions":[{"type":"document","relations":{"writer":{"this":{}},"viewer":{ ... }}},{"type":"user"}]}} // JSON

fmt.Printf("%s", data.AuthorizationModel.Id) // 1uHxCSuTP0VKPYSnkq1pbb1jeZw

Read Authorization Model IDs

API Documentation

data, response, err := apiClient.OpenFgaApi.ReadAuthorizationModels(context.Background()).Execute()

// data = {"authorization_model_ids":["1uHxCSuTP0VKPYSnkq1pbb1jeZw","GtQpMohWezFmIbyXxVEocOCxxgq"]} // in JSON

fmt.Printf("%s", (*data.AuthorizationModelIds)[0]) // 1uHxCSuTP0VKPYSnkq1pbb1jeZw

Check

API Documentation

Provide a tuple and ask the OpenFGA API to check for a relationship

body := openfga.CheckRequest{
	TupleKey: openfga.TupleKey{
		User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
		Relation: openfga.PtrString("viewer"),
		Object: openfga.PtrString("document:roadmap"),
	},
	AuthorizationModelId: openfga.PtrString("1uHxCSuTP0VKPYSnkq1pbb1jeZw"),
}
data, response, err := apiClient.OpenFgaApi.Check(context.Background()).Body(body).Execute()

// data = {"allowed":true,"resolution":""} // in JSON

fmt.Printf("%t", *data.Allowed) // True

Write Tuples

API Documentation

body := openfga.WriteRequest{
	Writes: &openfga.TupleKeys{
		TupleKeys: []openfga.TupleKey{
			{
				User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
				Relation: openfga.PtrString("viewer"),
				Object: openfga.PtrString("document:roadmap"),
			},
		},
	},
	AuthorizationModelId: openfga.PtrString("1uHxCSuTP0VKPYSnkq1pbb1jeZw"),
}
_, response, err := apiClient.OpenFgaApi.Write(context.Background()).Body(body).Execute()

Delete Tuples

API Documentation

body := openfga.WriteRequest{
	Deletes: &openfga.TupleKeys{
		TupleKeys: []openfga.TupleKey{
			{
				User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
				Relation: openfga.PtrString("viewer"),
				Object: openfga.PtrString("document:roadmap"),
			},
		},
	},
	AuthorizationModelId: openfga.PtrString("1uHxCSuTP0VKPYSnkq1pbb1jeZw"),
}
_, response, err := apiClient.OpenFgaApi.Write(context.Background()).Body(body).Execute()

Expand

API Documentation

body := openfga.ExpandRequest{
	TupleKey: openfga.TupleKey{
		Relation: openfga.PtrString("viewer"),
		Object: openfga.PtrString("document:roadmap"),
	},
	AuthorizationModelId: openfga.PtrString("1uHxCSuTP0VKPYSnkq1pbb1jeZw"),
}
data, response, err := apiClient.OpenFgaApi.Expand(context.Background()).Body(body).Execute()

// data = {"tree":{"root":{"name":"document:roadmap#viewer","leaf":{"users":{"users":["user:81684243-9356-4421-8fbf-a4f8d36aa31b","user:f52a4f7a-054d-47ff-bb6e-3ac81269988f"]}}}}} // JSON

Read Changes

API Documentation

// Find if a relationship tuple stating that a certain user is a viewer of a certain document
body := openfga.ReadRequest{
    TupleKey: &openfga.TupleKey{
        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 := openfga.ReadRequest{
    TupleKey: &openfga.TupleKey{
        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 := openfga.ReadRequest{
    TupleKey: &openfga.TupleKey{
        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 := openfga.ReadRequest{
    TupleKey: &openfga.TupleKey{
        Object:   openfga.PtrString("document:roadmap"),
    },
}

// Read all stored relationship tuples
body := openfga.ReadRequest{}

data, response, err := apiClient.OpenFgaApi.Read(context.Background()).Body(body).Execute()

// In all the above situations, the response will be of the form:
// data = {"tuples":[{"key":{"user":"...","relation":"...","object":"..."},"timestamp":"..."}]} // JSON

Read Changes (Watch)

API Documentation

data, response, err := apiClient.OpenFgaApi.ReadChanges(context.Background()).
    Type_("document").
    PageSize(25).
    ContinuationToken("eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==").
    Execute()

// response.continuation_token = ...
// response.changes = [
//   { tuple_key: { user, relation, object }, operation: "writer", timestamp: ... },
//   { tuple_key: { user, relation, object }, operation: "viewer", timestamp: ... }
// ]

List Objects

Requires a client initialized with a storeId

API Documentation

body := openfga.ListObjectsRequest{
	AuthorizationModelId: openfga.PtrString("1uHxCSuTP0VKPYSnkq1pbb1jeZw"),
    User:                 "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    Relation:             "viewer",
    Type:                 "document",
	ContextualTuples: &ContextualTupleKeys{
        TupleKeys: []TupleKey{{
            User:     PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
            Relation: PtrString("writer"),
            Object:   PtrString("document:budget"),
        }},
    },
}

data, response, err := apiClient.OpenFgaApi.ListObjects(context.Background()).Body(body).Execute()

// response.objects = ["document:roadmap"]

API Endpoints

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 [EXPERIMENTAL] Get all objects of the given type that the user has a relation with
OpenFgaApi ListStores Get /stores List all stores
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

Models

Contributing

Issues

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.

Pull Requests

All changes made to this repo will be overwritten on the next generation, so we kindly ask that you send all pull requests related to the SDKs to the sdk-generator repo instead.

Author

OpenFGA

License

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.

About

OpenFGA SDK for Go

https://openfga.dev

License:Apache License 2.0


Languages

Language:Go 100.0%