Creating new Role (by code) during the Tenant creation process from UI (ABP.IO)

Viewed 235

I am trying to add the creation of roles while I create a new Tenant from the UI on ABP.IO Framework version 4.

From ABP.IO documentation, I found that by using the existing class SaasDataSeedContributor I can "seed" some datas while I am creating a new Tenant.

My issue is that from this class, I do not have permission to use IIdentityRoleAppService.CreateAsync method (Given policy has not granted). So I tried to go through an AppService and use IdentityRoleManager or even IIdentityRoleRepository,but it is not possible to create IdentityRole object as the constructor is inaccessible due to his protection level.

Any thought about it? Is there any another way to do action while creating a tenant appart using SaasDataSeedContributor. Or maybe I am doing something wrong here.

Thanks for your help

1 Answers

Try this.

public class AppRolesDataSeedContributor : IDataSeedContributor, ITransientDependency
{
    private readonly IGuidGenerator _guidGenerator;
    private readonly IdentityRoleManager _identityRoleManager;

    public AppRolesDataSeedContributor(IGuidGenerator guidGenerator, IdentityRoleManager identityRoleManager)
    {
        _guidGenerator = guidGenerator;
        _identityRoleManager = identityRoleManager;
    }


    public async Task SeedAsync(DataSeedContext context)
    {
        if (context.TenantId.HasValue)
        {
            // try this for a single known role
            var role = await _identityRoleManager.FindByNameAsync("new_role");
            if (role == null)
            {
                var identityResult = await _identityRoleManager.CreateAsync(
                    new IdentityRole(_guidGenerator.Create(), "new_role", context.TenantId.Value));
            }


            // or this (not tested) for multiple roles
            /*
             var newRoles = new[] { "role1", "role2" };

            var identityRoles = from r
                    in _identityRoleManager.Roles
                where r.TenantId == context.TenantId.Value
                select r.Name;

            var except = newRoles.Except(identityRoles.ToList());
            foreach (var name in except)
            {
                var identityResult = await _identityRoleManager.CreateAsync(
                    new IdentityRole(_guidGenerator.Create(), name, context.TenantId.Value));
            }
            */

        }

    }
}
Related