1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
|
package main
import (
"context"
"fmt"
"os"
openfga "github.com/openfga/go-sdk"
"github.com/openfga/go-sdk/client"
"github.com/openfga/go-sdk/credentials"
)
func mainInner() error {
ctx := context.Background()
creds := credentials.Credentials{}
if os.Getenv("FGA_CLIENT_ID") != "" {
creds = credentials.Credentials{
Method: credentials.CredentialsMethodClientCredentials,
Config: &credentials.Config{
ClientCredentialsClientId: os.Getenv("FGA_CLIENT_ID"),
ClientCredentialsClientSecret: os.Getenv("FGA_CLIENT_SECRET"),
ClientCredentialsApiAudience: os.Getenv("FGA_API_AUDIENCE"),
ClientCredentialsApiTokenIssuer: os.Getenv("FGA_API_TOKEN_ISSUER"),
},
}
}
apiUrl := os.Getenv("FGA_API_URL")
if apiUrl == "" {
apiUrl = "http://localhost:8080"
}
fgaClient, err := client.NewSdkClient(&client.ClientConfiguration{
ApiUrl: apiUrl,
StoreId: os.Getenv("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
AuthorizationModelId: os.Getenv("FGA_MODEL_ID"), // optional, recommended to be set for production
Credentials: &creds,
})
if err != nil {
return err
}
// ListStores
fmt.Println("Listing Stores")
stores1, err := fgaClient.ListStores(ctx).Execute()
if err != nil {
return err
}
fmt.Printf("Stores Count: %d\n", len(stores1.GetStores()))
// CreateStore
fmt.Println("Creating Test Store")
store, err := fgaClient.CreateStore(ctx).Body(client.ClientCreateStoreRequest{Name: "Test Store"}).Execute()
if err != nil {
return err
}
fmt.Printf("Test Store ID: %v\n", store.Id)
// Set the store id
fgaClient.SetStoreId(store.Id)
// ListStores after Create
fmt.Println("Listing Stores")
stores, err := fgaClient.ListStores(ctx).Execute()
if err != nil {
return err
}
fmt.Printf("Stores Count: %d\n", len(stores.Stores))
// GetStore
fmt.Println("Getting Current Store")
currentStore, err := fgaClient.GetStore(ctx).Execute()
if err != nil {
return err
}
fmt.Println("Current Store Name: %v\n" + currentStore.Name)
// ReadAuthorizationModels
fmt.Println("Reading Authorization Models")
models, err := fgaClient.ReadAuthorizationModels(ctx).Execute()
if err != nil {
return err
}
fmt.Printf("Models Count: %d\n", len(models.AuthorizationModels))
// ReadLatestAuthorizationModel
latestAuthorizationModel, err := fgaClient.ReadLatestAuthorizationModel(ctx).Execute()
if err != nil {
return err
}
if latestAuthorizationModel.AuthorizationModel != nil {
fmt.Printf("Latest Authorization Model ID: %v\n", (*latestAuthorizationModel.AuthorizationModel).Id)
} else {
fmt.Println("Latest Authorization Model not found")
}
// WriteAuthorizationModel
fmt.Println("Writing an Authorization Model")
body := client.ClientWriteAuthorizationModelRequest{
SchemaVersion: "1.1",
TypeDefinitions: []openfga.TypeDefinition{
{
Type: "user",
Relations: &map[string]openfga.Userset{},
},
{
Type: "document",
Relations: &map[string]openfga.Userset{
"writer": {This: &map[string]interface{}{}},
"viewer": {Union: &openfga.Usersets{
Child: []openfga.Userset{
{This: &map[string]interface{}{}},
{ComputedUserset: &openfga.ObjectRelation{
Object: openfga.PtrString(""),
Relation: openfga.PtrString("writer"),
}},
},
}},
},
Metadata: &openfga.Metadata{
Relations: &map[string]openfga.RelationMetadata{
"writer": {
DirectlyRelatedUserTypes: &[]openfga.RelationReference{
{Type: "user"},
{Type: "user", Condition: openfga.PtrString("ViewCountLessThan200")},
},
},
"viewer": {
DirectlyRelatedUserTypes: &[]openfga.RelationReference{
{Type: "user"},
},
},
},
},
},
},
Conditions: &map[string]openfga.Condition{
"ViewCountLessThan200": {
Name: "ViewCountLessThan200",
Expression: "ViewCount < 200",
Parameters: &map[string]openfga.ConditionParamTypeRef{
"ViewCount": {
TypeName: openfga.TYPENAME_INT,
},
"Type": {
TypeName: openfga.TYPENAME_STRING,
},
"Name": {
TypeName: openfga.TYPENAME_STRING,
},
},
},
},
}
authorizationModel, err := fgaClient.WriteAuthorizationModel(ctx).Body(body).Execute()
if err != nil {
return err
}
fmt.Printf("Authorization Model ID: %v\n", authorizationModel.AuthorizationModelId)
// ReadAuthorizationModels - after Write
fmt.Println("Reading Authorization Models")
models, err = fgaClient.ReadAuthorizationModels(ctx).Execute()
if err != nil {
return err
}
fmt.Printf("Models Count: %d\n", len(models.AuthorizationModels))
// ReadLatestAuthorizationModel - after Write
latestAuthorizationModel, err = fgaClient.ReadLatestAuthorizationModel(ctx).Execute()
if err != nil {
return err
}
fmt.Printf("Latest Authorization Model ID: %v\n", (*latestAuthorizationModel.AuthorizationModel).Id)
// Write
fmt.Println("Writing Tuples")
_, err = fgaClient.Write(ctx).Body(client.ClientWriteRequest{
Writes: []client.ClientTupleKey{
{
User: "user:anne",
Relation: "writer",
Object: "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
Condition: &openfga.RelationshipCondition{
Name: "ViewCountLessThan200",
Context: &map[string]interface{}{"Name": "Roadmap", "Type": "document"},
},
},
},
}).Options(client.ClientWriteOptions{
AuthorizationModelId: &authorizationModel.AuthorizationModelId,
}).Execute()
if err != nil {
return err
}
fmt.Println("Done Writing Tuples")
// Set the model ID
err = fgaClient.SetAuthorizationModelId(latestAuthorizationModel.AuthorizationModel.Id)
if err != nil {
return err
}
// Read
fmt.Println("Reading Tuples")
readTuples, err := fgaClient.Read(ctx).Execute()
if err != nil {
return err
}
fmt.Printf("Read Tuples: %v\n", readTuples)
// ReadChanges
fmt.Println("Reading Tuple Changes")
readChangesTuples, err := fgaClient.ReadChanges(ctx).Execute()
if err != nil {
return err
}
fmt.Printf("Read Changes Tuples: %v\n", readChangesTuples)
// Check
fmt.Println("Checking for access")
failingCheckResponse, err := fgaClient.Check(ctx).Body(client.ClientCheckRequest{
User: "user:anne",
Relation: "viewer",
Object: "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
}).Execute()
if err != nil {
fmt.Printf("Failed due to: %w\n", err.Error())
} else {
fmt.Printf("Allowed: %v\n", failingCheckResponse.Allowed)
}
// Checking for access with context
fmt.Println("Checking for access with context")
checkResponse, err := fgaClient.Check(ctx).Body(client.ClientCheckRequest{
User: "user:anne",
Relation: "viewer",
Object: "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
Context: &map[string]interface{}{"ViewCount": 100},
}).Execute()
if err != nil {
return err
}
fmt.Printf("Allowed: %v\n", checkResponse.Allowed)
// ListObjects
fmt.Println("Listing objects user has access to")
listObjectsResponse, err := fgaClient.ListObjects(ctx).Body(client.ClientListObjectsRequest{
User: "user:anne",
Relation: "viewer",
Type: "document",
Context: &map[string]interface{}{"ViewCount": 100},
}).Execute()
fmt.Printf("Response: Objects = %v\n", listObjectsResponse.Objects)
// ListRelations
fmt.Println("Listing relations user has with object")
listRelationsResponse, err := fgaClient.ListRelations(ctx).Body(client.ClientListRelationsRequest{
User: "user:anne",
Object: "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
Relations: []string{"viewer"},
}).Execute()
fmt.Printf("Response: Relations = %v\n", listRelationsResponse.Relations)
// ListUsers
fmt.Println("Listing user who have access to object")
listUsersResponse, err := fgaClient.ListUsers(ctx).Body(client.ClientListUsersRequest{
Relation: "viewer",
Object: openfga.FgaObject{
Type: "document",
Id: "roadmap",
},
UserFilters: []openfga.UserTypeFilter{{
Type: "user",
}},
}).Execute()
fmt.Printf("Response: Users = %v\n", listUsersResponse.Users)
// WriteAssertions
_, err = fgaClient.WriteAssertions(ctx).Body([]client.ClientAssertion{
{
User: "user:carl",
Relation: "writer",
Object: "document:budget",
Expectation: true,
Context: &map[string]interface{}{"Name": "Roadmap", "Type": "document"},
ContextualTuples: []client.ClientContextualTupleKey{
{
User: "user:carl",
Relation: "writer",
Object: "document:budget",
},
},
},
{
User: "user:anne",
Relation: "viewer",
Object: "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
Expectation: false,
},
}).Execute()
if err != nil {
return err
}
fmt.Println("Assertions updated")
// ReadAssertions
fmt.Println("Reading Assertions")
assertions, err := fgaClient.ReadAssertions(ctx).Execute()
if err != nil {
return err
}
fmt.Printf("Assertions: %v\n", assertions.GetAssertions())
// DeleteStore
fmt.Println("Deleting Current Store")
_, err = fgaClient.DeleteStore(ctx).Execute()
if err != nil {
return err
}
fmt.Printf("Deleted Store: %v\n", currentStore.Name)
return nil
}
func main() {
if err := mainInner(); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
|