How can I set the user's role upon registration? #7328

Responses to the discussion on Github


EKarpinsky139d ago

Author

SOLVED: You have to change the register function that comes with Strapi, now located in the ‘node_modules’ directory. Create a new file “Auth.js” in /extensions/controllers (you will have to create the controllers directory as well). In that Auth.js file, copy paste the register function from ‘node_modules/strapi-plugin-users-permissions’, as well as the consts at the top such as lodash, and edit the role declaration into the following line:

const role = await strapi.query(‘role’, ‘users-permissions’).findOne({id: ctx.request.body.role.id}, );

Quite the long approach, so hopefully Strapi will release an easier way of specifying role id on register, instead of just using the default one.


lauriejim139d ago

Maintainer

Thank you for this answer, got a lot of this question. We will probably have to reference that somewhere


EKarpinsky139d ago

Author

My pleasure! Was bugging me since yesterday and even Google had a tough one with this!


derrickmehaffy139d ago

Collaborator

Quite the long approach, so hopefully Strapi will release an easier way of specifying role id on register, instead of just using the default one.

Previously our stance on this has been it can be a security risk so we generally advise against allowing the user to pick their role. I know this isn’t always the case for all users but in the few that I have seen it would have been a pretty major security risk. My suggestion in the past was to register them under the default and then via either an automated review process or manual review to then reassign their role after that.

Either way thank you for the solution you found :slight_smile:


abbeyseto116d ago

Thanks, @EKarpinsky for this solution.

I really needed this feature and was happy this helped me.

Just a point to note, putting the logic in **/extensions/controllers/Auth.js**, the custom roles logic doesn’t work. The default logic from the node_modules was still called. To correct this i tried:

extensions\users-permissions\controllers\Auth.js

and this worked perfectly.

1 Like