How do I update Netlify identity user's app metadata?

344 Views Asked by At

I am using gotrue-js in react to signup and login users to my netlify identity. I am getting an error called "data":{"code":401,"msg":"Invalid token: signature is invalid"}". I am running this locally (on localhost:8888) and using netlify cli to run the site and run the functions.To be completely clear Im getting a 200 statusCode in the terminal but in the response I get the following error.

Login.js

  const handleSubmit = () => {
        auth.login(login.email,login.password)
        .then(response => {
            const myAuthHeader = "Bearer " + response.token.access_token; //creates the bearer token
            fetch(`/.netlify/functions/update_netlify_user/admin/users/${response.id}`, {
                method: "PUT",
                body: JSON.stringify({}),
                headers: { Authorization: myAuthHeader },
                credentials: "include"
            })
              .then(response => {
                console.log({ response });
              })
          })
      }

update_netlify_user.js

const fetch = require("node-fetch")

exports.handler = async (event, context) => {
  const { identity, user } = context.clientContext;
  const userID = user.sub;
  console.log(context)
  const userUrl = `${identity.url}/admin/users/${userID}`;
  const adminAuthHeader = "Bearer " + identity.token;

  try {
    return fetch(userUrl, {
      method: "PUT",
      headers: { Authorization: adminAuthHeader },
      body: JSON.stringify({ app_metadata: { roles: ["superstar"] } })
    })
      .then(response => {
        return response.json();
      })
      .then(data => {
        console.log("Updated a user! 204!");
        console.log(JSON.stringify({ data }));
        return { statusCode: 204 };
      })
      
  } catch (e) { return e; }
};
0

There are 0 best solutions below