Auth0's Management API v2 to update user profile

Hi,

I’m new to auth0 and I’m trying to update my auth0 user profile. I’m following the (Update Auth0 Applications using the Management API) as a guide. I’m able to getUser, but not able to updateUser…below is my code. If anyone can help point out my error, it would be great

Auth0Manager.js

const axios = require('axios');
const ManagementClient = require('auth0').ManagementClient;

/**
 * The module to interact with the Auth0Management API
 *
 * Requirements:
 *  - Have an Auth0 account and an account name.
 *  - Have a management API: https://manage.auth0.com/dashboard/us/{DOMAIN}/apis
 *
 * How this works:
 *  1. Requests an access token using client_id and client_secret
 *  2. Uses the access token to create a new ManagementClient
 *  3. Use the ManagementClient to interact with the API:
 *     https://auth0.github.io/node-auth0/module-management.ManagementClient.html
 *
 * Example usage to get a client:
 *
 * const Auth0Manager = require('./Auth0Manager');
 * Auth0Manager
 *  .init()
 *  .then(() => Auth0Manager.getClient())
 *  .then(client => res.json(client))
 *  .catch(err => res.json({ message: 'There was an error!', ...err }));
 */

module.exports = (function () {
    let managementClient;

    return {
        init,
        getClient,
        getUser,
        updateClient,
        updateUser
    };

    /**
     * Create a management client
     */
    function init() {
        return getToken()
            .then(data => data.access_token)
            .then(token => {
                const managementClient = new ManagementClient({
                    domain: `${process.env.CLIENT_DOMAIN}`,
                    token,
                    audience: `https://${process.env.CLIENT_DOMAIN}/api/v2/`
                });

                // set it so we can use it in our other methods
                this.managementClient = managementClient;
                return true;
            })
            .catch(err => err);
    }

    /**
     * Get an access token from the Auth0 API
     * We will use this access token to connect to the management API
     * To get a token, we need to provide client_id and client_secret
     * Both of these can be found in the APIs section of Auth0 dashboard
     */
    function getToken() {
        // get the info we need
        const clientId = process.env.CLIENT_ID;
        const clientSecret = process.env.CLIENT_SECRET;
        const url = `https://${process.env.CLIENT_DOMAIN}/oauth/token`;

        // make the call to the API via POST
        return axios
            .post(url, {
                client_id: clientId,
                client_secret: clientSecret,
                grant_type: 'client_credentials',
                audience: `https://${process.env.CLIENT_DOMAIN}/api/v2/`
            })
            .then(res => res.data)
            .catch(err => err);
    }

    /**
     * Make a call to the Management API to get all the data for a certain client
     * All the things that are available in the dashboard can be accessed here
     * @param string clientId
     */
    function getClient(clientId = null) {
        if (!clientId) clientId = process.env.CLIENT_ID;

        return this.managementClient
            .getClient({ client_id: clientId })
            .then(client => client)
            .catch(err => err);
    }

    function getUser(user_id = null) {
        if (!user_id) user_id = process.env.USER_ID;

        return this.managementClient
            .getUser({ user_id: user_id })
            .then(user => user)
            .catch(err => err);
    }



    /**
     * Take data and update the Auth0Client
     * This can be used to update the entire client via API instead of in the dashboard
     * Very helpful if moving settings from local to a production environment
     *
     * @param {Object} data     The data that will overwrite anything in our dashboard
     * @param {String} clientId The client that we want to update
     */
    function updateClient(data, clientId = null) {
        if (!clientId) clientId = process.env.CLIENT_ID;

        return this.managementClient
            .updateClient({ client_id: clientId }, data)
            .then(client => client)
            .catch(err => err);
    }

    function updateUser(data, userID = null) {
        if (!userID) userID = process.env.USER_ID;

        return this.managementClient
            .updateUser({ user_id: userID }, data)
            .then(user => user)
            .catch(err => err);
    }

})();

update_user.js

require("dotenv").config();
const Auth0Manager = require("./Auth0Manager");
var fs = require("file-system");

// the new data we want to set
let newData = fs.readFileSync(
  "./dev-data/data/user-data.json",
  "utf8",
  function (err, data) {
    if (err) {
      throw err;
    }
    return data;
  }
);
newData = JSON.parse(newData);
const updatedData = { nickname: `${newData[0].nickname}` };
// const userId = { user_id: `${newData[0].user_id}` };
console.log(newData);
console.log(updatedData);

Auth0Manager.init()
  .then(() => {
    return Auth0Manager.updateUser(updatedData);
  })
  .then((updatedUser) => {
    console.log("updatedUser", updatedUser);
    return updatedUser;
  })
  .catch((err) => ({ message: "There was an error!", ...err }));

Hi @randall2,

Welcome to the Auth0 Community!

I understand you’ve been unsuccessful in updating a user when using the ManagementClient.

After looking through your code, I don’t immediately see an issue that stands out to rationalize why you were unable to update a user.

Because of this, could you please clarify if updating the user with the Management API Patch users by ID with your user-data.json file work successfully?

I have gone ahead and tested this out myself and was able to update the user without any problems, following the https://auth0.github.io/node-auth0/module-management.ManagementClient.html#updateUser as a reference. See below for my tested code.

  const ManagementClient = require('auth0').ManagementClient;

  const management = new ManagementClient({
      domain: event.secrets.domain,
      clientId: event.secrets.client_id,
      clientSecret: event.secrets.client_secret,
  });

  const params =  { id : event.user.user_id};
  const data = { "user_metadata":{"favorite_color": "blue"}};

  try {
    const res = await management.updateUser(params, data)
  } catch (e) {
    console.log(e)
    // Handle error
  }

Given that, I have a hunch that the issue may be related to your JSON data passed in the request.

Looking forward to your reply.

Thanks.

1 Like

Hi Rueben,

Thanks for the reply. After the data was “stringify”, the patch was completed successfully. Thanks for your help!

Randall

1 Like

Hi @randall2,

That’s great! I’m happy to hear that it works now, and thank you for sharing your fix.

Have a great rest of your day!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.