Set user role on register

change this
.node_modules@strapi\plugin-users-permissions\server\controllers\auth.js
*but remember, new update can be rewrite this module and delite this added function, to prevent this, use custom controllers.
**with this approach strapi does not return the role string. But there is no need for it, because of security)))

async register(ctx) {
    // ... (previous code)

    // Validate and extract data from the request
    const params = {
      ..._.pick(ctx.request.body, allowedKeys),
      provider: 'local',
    };

    await validateRegisterBody(params);

    // New code here
    const { role: roleName } = ctx.request.body;

    // Use a new variable name if 'role' is already taken
    let userRole;
    if (roleName && roleName !== 'admin') {
      userRole = await strapi.query('plugin::users-permissions.role').findOne({ where: { name: roleName } });
    }
    if (!userRole) {
      userRole = await strapi.query('plugin::users-permissions.role').findOne({ where: { type: settings.default_role } });
    }

    // Create a new user
    const newUser = {
      ...params,
      role: userRole.id, // Use the new variable 'userRole'
      email: params.email.toLowerCase(),
      username: params.username,
      confirmed: !settings.email_confirmation,
    };

    const user = await getService('user').add(newUser);

    // ... (rest of the function)
}

3 Likes