Create Organization for user on post-login action

Hey guys!

I have a use case of organizations.

The idea i’m trying to achieve is next:

  • User logs/signups into my SPA app.
  • on post-login action organization created from domain name of used email (if it’s not a public email)
  • user being attached to an organization.

Tried to compose this code, but still have no luck.

const uuid4 = require('uuid4');

exports.onExecutePostLogin = async (event, api) => {
  if (event.stats.logins_count > 1) {
    return
  } 
  const ManagementClient = require('auth0').ManagementClient;

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

  const user_domain = (event.user.email.split('@')[1]).split('.')[0]
  if(user_domain){
    const id = uuid4()
    management.organizations.create({id: id, name: user_domain}, function(err) {
      if (err) {
        return
      }
      var params =  { id : id}
      var data = { members: [ event.user.user_id ] }
      management.organizations.addMembers(params, data, function (err) {
        if (err) {
            // Handle error.
        }
      })
    })
  }
  else{
    //pass
  }
};

Thank you!

Hey @artem2 welcome to the community!

Thanks for sharing your code - I haven’t tried it myself yet, but are you getting any errors? Where is it breaking down?

Looking through this again - You won’t be able to assign an id to the newly created organization. You can assign the domain as the name, but will need to omit the id from creating the organization and then use the id in the success response inmanagement.organizations.addMembers().

This code worked for me - Of course it will need tweaking to fit your use case with the domain and event.user.user_id.

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

const management = new ManagementClient({
      domain: my_auth0_domain,
      clientId: xxx,
      clientSecret: xxx
  });
  
const data = {"name": "org28"}
  
management.organizations.create(data, function (err, response) {
  if (err) {
    // Handle error.
    }
    //org created
     var org_id = response.id
     var params =  { id : org_id}
     var data = { members: [ 'auth0|xxxx' ] }

    management.organizations.addMembers(params, data, function (err, response) {
      if (err) {
        // Handle error.
      }
    });
});

Hope this helps!

Hey @tyf thanks for sharing an answer.

I tried the sample of your code, but it’s still does not create an ORG nor attach user to it.

Organization strategy for application looks like this:

The action on newly created user is shown as ‘success’, but in reality nothing has been done:

Even checking the logs after, I can see that the other action, which updates user app metadata has been executed (API Operation “Update User”), but nothing related to organization has been done.

What could be the reason there, and if I should implement this inside of my backend, instead of auth0 post-login actions?

Thank you!

Hey @artem2 no problem, happy to help!

Hmm that’s interesting - I see both API operations in my logging (create org and assign member) using the following Action. Again it’s a bit more simplified version of yours, primarily skipping the domain bit and just hardcoding the org name:

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

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

  const management = new ManagementClient({
      domain: event.secrets.AUTH0_DOMAIN,
      clientId: event.secrets.CLIENT_ID,
      clientSecret: event.secrets.CLIENT_SECRET
  });
  
const data = {"name": "test_org_test"}
const user = event.user.user_id
console.log(`Here's the user ${user}`)
  
management.organizations.create(data, function (err, response) {
  if (err) {
    // Handle error.
    }
    //org created
     var org_id = response.id
     var params =  { id : org_id}
     var data = { members: [ user ] }

    management.organizations.addMembers(params, data, function (err, response) {
      if (err) {
        // Handle error.
      }
    });
});

I’m wondering if it could be breaking down at your user_domain related code or another Action could be causing issues with this one.

Hey!

Thank’s for answering :smiley:

Tested code related to user_domain, it passes perfectly.

Could it be some issues with ManagementClient, because I was struggling to find values for it.

Because the domain, client id and secret were used from SPA app.

Hey @artem2 I apologize for the delayed response here!

That could definitely be an issue - You’ll want to create an M2M app to use for the ManagementClient:

1 Like

Hey @tyf !

Thank you for keeping engagement with my issue, really appreciate this :slight_smile:

Luckily, the guess about M2M app requirement was valid and I was able to resolve this.

To sum it up for anyone who’s gonna google this:

  1. Code is valid as of time of writting.
  2. Use M2M application keys to be able to perform such action.
1 Like

Hey @artem2 thanks for following up with the community, glad you were able to get this sorted! :rocket:

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