Skip to content

Instantly share code, notes, and snippets.

@kiasaki
Last active January 29, 2020 16:25
Show Gist options
  • Save kiasaki/7b9ab3442da190dc5926dba0c262c433 to your computer and use it in GitHub Desktop.
Save kiasaki/7b9ab3442da190dc5926dba0c262c433 to your computer and use it in GitHub Desktop.
FaunaDB role
CreateCollection({name: "users"})
CreateCollection({name: "accounts"})
CreateCollection({name: "items"})
CreateIndex({
name: "allUsers",
source: Collection("users"),
permissions: {read: null},
})
CreateIndex({
name: "allAccounts",
source: Collection("accounts"),
permissions: {read: null},
})
CreateIndex({
name: "allItems",
source: Collection("items"),
permissions: {read: null},
})
CreateIndex({
name: "usersByEmail",
unique: true,
source: Collection("users"),
terms: [{field: ["data", "email"]}]
})
CreateIndex({
name: "accountsByUser",
source: Collection("accounts"),
terms: [{field: ["data", "members"]}],
})
CreateIndex({
name: "itemsByAccountIdAndRev",
source: Collection("items"),
terms: [{field: ["data", "accountId"]}, {field: ["data", "rev"]}],
})
CreateRole({
name: 'main',
membership: [
{
class: Collection('users'),
predicate: Query(Lambda('ref', Select(['data', 'isActive'], Get(Var('ref')), false))),
},
],
privileges: [
{
resource: Collection('users'),
actions: {
create: true,
read: Query(Lambda('ref', Equals(Var('ref'), Identity()))),
write: Query(
Lambda(['oldData', 'newData'], Equals(Select(['ref'], Var('oldData')), Identity()))
),
delete: false,
},
},
{
resource: Collection('accounts'),
actions: {
create: Query(
Lambda('newData', Equals(Select(['data', 'owner'], Var('newData')), Identity()))
),
read: Query(
Lambda(
'ref',
Any(
Map(
Select(['data', 'members'], Get(Var('ref'))),
Lambda('m', Equals(Identity(), Var('m')))
)
)
)
),
write: Query(
Lambda(
['oldData', 'newData'],
Any(
Map(
Select(['data', 'members'], Var('oldData')),
Lambda('m', Equals(Identity(), Var('m')))
)
)
)
),
delete: Query(Lambda('ref', Equals(Identity(), Select(['owner'], Get(Var('ref')))))),
},
},
{
resource: Collection('items'),
actions: {
create: Query(
Lambda(
'newData',
Any(
Map(
Select(['data', 'members'], Get(Select(['accountId'], Var('newData')))),
Lambda('m', Equals(Identity(), Var('m')))
)
)
)
),
read: Query(
Lambda(
'ref',
Any(
Map(
Select(['data', 'members'], Get(Select(['accountId'], Get(Var('ref'))))),
Lambda('m', Equals(Identity(), Var('m')))
)
)
)
),
write: Query(
Lambda(
['oldData', 'newData'],
And(
Any(
Map(
Select(['data', 'members'], Get(Select(['accountId'], Var('oldData')))),
Lambda('m', Equals(Identity(), Var('m')))
)
),
Any(
Map(
Select(['data', 'members'], Get(Select(['accountId'], Var('newData')))),
Lambda('m', Equals(Identity(), Var('m')))
)
)
)
)
),
delete: Query(
Lambda(
'ref',
Any(
Map(
Select(['data', 'members'], Get(Select(['accountId'], Get(Var('ref'))))),
Lambda('m', Equals(Identity(), Var('m')))
)
)
)
),
},
},
],
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment