Open Closed

Need data seeder to add roles and pre-defined permissions #7179


User avatar
0
mahsundag created

Hi,

I want to create a data seeder to add roles and pre-defined permissions.

So, I plan to include two new custom roles and their corresponding permissions.

For instance, "Employer" and "Contractor" as roles, and permissions to access Blazor pages.

I require a step-by-step solution, preferably with existing code tailored to my needs.

Adding a new user and setting existing roles with predefined permissions is my goal.

  • ABP Framework version: v8.0.4
  • UI Type: Blazor Server
  • Database System: EF Core (PostgreSQL)
  • Tiered (for MVC) or Auth Server Separated (for Angular): no
  • Exception message and full stack trace:
  • Steps to reproduce the issue:

1 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    A DataSeedContributor to add two roles and add all permissions to these roles.

    You can give it a try.

    https://docs.abp.io/en/abp/latest/Data-Seeding

    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.Extensions.Options;
    using Volo.Abp.Authorization.Permissions;
    using Volo.Abp.Data;
    using Volo.Abp.DependencyInjection;
    using Volo.Abp.Guids;
    using Volo.Abp.Identity;
    using Volo.Abp.MultiTenancy;
    using Volo.Abp.PermissionManagement;
    using Volo.Abp.Uow;
    
    public class MyDataSeedContributor : IDataSeedContributor, ITransientDependency
    {
        protected IGuidGenerator GuidGenerator { get; }
        protected IIdentityRoleRepository RoleRepository { get; }
        protected IIdentityUserRepository UserRepository { get; }
        protected ILookupNormalizer LookupNormalizer { get; }
        protected IdentityUserManager UserManager { get; }
        protected IdentityRoleManager RoleManager { get; }
        protected ICurrentTenant CurrentTenant { get; }
        protected IOptions<IdentityOptions> IdentityOptions { get; }
        protected IPermissionDefinitionManager PermissionDefinitionManager { get; }
        protected IPermissionDataSeeder PermissionDataSeeder { get; }
    
        public MyDataSeedContributor(
            IGuidGenerator guidGenerator,
            IIdentityRoleRepository roleRepository,
            IIdentityUserRepository userRepository,
            ILookupNormalizer lookupNormalizer,
            IdentityUserManager userManager,
            IdentityRoleManager roleManager,
            ICurrentTenant currentTenant,
            IOptions<IdentityOptions> identityOptions,
            IPermissionDefinitionManager permissionDefinitionManager,
            IPermissionDataSeeder permissionDataSeeder)
        {
            GuidGenerator = guidGenerator;
            RoleRepository = roleRepository;
            UserRepository = userRepository;
            LookupNormalizer = lookupNormalizer;
            UserManager = userManager;
            RoleManager = roleManager;
            CurrentTenant = currentTenant;
            IdentityOptions = identityOptions;
            PermissionDefinitionManager = permissionDefinitionManager;
            PermissionDataSeeder = permissionDataSeeder;
        }
    
        [UnitOfWork]
        public virtual async Task SeedAsync(DataSeedContext context)
        {
            var tenantId = context.TenantId;
            using (CurrentTenant.Change(tenantId))
            {
                await IdentityOptions.SetAsync();
    
                // "Employer" and "Contractor" roles
                const string employerRoleName = "Employer";
                const string contractorRoleName = "Contractor";
    
                var employerRoleNameRole = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName(employerRoleName));
                if (employerRoleNameRole == null)
                {
                    employerRoleNameRole = new IdentityRole(GuidGenerator.Create(), employerRoleName, tenantId)
                    {
                        IsPublic = true
                    };
    
                    (await RoleManager.CreateAsync(employerRoleNameRole)).CheckErrors();
                }
    
                var contractorRoleNameRole = await RoleRepository.FindByNormalizedNameAsync(LookupNormalizer.NormalizeName(contractorRoleName));
                if (contractorRoleNameRole == null)
                {
                    contractorRoleNameRole = new IdentityRole(GuidGenerator.Create(), contractorRoleName, tenantId)
                    {
                        IsPublic = true
                    };
    
                    (await RoleManager.CreateAsync(contractorRoleNameRole)).CheckErrors();
                }
    
                var yourUser = await UserRepository.FindAsync(Guid.NewGuid());//your user id
    
                (await UserManager.AddToRoleAsync(yourUser, employerRoleName)).CheckErrors();
                (await UserManager.AddToRoleAsync(yourUser, contractorRoleName)).CheckErrors();
    
                var multiTenancySide = CurrentTenant.GetMultiTenancySide();
                var allPermissionNames = (await PermissionDefinitionManager.GetPermissionsAsync())
                    .Where(p => p.MultiTenancySide.HasFlag(multiTenancySide))
                    .Select(p => p.Name)
                    .ToArray();
    
                await PermissionDataSeeder.SeedAsync(
                    RolePermissionValueProvider.ProviderName,
                    employerRoleName,
                    allPermissionNames,
                    context?.TenantId
                );
    
                await PermissionDataSeeder.SeedAsync(
                    RolePermissionValueProvider.ProviderName,
                    contractorRoleName,
                    allPermissionNames,
                    context?.TenantId
                );
            }
        }
    }
    
    
Made with ❤️ on ABP v9.1.0-preview. Updated on December 13, 2024, 06:09