What is the correct syntax for creating a user and populating the role?

System Information
  • 4.x:
  • MySQL:

Hi,

I am trying to create a user (table: up_users) and set the role, but the role is not set. What is the correct syntax to set the role?

I have tried the following:

const entry = await strapi.entityService.create('plugin::users-permissions.user', {
	data: { username: name, email: email, provider: 'local', password: pwd_hash, confirmationToken: null, confirmed: false, blocked: false, },
	populate: {
		role: {
			where: {
				type: 'user'
			}
		},
	}
})
const entry = await strapi.entityService.create('plugin::users-permissions.user', {
	data: { username: name, email: email, provider: 'local', password: pwd_hash, confirmationToken: null, confirmed: false, blocked: false, },
	populate: {
		role: {
			type: 'user'
		},
	}
})
const entry = await strapi.db.query('plugin::users-permissions.user').create({
	data: { username: name, email: email, provider: 'local', password: pwd_hash, confirmationToken: null, confirmed: false, blocked: false, },
	populate: {
		role: {
			where: {
				type: 'user'
			}
		},
	},
})

I also found the following page in the Strapi documentation (https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/entity-service/components-dynamic-zones.html#creation), but it doesn’t get me anywhere either.

Here is what I am doing in my unit tests

const users = [
  { username: "authenticated", email: "authd@test.com", provider: "local", password: "test1234", role: "authenticated" },
  { username: "contributor", email: "contrib@test.com", provider: "local", password: "test1234" , role: "contributor" },
];

async  function createUsers(strapi){
  await Promise.all(
    users.map(async (user) => {
      // fetch role by type to get ID
      if ( user.role) {
        const foundRole = await strapi.query("plugin::users-permissions.role").findOne({where: {type: user.role}});
        if (!foundRole) throw Error(`role ${user.role} does not exist`);
        user.role = foundRole.id;
      }
      const { id } = await strapi.plugins['users-permissions'].services.user.add({
        ...user,
        blocked: false,
        confirmed: true,
        created_by: 1, //user admin id
        updated_by: 1, //user admin id
      });
      // Mutate user add jwt for later..
      user.jwt =  await strapi.service('plugin::users-permissions.jwt').issue({ id })
      }
  ));
}

FYi the user.add service seems to properly hash the password as well.

This has been a help.

I am looking to give a role permissions. I have tons of collections I would like a role to have access to but I cant see a way to do this.

Thank you for your answer, @jgielstra.

This is my approach:

const sql_getRole = `SELECT * FROM up_roles WHERE type LIKE ${escape('user')}`
const res_all_getRole = await strapi.db.connection.context.raw( sql_getRole )
const res_getRole = res_all_getRole[0]
if ( res_getRole.length <= 0 )
{
	return ctx.badRequest(null, 'Internal error: User role not found!')
}
const user_role = res_getRole[0]

...

const sql_setRole = `INSERT INTO up_users_role_links (user_id, role_id) VALUES (${user_id}, ${user_role.id})`
const res_setRole = await strapi.db.connection.context.raw( sql_setRole )
const user_role_id = _.get(res_setRole, '[0].insertId', null)
if ( user_role_id === null )
{
	return ctx.badRequest(null, 'Internal error (role): Cannot create account!')
}

This solution is not particularly elegant, but it works.