|
import { OpenFgaClient } from "@openfga/sdk"; |
|
|
|
(async () => { |
|
const id = crypto.randomUUID().substring(0, 8); |
|
console.log("ID:", id); |
|
|
|
const client = new OpenFgaClient({ |
|
apiUrl: "http://localhost:8080", |
|
}); |
|
const store = await client.createStore({ name: `store-${id}` }); |
|
console.log("Store:", store); |
|
client.storeId = store.id; |
|
|
|
const authorizationModel = await client.writeAuthorizationModel({ |
|
"schema_version": "1.1", |
|
"type_definitions": [ |
|
{ |
|
"type": "admin", |
|
}, |
|
{ |
|
"type": "user", |
|
}, |
|
{ |
|
"type": "document", |
|
"relations": { |
|
"reader": { |
|
"this": {}, |
|
}, |
|
"writer": { |
|
"this": {}, |
|
}, |
|
"owner": { |
|
"this": {}, |
|
}, |
|
}, |
|
"metadata": { |
|
"relations": { |
|
"reader": { |
|
"directly_related_user_types": [ |
|
{ |
|
"type": "user", |
|
}, |
|
], |
|
}, |
|
"writer": { |
|
"directly_related_user_types": [ |
|
{ |
|
"type": "user", |
|
}, |
|
], |
|
}, |
|
"owner": { |
|
"directly_related_user_types": [ |
|
{ |
|
"type": "admin", |
|
}, |
|
], |
|
}, |
|
}, |
|
}, |
|
}, |
|
], |
|
}); |
|
console.log("AuthorizationModel:", authorizationModel); |
|
const { authorization_model_id } = authorizationModel; |
|
|
|
const users = await client.write({ |
|
writes: [ |
|
{ "user": "user:anne", "relation": "reader", "object": "document:A" }, |
|
{ "user": "user:anne", "relation": "reader", "object": "document:Z" }, |
|
{ "user": "user:bob", "relation": "writer", "object": "document:Z" }, |
|
{ "user": "admin:chris", "relation": "owner", "object": "document:Z" }, |
|
], |
|
}, { |
|
authorization_model_id, |
|
}); |
|
console.log("User-Anne:", JSON.stringify(users, null, 2)); |
|
|
|
// ##### Perform a check ##### |
|
// https://openfga.dev/docs/getting-started/perform-check |
|
|
|
const anneIsReader = await client.check({ |
|
user: "user:anne", |
|
relation: "reader", |
|
object: "document:Z", |
|
}, { |
|
authorization_model_id, |
|
}); |
|
console.log("Anne is reader:", anneIsReader); |
|
|
|
const anneIsWriter = await client.check({ |
|
user: "user:anne", |
|
relation: "writer", |
|
object: "document:Z", |
|
}, { |
|
authorization_model_id, |
|
}); |
|
console.log("Anne is writer:", anneIsWriter); |
|
|
|
// ##### Perform a List Objects call ##### |
|
// https://openfga.dev/docs/getting-started/perform-list-objects |
|
|
|
const objects = await client.listObjects({ |
|
user: "user:anne", |
|
relation: "reader", |
|
type: "document", |
|
}, { |
|
authorization_model_id, |
|
}); |
|
console.log("Objects:", objects); |
|
})(); |