We take advantage of Netlify Identity and Apollo client links to pass the user's Bearer token to the GraphQL API running on Netlify functions. This allows us to implement access control on the server using the user object passed in from the Identity service.
Instructor: [00:00] We have a user logged in on the client side, but our server still isn't using that information. This means that whenever somebody hits our site, they'll see everybody's to-dos because we're not name-spacing them by user or doing any access control at all. As we move to a database, this will become more important.
[00:15] Luckily, since we're using netlify-identity, this becomes a lot easier for us. If we pass in a valid barrier token with the authorization header, netlify gives us a user object on the context. We can take advantage of this user object, do access control on the to-dos.
[00:29] The first thing we need to do is add apollo-link context. Apollo-link context is necessary for the setContext function, which we'll use to implement our own authentication link that we'll pass to the apollo client.
[00:40] First, we'll take the HTTP link and move it out. Then we're going to say that we're going to take our off link and concatenate it with the HTTP link to provide our link to the client.
[00:49] Now we can put everything together. We use the setContext function from apollo-link context to get the headers. We spread any headers that already exist into the headers object that we return, and we set up our own authorization header. If we have a token, we set the barrier token, and if we don't, we set the authorization header to an empty string.
[01:07] Because this link's fired on every request, we can use the netlifyIdentity.currentUser() to get the current user, rather than worrying about context, but netlify identity user token is on user.token.access_token.
[01:19] Now that we've taken care of Gatsby browser, we also have to take care of our graphQL API function. There are two contexts here. The context we see here that we're destructuring is the Lambda request context. On the Lambda request context, we'll have a client context and a user if there's a user available.
[01:36] Inside of the user there will be a sub that is the user ID. If we have a user available, we'll return the user ID. If we don't, return an empty object. This allows us to access the user ID inside of our resolvers, which is the second context. In this case, if we don't have a valid user, we're just going to return an empty array.
[01:53] If we do have a valid user, we'll return the to-dos. This will allow us to test to make sure that everything works before we move into putting the state in the database. If we look at the network request or the production site, we can now see that the barrier token is involved.
[02:06] Now we can see that when we have a user, we can see the to-dos still. Note that if we don't have a user like we don't in this GraphQL explorer, we don't see any to-dos.