Access Control
The examples on this page use the db.user and db.post tables from Relations and the typed context from Resolving Queries. They also assume published: t.boolean() in the columns of PostTable and email: t.text().nullable() in the columns of UserTable, declared in the GraphQL types as published: Boolean! and email: String.
Hide fields
To keep a column, such as a password hash, out of every response, list the fields that clients may read in fields, and set allowAllFields: false on the type so that allowAllFields: true of the graph does not expose the rest:
const graph = r.graph<Context>(
{
User: r.table(db.user, {
allowAllFields: false,
fields: { id: true, name: true, posts: true },
}),
Post: r.table(db.post),
},
{ allowAllFields: true },
)See Fields for how fields and allowAllFields combine.
Restrict rows
To restrict which rows a viewer gets, such as only published posts for anonymous viewers, pass modify to the type:
const graph = r.graph<Context>({
User: r.table(db.user),
Post: r.table(db.post, {
modify: (query, { context }) => {
return context.userId ? query : query.where({ published: true })
},
}),
})modify applies to every query of the type: its root queries and each relation that loads it, such as user { posts }.
Mask values per viewer
To return a value only to viewers allowed to see it, pass transform to its field and decide from the context:
const graph = r.graph<Context>({
User: r.table(db.user, {
fields: {
id: true,
name: true,
email: r.field({
transform: (email, _user, { context }) => (context.isAdmin ? email : null),
}),
},
}),
Post: r.table(db.post),
})This check uses only the viewer's context. If a check also needs a column of the row, select that column explicitly.
Currently broken
transform is not applied when the type is loaded through a relation, such as posts { author { email } }, so the client gets the value unmasked. Until it works, check the permission in a GraphQL resolver of the field instead:
const resolvers = {
User: {
email: (user, _args, context) => (context.isAdmin ? user.email : null),
},
}Limit filters
A filter can reference any column of the type, including one missing from fields, so a client can learn a hidden value from which rows match. Enable filters only on types whose columns are all public, or check the keys of the filter before resolving the query.