# Auth0 auto user role adder

**URL:** <https://community.auth0.com/t/auth0-auto-user-role-adder/110245>\
**Category:** Get Help\
**Tags:** management-api, roles\
**Created:** [June 29, 2023, 7:40am UTC](https://community.auth0.com/t/auth0-auto-user-role-adder/110245 "2023-06-29T07:40:29Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![dpatrone1](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/dpatrone1/32/48427_2.png) [@dpatrone1](https://community.auth0.com/u/dpatrone1)\
**Post date:** [June 29, 2023, 7:40am UTC](https://community.auth0.com/t/auth0-auto-user-role-adder/110245/1 "2023-06-29T07:40:29Z")

</div>

hi i’m new in the auth0 world and i can’t find any solution of my problem, in this forum there exist some topic discussin about my porblem but their solution did not solved my problem.  
I need to add a role to a user when they first log in with their new accout (email or google, facebook etc…) here is a solution given from another user that seems to be working for him but not for me

```auto
const auth0Sdk = require("auth0");

exports.onExecutePostUserRegistration = async (event, api) => {
  //if (event.stats.logins_count !== 1) {
   // return;
  //}

	const ManagementClient = auth0Sdk.ManagementClient;
  
  var management = new ManagementClient({
      domain: event.secrets.domain,
      clientId: event.secrets.clientId,
      clientSecret: event.secrets.clientSecret,
      scope: "update:users"
  });
  //console.log(management)

  const params = { id : event.user.user_id};
  const data = { "roles" : ["rangerGestUser"]};
  console.log(data)
  console.log(params)
  management.users.assignRoles(params, data, function (err, user) {
    if (err) {
      // Handle error.
				return api.access.deny(err.message);
    }   
      console.log('success')
    
  });
};

```

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [June 29, 2023, 11:36pm UTC](https://community.auth0.com/t/auth0-auto-user-role-adder/110245/3 "2023-06-29T23:36:31Z")

</div>

Hi there @dpatrone1 welcome to the community!

How exactly is the code not working for you? It’s important to note that **Post User Registration** are triggered for Database and Passwordless connections, not for external identity providers (Google, Facebook, or enterprise connections).

---

<div class="post-metadata">

**Author:** ![dpatrone1](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/dpatrone1/32/48427_2.png) [@dpatrone1](https://community.auth0.com/u/dpatrone1)\
**Post date:** [June 30, 2023, 7:06am UTC](https://community.auth0.com/t/auth0-auto-user-role-adder/110245/4 "2023-06-30T07:06:35Z")

</div>

Thank u for your rapid reply, i need to add the role either when a user is registered via external identity providers and when a user registers himself using email. The script provided is not working for email user registration and as u said for external identity provider (now i’m doing it manually).  
I don’t know if the information is useful but the `console.log('success')` line is not printed.

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [June 30, 2023, 10:07pm UTC](https://community.auth0.com/t/auth0-auto-user-role-adder/110245/5 "2023-06-30T22:07:07Z")

</div>

No problem, I’m happy to help where I can!

I’m not seeing the `console.log` either in the Action logging specifically either, but I do see it when using the Real-time Webtask Logs [Extension](https://auth0.com/docs/customize/extensions/real-time-webtask-logs). Here’s an example Post-Login Action that is working for me to add a default role to users on first login. This should function for database connection users as well as social:

```auto
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.clientId,
      clientSecret: event.secrets.clientSecret,
  });

  const params = { id : event.user.user_id};
  const data = { "roles" : ["rol_55l05t7f5n83zx2p"]};

  management.assignRolestoUser(params, data, function (err) {
  if (err) {
    // Handle error.
    console.log(err)
  }
  else {
    console.log(`role ${data} successfully assigned to ${event.user.email}`)
  // User assigned roles.
  }
});

};

```

---

<div class="post-metadata">

**Author:** ![dpatrone1](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/dpatrone1/32/48427_2.png) [@dpatrone1](https://community.auth0.com/u/dpatrone1)\
**Post date:** [July 1, 2023, 9:00am UTC](https://community.auth0.com/t/auth0-auto-user-role-adder/110245/6 "2023-07-01T09:00:31Z")

</div>

thank u, it seems to be a perfect solution but some new problems spawned 🥲, i copied ur code in a new custom action.

i created a new application with type m2m to allow client\_credential grant\_type.  
in the application settings in the apis section i’ve allowed the required permisisons.  
in the custom action, i’ve used client secret and client id from the new m2m application.

from the log the error now is:

```auto
 Bad Request: Invalid request payload input
at /data/_verquire/_node16/@auth0/rule-utilities/0.2.0/node_modules/rest-facade/src/Client.js:402:25
at Request.callback (/data/_verquire/_node16/@auth0/rule-utilities/0.2.0/node_modules/superagent/lib/node/index.js:905:3)
at /data/_verquire/_node16/@auth0/rule-utilities/0.2.0/node_modules/superagent/lib/node/index.js:1126:20
at IncomingMessage.<anonymous> (/data/_verquire/_node16/@auth0/rule-utilities/0.2.0/node_modules/superagent/lib/node/parsers/json.js:22:7)
at IncomingMessage.emit (node:events:539:35)
at IncomingMessage.emit (node:domain:537:15)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
statusCode: 400,
requestInfo: {
method: 'post',
url: 'https://server21.us.auth0.com/api/v2/users/auth0|642d799ca91c546d0a2a378b/roles'
},
originalError: Error: Bad Request
at Request.callback (/data/_verquire/_node16/@auth0/rule-utilities/0.2.0/node_modules/superagent/lib/node/index.js:883:15)
at /data/_verquire/_node16/@auth0/rule-utilities/0.2.0/node_modules/superagent/lib/node/index.js:1126:20
at IncomingMessage.<anonymous> (/data/_verquire/_node16/@auth0/rule-utilities/0.2.0/node_modules/superagent/lib/node/parsers/json.js:22:7)
at IncomingMessage.emit (node:events:539:35)
at IncomingMessage.emit (node:domain:537:15)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
status: 400,
response: Response {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
res: [IncomingMessage],
request: [Request],
req: [ClientRequest],
text: '{"statusCode":400,"error":"Bad Request","message":"Invalid request payload input"}',
body: [Object],
files: undefined,
buffered: true,
headers: [Object],
header: [Object],
statusCode: 400,
status: 400,
statusType: 4,
info: false,
ok: false,
redirect: false,
clientError: true,
serverError: false,
error: [Error],
created: false,
accepted: false,
noContent: false,
badRequest: true,
unauthorized: false,
notAcceptable: false,
forbidden: false,
notFound: false,
unprocessableEntity: false,
type: 'application/json',
charset: 'utf-8',
links: {},
setEncoding: [Function: bound],
redirects: [],
pipe: [Function (anonymous)],
[Symbol(kCapture)]: false
}
}
}

```

thanks in advice  
davide

---

<div class="post-metadata">

**Author:** ![dpatrone1](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/dpatrone1/32/48427_2.png) [@dpatrone1](https://community.auth0.com/u/dpatrone1)\
**Post date:** [July 2, 2023, 4:35pm UTC](https://community.auth0.com/t/auth0-auto-user-role-adder/110245/7 "2023-07-02T16:35:56Z")

</div>

problem solved, i was enterign the role name and not the role\_id in the data payload, now is working!

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [July 3, 2023, 10:08pm UTC](https://community.auth0.com/t/auth0-auto-user-role-adder/110245/8 "2023-07-03T22:08:16Z")

</div>

That’s great to know, and thanks for following up! 🚀

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [July 17, 2023, 10:08pm UTC](https://community.auth0.com/t/auth0-auto-user-role-adder/110245/9 "2023-07-17T22:08:25Z")

</div>

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