Skip to content

Access Control ​

The examples on this page use the UserModel and PostModel models from Relations and the typed context from Resolving Queries. They also assume a published column of post and a nullable email column of user, 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:

ts
const graph = r.graph<Context>(
  {
    User: r.model(UserModel, {
      allowAllFields: false,
      fields: { id: true, name: true, posts: true },
    }),
    Post: r.model(PostModel),
  },
  { 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:

ts
const graph = r.graph<Context>({
  User: r.model(UserModel),
  Post: r.model(PostModel, {
    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:

ts
const graph = r.graph<Context>({
  User: r.model(UserModel, {
    fields: {
      id: true,
      name: true,
      email: r.field({
        transform: (email, _user, { context }) => (context.isAdmin ? email : null),
      }),
    },
  }),
  Post: r.model(PostModel),
})

This check uses only the viewer's context. If a check also needs a column of the row, select that column explicitly.

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.