Create Model Permissions

We'll begin by creating ModelPermissions for the users model. We'll create a user role and add a filter that will only allow users to see their own information.

Enable Auto-select

In our browser, let's select the auto-select latest build option. This will ensure we're always seeing the latest build generated by the dev command:

Execute a query

Add ModelPermission

For our users model, we want to introduce an authorization concept we call permissions. This allows you to control which models are accessible to which users — via a model permission — and which fields can be returned using type permissions.

Presently, if we run the following query, we'll see all users' information returned:

query UsersQuery {
app_users {
id
name
}
}

In just a few lines — and with the assistance of LSP powering our extension — we can declaratively restrict access so that a user is only able to see a limited set of their own data.

Open your project in VS Code and find the /app/app_connector/models/Users.hml file.

As you can see below, when we start typing role, LSP kicks in and assists us with creating the following permission which checks the x-hasura-user-id header to only return a specific user's information. We're triggering the auto-complete options using TAB and CTRL+SPACE:

Execute a query

With the guidance of LSP, let's make our ModelPermissions object look like the metadata below in our Users.hml file:

---
kind: ModelPermissions
version: v1
definition:
modelName: Users
permissions:
- role: admin
select:
filter: null
- role: user
select:
filter:
fieldComparison:
field: id
operator: _eq
value:
sessionVariable: x-hasura-user-id

What just happened?

Permissions

With only a few lines of YAML, you added row-level column-level permissions to your API. You can learn more about how to pass these values as session variables using your preferred authentication solution in our auth section.

Next, we'll check out how we can restrict access to specific fields based on role.

Did you find this page helpful?
Start with GraphQL on Hasura for Free
  • ArrowBuild apps and APIs 10x faster
  • ArrowBuilt-in authorization and caching
  • Arrow8x more performant than hand-rolled APIs
Promo
footer illustration
Brand logo
© 2024 Hasura Inc. All rights reserved
Github
Titter
Discord
Facebook
Instagram
Youtube
Linkedin