Skip to content

Instantly share code, notes, and snippets.

@gahabeen
Last active January 21, 2022 16:36
Show Gist options
  • Save gahabeen/089bea4720f7bb8ec8fc47e0eb094ad7 to your computer and use it in GitHub Desktop.
Save gahabeen/089bea4720f7bb8ec8fc47e0eb094ad7 to your computer and use it in GitHub Desktop.
Managing Roles Memberships in Fauna (DB)

Managing Roles Memberships in Fauna (DB) (the hacky way)

The above definitions are a hacky way to manage base role memberships while still being able to do proper check of a Ref roles.

You would manage the memberships predicates by modifying a User-Defined Function. (It doesn't sound amazing but well, until we're able to read a predicate and use it as a Lambda, I see no other way.)

Let me know if you see optimizations ;)

// HasRole - User-Defined Function
CreateFunction({
name: 'HasRole',
body: Query(Lambda(['role', 'ref'], Select(Var('role'), Call('RolesMemberships', [Var('ref')]), false)))
})
// RolesMemberships - User-Defined Function
CreateFunction({
name: 'RolesMemberships',
body: Query(
Lambda(
['ref'],
Let(
{
doc: Get(Var('ref')),
collection: Select('collection', Var('ref'), null)
},
If(IsNull(Var('collection')), Abort('No collection found in the Ref'), {
// Roles Memberships predicates
user: If(Equals(Var('collection'), Collection('users')), true, false)
})
)
)
)
})
// Example of a "user" Role - using the RolesMemberships UDF via HasRole UDF
CreateRole({
name: 'user',
membership: [
{
resource: Collection('users'),
predicate: Lambda('ref', Call('HasRole', 'user', 'ref'))
}
],
// example of privileges
privileges: [
{
resource: Collection('users'),
action: {
read: Lambda(
'ref',
Equals(
Identity(),
Select(['data', 'owner'], Get(Var('ref')))
)
)
}
}
]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment