Check a secret’s user-defined roles
Learn: Roles |
---|
This guide covers how to check the user-defined roles assigned to a Fauna authentication secret using a user-defined collection and user-defined functions (UDFs).
-
Create a collection schema for the
RoleCheck
collection:// Defines the `RoleCheck` collection. // The collection will contain a document for each // user-defined role. collection RoleCheck { // Defines the `byName()` index. // Use the index to get `RoleCheck` collection documents by // their `name`. index byName { terms [.name] } }
-
Create function schema for the
currentRoles
andhasRole
UDFs:// Defines the `currentRoles()` UDF. // Return an Array of user-defined roles. // Ex: ["customer", "manager"] function currentRoles() { RoleCheck.all().map(.name).toArray() } // Defines the `hasRole()` UDF. // Takes a role as an argument. Returns `true` or `false`. function hasRole(role) { RoleCheck.byName(role) != null }
Commit the schema to Fauna using a staged schema change.
-
Run the following FQL query with a secret that uses the built-in
admin
orserver
roles. The query populates theRoleCheck
collection with a document for each user-defined role.// Gets all user-defined roles as an Array. let roles = Role.all().toArray() // Creates a `RoleCheck` collection document for // each role in the previous Array. roles.map(role => { RoleCheck.create({ name: role.name }) })
-
Run the following FQL query to add privileges for the new collection and UDFs to existing user-defined roles.
// Gets all user-defined roles as an Array. let roles = Role.all().toArray() // Adds privileges for the new collection and UDFs to each role // in the previous Array. roles.map(role => { let newPrivileges = role.privileges.concat([ { resource: "RoleCheck", actions: { read: "doc => doc.name == '#{role.name}'" } }, { resource: "hasRole", actions: { call: true } }, { resource: "currentRoles", actions: { call: true } } ]) role.update({ privileges: newPrivileges }) })
-
Run the
HasRole()
andCurrentRoles()
in FQL queries using secrets assigned to various roles:// Secret with the built-in `admin` role. currentRoles() // ["customer", "manager"] hasRole("customer") // true hasRole("manager") // true // Secret with the user-defined `customer` role. currentRoles() // ["customer"] hasRole("customer") // true hasRole("manager") // false // Secret with the user-defined `manager` role. currentRoles() // ["manager"] hasRole("customer") // false hasRole("manager") // true
Is this article helpful?
Tell Fauna how the article can be improved:
Visit Fauna's forums
or email docs@fauna.com
Thank you for your feedback!