In this tutorial, you are going to learn how you can trigger a Lambda function on authentication events with AWS Amplify. We are going to add users to a group to make specific data read-only for everyone but its owner.
Note: This article is a tutorial for intermediate developers who are familiar with the basics of Amplify. Do you want to learn how to accelerate the creation of your projects using Amplify π? I recommend beginners to check out Nader Dabit's free course on egghead, or Amplify's 'Getting Started'.
An everyday use case for data is that some data is read-only, and other is not. Currently, the only way- Amplify lets you declare different permissions for users is by using static groups in Cognito and using attributes on the schema. We are going to leverage Amplify's new support for Lambda triggers to add users to a static group upon sign up.
Let's go! π¨π»βπ» I'm going to assume you have a new project ready created with amplify init.
Start by adding authentication to it. (Make sure you have the latest version of the CLI installed! ππ» npm install -g @aws-amplify/cli)
The steps are pretty self-explanatory. We define a Lambda function that triggers after a user confirms her/his sign-up and add the user to the everyone group.
Next, add an API.
Here is how the schema should look like.
Since we didn't specify any operations for the owner, he is free to execute any query or mutation on the todos he owns. Every other user is only able to use the get and list queries on his todos. The available values for the operations key besides read are create, delete and update. Additionally, we add an optional owner attribute to the todo schema because we use it to verify that we are only allowed to read other users' todos. If you make it mandatory by adding a ! you will have to specify the owner manually when you create the todo. Leaving out the ! allows amplify to populate that field for you automatically.
Push your changes.
Now, create two users and add a couple of todos for each of them. You don't have to do that through your code. If you are coding along and want to save time, you can use the Cognito console to create the users and the AppSync console to execute the GraphQL operations. Remember when using the console to add users, the function will NOT be triggered. You will have to add the user to the "everyone" group manually.
If you list the todos, you should see the todos of all users.
But if you try to mutate a todo that is not your own, you should get an error.
The error looks something like this.
Very good! π€ We implemented read-only permissions, and our users get added to a static Cognito group using Lambda triggers.
Learn senior fullstack secrets
Subscribe to my newsletter for weekly updates on new videos, articles, and courses. You'll also get exclusive bonus content and discounts.