Rule migration to Actions: adding properties to event.user. Possible?

I’m trying to migrate this rule, which adds three properties directly to the user object, to an action:

function (user, context, callback) {
  if (typeof user.email === "undefined") {
    user.email = user.nameIdAttributes.value;
    if (typeof user.givenName  !== "undefined") {
    	user.given_name = user.givenName;
    	user.family_name = user.sn;
    }
  }
  
  if (typeof user.given_name === "undefined") {
    user.given_name = "";
    user.family_name = "";
  }
  callback(null, user, context);
}

The problem I’m having is, the application expects to find user.email, user.given_name and user.family_name but I don’t see a way to provide this in an action script. I can add user.app_metadata or user.user_metadata, but not user.setCustomClaim (or whatever it would be named) to set these properties directly on the user object.

Is this possible with actions? If so, what’s the trick. If not I’ll have to modify our application to look for these properties somewhere other than where it currently expects to find them.

Hi @tracy.williams!

Welcome to the Auth0 Community!

To add properties directly to the user object (except user_metadata and app_metadata, these have direct methods built into the Actions API object), you can use the Management API in a post-login Action. This Community article details how to call the Management API in Actions: Using the Management API in Actions

That article provides a sample Action for adding a role to a user on their first login. For your use case, you could do something like this:

exports.onExecutePostLogin = async (event, api) => {

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

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

  const params =  { id : event.user.user_id};
  const data = { *the properties you want to update* };

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

Note: This is just a code sample and should be tested in a development environment first.

Also, as mentioned in the Actions Limitations docs, calls made to the Auth0 Management API are rate-limited. Please keep this in mind.

Please let me know if you have any additional questions!

Best,

Mary Beth

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